要在C#中使用Apache POI的XWPFDocument類插入圖片和圖形,您需要以下步驟:
添加Apache POI依賴項到您的項目中。您可以通過NuGet包管理器搜索Apache POI并添加到項目中。
創建一個XWPFDocument對象并從中獲取圖像數據流。
using NPOI.XWPF.UserModel;
using NPOI.OpenXmlFormats.Wordprocessing;
using System.IO;
XWPFDocument doc = new XWPFDocument();
FileStream imgStream = new FileStream("path_to_image.jpg", FileMode.Open);
byte[] imgBytes = new byte[imgStream.Length];
imgStream.Read(imgBytes, 0, imgBytes.Length);
imgStream.Close();
XWPFParagraph paragraph = doc.CreateParagraph();
XWPFRun run = paragraph.CreateRun();
run.AddPicture(new MemoryStream(imgBytes), (int)PictureType.JPEG, "path_to_image.jpg", Units.ToEMU(300), Units.ToEMU(200));
XWPFParagraph paragraph = doc.CreateParagraph();
XWPFRun run = paragraph.CreateRun();
int id = doc.AddPictureData(new MemoryStream(imgBytes), (int)PictureType.JPEG);
doc.CreatePicture(id, Units.ToEMU(300), Units.ToEMU(200), paragraph);
using (FileStream fs = new FileStream("output.docx", FileMode.Create))
{
doc.Write(fs);
}
這樣就可以在C#中使用XWPFDocument類插入圖片和圖形到Word文檔中。