簡體   English   中英

使用NPOI將圖像插入Excel文件

[英]Insert Image to Excel File Using NPOI

我正在使用C#在Visual Studio 2010中編寫程序,而我正在使用NPOI庫。

我正在嘗試將圖像插入excel文件。 我嘗試了兩種不同的方法,但它們都不起作用。

//Method 1

HSSFPatriarch patriarch = newSheet.CreateDrawingPatriarch() as HSSFPatriarch;
HSSFClientAnchor anchor;
var memoryStream = new MemoryStream();
System.Drawing.Image image = System.Drawing.Image.FromFile("image.jpeg");
image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Gif);
anchor = new HSSFClientAnchor(0, 0, 255, 255, 0, 0, 0, 0);
anchor.AnchorType = 2; //types are 0, 2, and 3. 0 resizes within the cell, 2 doesn't
int index = newWorkbook.AddPicture(memoryStream.ToArray(), PictureType.JPEG);
HSSFPicture signaturePicture = patriarch.CreatePicture(anchor, index) as HSSFPicture; //ERROR

使用方法1,當我嘗試編譯時捕獲異常。 錯誤消息是Object reference not set to an instance of an object ,並且錯誤發生在代碼的最后一行。

//Method 2

byte[] data = File.ReadAllBytes("image.jpeg");
int picInd = newWorkbook.AddPicture(data, XSSFWorkbook.PICTURE_TYPE_JPEG);
XSSFCreationHelper helper = newWorkbook.GetCreationHelper() as XSSFCreationHelper;
XSSFDrawing drawing = newSheet.CreateDrawingPatriarch() as XSSFDrawing;
XSSFClientAnchor anchor = helper.CreateClientAnchor() as XSSFClientAnchor;
anchor.Col1 = 0;
anchor.Row1 = 0;
XSSFPicture pict = drawing.CreatePicture(anchor, picInd) as XSSFPicture;

方法2編譯並運行沒有問題。 但是當我嘗試打開創建的excel文件時,我收到一條消息,說Excel found unreadable content in 'output.xlsx'. Do you want to recover the contents of this workbook? Excel found unreadable content in 'output.xlsx'. Do you want to recover the contents of this workbook? 我恢復了工作簿,仍然沒有顯示圖像。

插入圖像后的下一步是在同一工作簿中Clone工作表。 使用方法2,根本沒有創建克隆表,我不確定一旦圖像問題得到修復,這是否會得到修復。

有人可以幫我這個嗎? 我想知道如何使方法正常工作,或者是否有另一種方法將圖像插入excel文件。

另外,作為一個注釋,我正在使用XSSFWorkbookXSSFSheet等(不是HSSF ),我的輸出文件是.xlsx

任何幫助/建議表示贊賞,謝謝!

你的方法-2很好。 但是你需要添加pict.Resize(); 在最后一行。

byte[] data = File.ReadAllBytes("image.jpeg");
int picInd = newWorkbook.AddPicture(data, XSSFWorkbook.PICTURE_TYPE_JPEG);
XSSFCreationHelper helper = newWorkbook.GetCreationHelper() as XSSFCreationHelper;
XSSFDrawing drawing = newSheet.CreateDrawingPatriarch() as XSSFDrawing;
XSSFClientAnchor anchor = helper.CreateClientAnchor() as XSSFClientAnchor;
anchor.Col1 = 0;
anchor.Row1 = 0;
XSSFPicture pict = drawing.CreatePicture(anchor, picInd) as XSSFPicture;
pict.Resize();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM