我正在使用 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
感谢任何帮助/建议,谢谢!