使用EPPlus在没有科学记数法的情况下写入Excel

问题描述 投票:2回答:2

我有一个非常直截了当的问题。我有一个C#应用程序,它执行一些数据处理,然后使用EPPlus输出到excel文件。问题是我的一些数字很长,例如,数据值可能类似于20150602125320,在excel表中会变成2.01506E+13。我试图避免这种情况。将值转换为字符串有效,但我需要它们作为数字,以便在excel中进一步操作。任何人都知道我可以在没有科学记数法的情况下将数据保持原始形式吗?谢谢!

c# excel epplus
2个回答
4
投票

您必须设置格式字符串以匹配您要查找的内容:

[TestMethod]
public void Big_Number_Format()
{
    //http://stackoverflow.com/questions/31124487/write-to-excel-without-scientifc-notation-using-epplus
    var existingFile = new FileInfo(@"c:\temp\temp.xlsx");
    if (existingFile.Exists)
        existingFile.Delete();

    using (var package2 = new ExcelPackage(existingFile))
    {
        var ws = package2.Workbook.Worksheets.Add("Sheet1");
        ws.Cells[1, 1].Value = 20150602125320;
        ws.Cells[1, 2].Value = 20150602125320;

        ws.Cells[1, 1].Style.Numberformat.Format = "0";
        ws.Cells[1, 2].Style.Numberformat.Format = "0.00";
        package2.Save();
    }
}

如果你想看到你在excel功能区中看到的“内置”格式的一般列表,你可以在这里看到它们,但你不能直接在你的app中访问它们,因为它们被标记为internal

https://github.com/JanKallman/EPPlus/blob/master/EPPlus/Style/XmlAccess/ExcelNumberFormatXml.cs#L62

/// <summary>
/// Id for number format
/// 
/// Build in ID's
/// 
/// 0   General 
/// 1   0 
/// 2   0.00 
/// 3   #,##0 
/// 4   #,##0.00 
/// 9   0% 
/// 10  0.00% 
/// 11  0.00E+00 
/// 12  # ?/? 
/// 13  # ??/?? 
/// 14  mm-dd-yy 
/// 15  d-mmm-yy 
/// 16  d-mmm 
/// 17  mmm-yy 
/// 18  h:mm AM/PM 
/// 19  h:mm:ss AM/PM 
/// 20  h:mm 
/// 21  h:mm:ss 
/// 22  m/d/yy h:mm 
/// 37  #,##0 ;(#,##0) 
/// 38  #,##0 ;[Red](#,##0) 
/// 39  #,##0.00;(#,##0.00) 
/// 40  #,##0.00;[Red](#,##0.00) 
/// 45  mm:ss 
/// 46  [h]:mm:ss 
/// 47  mmss.0 
/// 48  ##0.0E+0 
/// 49  @
/// </summary> 

3
投票

你需要在单元格上设置Numberformat。在基础XML中,您需要设置的NumFmtId1

我看不到你可以直接设置格式Id的方法,而是需要设置格式字符串。 documentation here列出(部分)Id和格式字符串之间的映射。在你的情况下,你似乎需要"0"

private static void WriteExcelFile(string path)
{
    using (var package = new ExcelPackage())
    {
        var workbook = package.Workbook;
        var worksheet = workbook.Worksheets.Add("Sheet1");
        var cell = worksheet.Cells["A1"];

        cell.Value = 20150602125320;

        cell.Style.Numberformat.Format = "0";

        //DefaultColWidth just set so you don't end up with #######
        //this is not required
        worksheet.DefaultColWidth = 20;
        package.SaveAs(new System.IO.FileInfo(path));
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.