2013-05-02 81 views
0

我想創建一個使用EPPlus庫的Excel表。 但是,輸出excel文件與代表數字的單元格沒有很好的關係。GridView到Excel使用EPPlus

enter image description here

我正在使用的代碼是:

using (var pck = new ExcelPackage()) 
{ 
    ExcelWorksheet ws = pck.Workbook.Worksheets.Add(string.IsNullOrEmpty(SpreadsheetName) ? "Report" : SpreadsheetName); 
    ws.Cells["B2"].LoadFromDataTable(gridViewTable, true, OfficeOpenXml.Table.TableStyles.Light1); 

    for (int i = 1; i <= gridViewTable.Columns.Count; i++) 
    { 
     ws.Column(i).AutoFit(); 
    } 

    // ************** 
    //  HEADER 
    // ************** 

    //prepare the range for the column headers 
    string cellRange = "B2:" + Convert.ToChar('B' + gridViewTable.Columns.Count - 1) + 2; 

    //Format the header for columns 
    using (ExcelRange rng = ws.Cells[cellRange]) 
    { 
     rng.Style.WrapText = false; 
     rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; 
     rng.Style.Font.Bold = true; 
     rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid 
     rng.Style.Fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#007A99")); 
     rng.Style.Font.Color.SetColor(Color.White); 
    } 

    // ************ 
    //  DATA 
    // ************ 

    //prepare the range for the rows 
    string rowsCellRange = "B3:" + Convert.ToChar('B' + gridViewTable.Columns.Count - 1) + (gridViewTable.Rows.Count + 1); 

    //Format the rows 
    using (ExcelRange rng = ws.Cells[rowsCellRange]) 
    { 
     rng.Style.WrapText = false; 
     rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left; 
     rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid 
     rng.Style.Fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#B2D1F0")); 
     rng.Style.Font.Color.SetColor(Color.Black); 
    } 

    Response.ClearHeaders(); 
    Response.ClearContent(); 
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
    Response.AddHeader("content-disposition", "attachment; filename=" + (string.IsNullOrEmpty(FileName) ? "Report" : FileName) + ".xlsx"); 
    Response.BinaryWrite(pck.GetAsByteArray()); 
} 

有誰可能知道爲什麼會出現這種情況?

+0

源'DataTable'中受影響列的類型是什麼? – 2013-05-02 14:49:45

+0

我正在將GridView轉換爲DataTable對象。前者擁有帶有標籤的模板字段。數據在Text屬性中表示。但是,我仍然將這些標籤的文本屬性轉換爲Double類型,然後爲DataTable創建相關行。 – Droritos 2013-05-04 12:37:48

回答

0

我明白了。

如果您使用LoadFromDataTable()方法,則應在其列中鍵入DataTable對象,這意味着您應該使用 table.Columns.Add(columnName,columnType)創建列。