诀窍是不要将数字作为“原始对象”传递给 EPPlus,而是正确地转换它们。
以下是我在使用 EPPlus 制作的 DataTable-to-Excel 导出方法中的做法:
if (dc.DataType == typeof(int)) ws.SetValue(row, col, !r.IsNull(dc) ? (int)r[dc] : (int?)null);
else if (dc.DataType == typeof(decimal)) ws.SetValue(row, col, !r.IsNull(dc) ? (decimal)r[dc] : (decimal?)null);
else if (dc.DataType == typeof(double)) ws.SetValue(row, col, !r.IsNull(dc) ? (double)r[dc] : (double?)null);
else if (dc.DataType == typeof(float)) ws.SetValue(row, col, !r.IsNull(dc) ? (float)r[dc] : (float?)null);
else if (dc.DataType == typeof(string)) ws.SetValue(row, col, !r.IsNull(dc) ? (string)r[dc] : null);
else if (dc.DataType == typeof(DateTime))
{
if (!r.IsNull(dc))
{
ws.SetValue(row, col, (DateTime)r[dc]);
// Change the following line if you need a different DateTime format
var dtFormat = "dd/MM/yyyy";
ws.Cells[row, col].Style.Numberformat.Format = dtFormat;
}
else ws.SetValue(row, col, null);
}
重要提示:值得注意的是,DateTime 值需要更多的工作才能正确处理,因为我们希望以某种方式对其进行格式化,并且可以说支持 NULL 值column: 上述方法同时满足这两个要求。
我在this post on my blog 中发布了完整的代码示例(使用 EPPlus 将数据表转换为 Excel 文件)。