使用NPOI插入图像到Excel文件

本文关键字:Excel 文件 图像 NPOI 插入 使用 | 更新日期: 2023-09-27 18:07:16

我正在用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?我恢复了工作簿,仍然没有显示图像。

插入图像后的下一步是在同一工作簿中Clone工作表。使用方法2,克隆表根本没有创建,我不确定一旦图像问题得到修复,是否会修复。

有人能帮我一下吗?我想知道如何使这两种方法正常工作,或者是否有另一种方法来插入图像到excel文件。

另外,作为注意,我使用XSSFWorkbook, XSSFSheet等(不是HSSF),我的输出文件是.xlsx

任何帮助/建议是感激的,谢谢!

使用NPOI插入图像到Excel文件

你的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();