使用NPOI C#将图像添加到Excel(.xlsx)

时间:2016-12-14 09:19:55

标签: c# excel npoi

我想使用NPOI将图像插入XLSX文件(而不是xls)。 我正在使用XSSFWorkbookXSSFSheet

byte[] data = File.ReadAllBytes("SomeImage.jpg");
int picInd = workbook.AddPicture(data, XSSFWorkbook.PICTURE_TYPE_JPEG);
XSSFCreationHelper helper = workbook.GetCreationHelper() as XSSFCreationHelper;
XSSFDrawing drawing = _sheet.CreateDrawingPatriarch() as XSSFDrawing;
XSSFClientAnchor anchor = helper.CreateClientAnchor() as XSSFClientAnchor;
anchor.Col1 = 1;
anchor.Row1 = 1;
XSSFPicture pict = drawing.CreatePicture(anchor, picInd) as XSSFPicture;

文件已成功保存。但打开它时显示以下错误,单击是,它不显示图像。 enter image description here

1 个答案:

答案 0 :(得分:2)

我得到了解决方案:

byte[] data = File.ReadAllBytes("someImage.png");
int pictureIndex = workbook.AddPicture(data, PictureType.PNG);
ICreationHelper helper = workbook.GetCreationHelper();
IDrawing drawing = _sheet.CreateDrawingPatriarch();
IClientAnchor anchor = helper.CreateClientAnchor();
anchor.Col1 = 0;//0 index based column
anchor.Row1 = 0;//0 index based row
IPicture picture = drawing.CreatePicture(anchor, pictureIndex);
picture.Resize();