Add image to Excel (.xlsx) using NPOI C#

拥有回忆 提交于 2019-12-12 04:32:34

问题


I want to insert image to an XLSX file (not xls) using NPOI. I am using XSSFWorkbook and XSSFSheet

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;

The file is saved successfully. but while opening it showing the following error and on clicking yes, it does not display the image.


回答1:


I got the solution:

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


来源:https://stackoverflow.com/questions/41138848/add-image-to-excel-xlsx-using-npoi-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!