2013-05-02 98 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)创建列。