EPPlus - LoadFromCollection - 文本转换为数字

Joh*_*tos 5 .net c# excel formatting epplus

我正在用C#编写一个需要导出List<MyObject>到Excel的程序,我正在使用EPPlus这样做.

我的挑战是我的对象有一个属性:

string Prop1 { get; set; }
Run Code Online (Sandbox Code Playgroud)

并且,我需要导出的值之一具有一个值,例如,其形式为Prop1 = "123E4".

挑战在于EPPlus LoadFromCollection方法将其导出到Excel,但Excel使用科学记数法(Outputted value = 1.23E+061230000)将其转换为数字.

我已经尝试将整个列设置为.Style.Numberformat.Format = "@"(以及我能想到的任何其他样式),我甚至尝试在LoadFromCollection调用方法之前和之后设置样式.

我也尝试在字符串前面添加一个'字符,但实际上该字符在该列中的每个单元格中保留,然后使得值不正确以进行分析.

我正在玩我的List转换为DataTable以便使用该LoadFromDataTable方法,但即使这似乎不起作用.

关于如何将其导出为纯文本的任何想法/建议

Ern*_*e S 7

如果你的字符串看起来像数字,Excel会用细胞角落的那些绿色三角形警告你.这假设您正在使用类似的东西将数字(如果它们是数字)转换为字符串.ToString().没有办法在Excel中解决这个问题,但您可以使用XML动画打开该条件的禁用警告消息,因为EPPlus本身没有这种能力.

像这样的东西会这样做:

public class TestObject
{
    public int Col1 { get; set; }
    public int Col2 { get; set; }
    public string Col3 { get; set; }
}

[TestMethod]
public void Number_String_Test()
{
    //Throw in some data
    var datalist = new List<TestObject>();

    for (var i = 0; i < 10; i++)
    {
        datalist.Add(new TestObject
        {
            Col1 = i,
            Col2 = i *10,
            Col3 = (i*10) + "E4"
        });
    }

    //Create a test file
    var fi = new FileInfo(@"c:\temp\numtest.xlsx");
    if (fi.Exists)
        fi.Delete();

    using (var pck = new ExcelPackage(fi))
    {
        var worksheet = pck.Workbook.Worksheets.Add("Sheet1");
        worksheet.Cells.LoadFromCollection(datalist);

        //This would be the variable drawn from the desired cell range
        var range = "C1:C11";

        //Get reference to the worksheet xml for proper namspace
        var xdoc = worksheet.WorksheetXml;

        //Create the import nodes (note the plural vs singular
        var ignoredErrors = xdoc.CreateNode(XmlNodeType.Element, "ignoredErrors", xdoc.DocumentElement.NamespaceURI);
        var ignoredError = xdoc.CreateNode(XmlNodeType.Element, "ignoredError", xdoc.DocumentElement.NamespaceURI);
        ignoredErrors.AppendChild(ignoredError);

        //Attributes for the INNER node
        var sqrefAtt = xdoc.CreateAttribute("sqref");
        sqrefAtt.Value = range;

        var flagAtt = xdoc.CreateAttribute("numberStoredAsText");
        flagAtt.Value = "1";

        ignoredError.Attributes.Append(sqrefAtt);
        ignoredError.Attributes.Append(flagAtt);

        //Now put the OUTER node into the worksheet xml
        xdoc.LastChild.AppendChild(ignoredErrors);

        pck.Save();
    }
}
Run Code Online (Sandbox Code Playgroud)