使用EPPlus在没有科学标记的情况下写入Excel
本文关键字:情况下 Excel EPPlus 使用 | 更新日期: 2023-09-27 18:00:19
我有一个非常简单的问题。我有一个C#应用程序,它可以进行一些数据处理,然后使用EPPlus输出到excel文件。问题是我的一些数字很长,例如,一个数据值可能是20150602125320
,它在excel表中变成2.01506E+13
。我正在努力避免这种情况。将值转换为字符串是可行的,但我需要它们作为数字在excel中进行进一步的操作。有人知道我能在没有科学符号的情况下保持数据的原始形式吗?非常感谢。
您必须设置格式字符串以匹配您要查找的内容:
[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的功能区中看到"内置"格式的一般列表,你可以在这里看到它们,但你不能在应用程序中直接访问它们,因为它们被标记为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>
您需要在单元格上设置Numberformat
。在底层XML中,需要设置的NumFmtId
是1
。
我看不出有什么方法可以直接设置格式Id,而是需要设置格式字符串。这里的文档列出了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));
}
}