0

我正在尝试使用 EPPlus 的库创建一个 excel 表。但是,输出的 excel 文件与代表数字的单元格的关系并不好。

在此处输入图像描述

我正在使用的代码是:

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

有谁可能知道为什么会这样?

4

1 回答 1

0

我知道了。

如果使用 LoadFromDataTable() 方法,则应在其列中键入 DataTable 对象,这意味着您应使用 table.Columns.Add(columnName, columnType); 创建列

于 2013-05-05T07:42:38.707 回答