2015-11-16 54 views
1

我想讓應用程序從字符串類型列表和圖像類型列表中生成一個Excel文件。我有用戶輸入行然後讓,直到G被壓制他們採取截圖等,然後它應該生成Excel與格式文件等等:使用EPPlus將圖像寫入Excel文件

Row 1- Title-0- 
Row 2- Header-1- 
Row 3- Image-0- 
Row 4- Header-2- 
Row 5- Image-1- 
Row 6- Header-3- 
Row 7- Image-2- 
Row 8- Header-4- 
Row 9- Image-3- 
Row 10- Header-5- 
Row 11- Image-4- 

...依此類推,直至對其做所有的收藏品。

我已經創建了列表和列表,並且我知道它們都包含字符串和圖像,然後再按G,因爲我查看了收藏夾調試模式。

這是我到目前爲止的代碼,excel文件看起來是正確的,除了沒有圖像可以看到,但它是重新調整行高度圖片的大小。我以前從未與Images合作過,因此我認爲我可能會錯過重要的東西,但不知道是什麼。

將集合從調用方法傳遞到此方法 字符串集合被命名爲「withHeadersList」, 圖像集合被命名爲「withImgList」。

生成EXCEL方法:

public static bool GenerateTestPlan(List<String> withHeadersList, List<Image> withImgList, string stringOutputPath) 
     { 
      ExcelPackage newExcelPackage = CreateExcelPackage(withHeadersList[0]); 
      ExcelWorksheet newExcelWorksheet = CreateWorkSheet(newExcelPackage, "Sheet1"); 

      SetCellValue(newExcelWorksheet, 1, 1, withHeadersList[0]); //Title 
      newExcelWorksheet.Row(1).Style.Font.Size = 35; 
      newExcelWorksheet.Row(1).Style.Font.Bold = true; 

      int pRowIndex = 3; 
      int hRowIndex = 2; 
      for (int i = 1; i < withHeadersList.Count; i++) 
      { 
       SetCellValue(newExcelWorksheet, hRowIndex, 1, withHeadersList[i]); 
       newExcelWorksheet.Row(hRowIndex).Style.Font.Size = 20; 

       newExcelWorksheet.Row(pRowIndex).Height = withImgList[i - 1].Height;   //Set row height to height of screenshot 


       var img = newExcelWorksheet.Drawings.AddPicture(withHeadersList[i], withImgList[i - 1]); //Add Images (THINK THIS LAST PARAMETER IS THE PROBLEM) 
       img.SetPosition(pRowIndex, Pixel2MTU(2), 1, Pixel2MTU(2)); 
       img.SetSize(withImgList[i - 1].Width, withImgList[i - 1].Height); 

       hRowIndex += 2; 
       pRowIndex += 2; 
      } 

      SaveExcelPackage(newExcelPackage, stringOutputPath); 

      return true; 
     } 

Excel File here 正如你看到的就好像只是沒有被呈現的圖像。

+0

'Pixel2MTU'在做什麼? – Ernie

回答

0

您的問題肯定是這一行:

img.SetPosition(pRowIndex, Pixel2MTU(2), 1, Pixel2MTU(2)); 

我不知道爲什麼要轉換像素的任何考慮SetPosition正在尋找像素偏移。從元數據:

// Summary: 
    //  Set the top left corner of a drawing. Note that resizing columns/rows after 
    //  using this function will effect the position of the drawing 
    // 
    // Parameters: 
    // Row: 
    //  Start row 
    // 
    // RowOffsetPixels: 
    //  Offset in pixels 
    // 
    // Column: 
    //  Start Column 
    // 
    // ColumnOffsetPixels: 
    //  Offset in pixels 
    public void SetPosition(int Row, int RowOffsetPixels, int Column, int ColumnOffsetPixels); 

我會建議剛通過較小的值傳遞,如2,對於RowOffestPixelsColumnOffsetPixels參數:

img.SetPosition(pRowIndex, 2, 1, 2); 

我發現了一個從快速谷歌搜索被稱爲Pixel2MTU(int pixels) on codeproject方法。方法如下:

public int Pixel2MTU(int pixels) 
{ 
    int mtus = pixels * 9525; 
    return mtus; 
} 

如果這是您使用的相同方法,您的圖像可能位於您的excel文檔的最右下角。