使用NPOI将图像插入Excel文件

我正在使用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

任何帮助/建议表示赞赏,谢谢!


你的Method-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();
链接地址: http://www.djcxy.com/p/35761.html

上一篇: Insert Image to Excel File Using NPOI

下一篇: Excel VBA WorkSheet.Copy After Excel 2013