问题
I'm writing a program in Visual Studio 2010 using C#, and I'm using the NPOI library.
I'm trying to insert an image to the excel file. I tried 2 different methods and neither of them works.
//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
With method 1, and exception was caught when I try to compile. The error message wasObject reference not set to an instance of an object
, and the error occurs at the last line of the code.
//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;
Method 2 compile and run without issues. But when I try to open the created excel file, I got a message saying Excel found unreadable content in 'output.xlsx'. Do you want to recover the contents of this workbook?
I recovered the workbook and still no image was showing.
The next step after inserting the image is to Clone
the sheet in the same workbook. With method 2, the clone sheet was not created at all, I'm not sure if this will be fix once the image issue is fixed.
Can someone please help me with this? I would like to know how I can make either of the method work properly, or if there's another way to insert image to excel file.
Also, as a note, I'm using XSSFWorkbook
, XSSFSheet
, and such (not HSSF
), and my output file is .xlsx
Any help/suggestion is appreciated, Thanks!
回答1:
Your Method-2 is fine. But you need to add pict.Resize();
at the last line.
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();
来源:https://stackoverflow.com/questions/24086803/insert-image-to-excel-file-using-npoi