2016-12-14 79 views
-1

我想使用NPOI將圖像插入到XLSX文件(不是xls)。 我使用XSSFWorkbookXSSFSheet使用NPOI將圖像添加到Excel(.xlsx)C#

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

+0

你有沒有嘗試過google搜索 「NPOI圖像的Excel」 或檢查NPOI的文檔?已經有很多重複的問題 –

+0

其中大部分是針對使用HSSFWorkbook的xls文件。我找不到任何解決方案爲XSSFWorkbook – Sobhan

+0

這一個沒有回答http://stackoverflow.com/questions/24086803/insert-image-to-excel-file-using-npoi – Sobhan

回答

0

我得到了解決:

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