使用NPOI将图像插入Excel文件

时间:2014-06-06 16:38:26

标签: c# image excel 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?我恢复了工作簿但仍然没有显示图像。

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

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

另外,作为备注,我正在使用XSSFWorkbookXSSFSheet等(不是HSSF),我的输出文件是.xlsx

感谢任何帮助/建议,谢谢!

1 个答案:

答案 0 :(得分:1)

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