EPPlus converts Excel Spreadsheet column to random negative value

五迷三道 提交于 2019-12-03 21:38:24

If you don't specify a columns type via the Datatypes property of the ExcelTextFormat object then EPPlus assumes unknown for the column. Since you have fourteen columns and you are having trouble with data in the fourteenth column you'll need to specify types for each prior column. Without knowing your Datatypes I've just listed fourteen instances of eDataTypes.String, but eDataTypes.Number etc. would also work.

EPPlus makes a guess when assigning a type to a column.

private void GenerateSpreadsheet(string id, string csv, string worksheetName)
{
    using (ExcelPackage pck = new ExcelPackage())
    {
        ExcelWorksheet ws = pck.Workbook.Worksheets.Add(worksheetName);

        ws.Cells["A1"].LoadFromText(csv, new ExcelTextFormat { Delimiter = '|', 
            DataTypes = new eDataTypes[] { eDataTypes.String, eDataTypes.String, 
                eDataTypes.String, eDataTypes.String, eDataTypes.String,
                eDataTypes.String, eDataTypes.String, eDataTypes.String,
                eDataTypes.String, eDataTypes.String, eDataTypes.String, 
                eDataTypes.String, eDataTypes.String, eDataTypes.String } }); 

        Response.AddHeader("Content-Disposition",
            String.Format("attachment; filename={0}.xlsx", id));
        Response.ContentType =
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
        Response.BinaryWrite(pck.GetAsByteArray());
        Response.End();
    }
}

It seems to be interpreted as DateTime, maybe a bug.

Try this:

var format = New ExcelTextFormat()
format.Delimiter = '|';
ws.Cells("A1").LoadFromText(csv, format);
var colNumber = 14;
var colRange = ws.Cells(1, colNumber, ws.Dimension.End.Row, colNumber);
colRange.Style.Numberformat.Format = "@";

If that does not work, try to set the format before you LoadFromText the CSV.

For example:

var csv = IO.File.ReadAllText(csvPath);
var ws = pck.Workbook.Worksheets.Add("Test");
var format As New ExcelTextFormat();
format.Delimiter = '|';
// if columns 4 shall not be interpreted like a DateTime 
format.DataTypes = {
    null,
    null,
    null,
    eDataTypes.String
};
var range = ws.Cells("A1").LoadFromText(csv, format);

Note: You must provide a DataType for every column. But i have tested it with null, seem to work if you don't want to specify the type. If it does not compile, feel free to change(manually converted from VB.NET).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!