for (var index = 0; index < dataTable.Columns.Count; index++)
{
var dataTableColumn = dataTable.Columns[index];
if (dataTableColumn.DataType != typeof(decimal))
continue;
var rangeWithHeader = ws.Column(index + 1).AsRange().RangeUsed();
var rangeWithoutHeader = ws.Range(rangeWithHeader.FirstCell().CellBelow(), rangeWithHeader.LastCell());
rangeWithoutHeader.Style.NumberFormat.Format = "#0.00000000";
}
型 完整样本:
static void Main(string[] args)
{
var wb = new XLWorkbook();
var dataTable = GetTable("Information");
// Add a DataTable as a worksheet
var ws = wb.Worksheets.Add(dataTable);
for (var index = 0; index < dataTable.Columns.Count; index++)
{
var dataTableColumn = dataTable.Columns[index];
if (dataTableColumn.DataType != typeof(decimal))
continue;
var rangeWithHeader = ws.Column(index + 1).AsRange().RangeUsed();
var rangeWithoutHeader = ws.Range(rangeWithHeader.FirstCell().CellBelow(), rangeWithHeader.LastCell());
rangeWithoutHeader.Style.NumberFormat.Format = "#0.00000000";
}
wb.SaveAs("AddingDataTableAsWorksheet.xlsx");
}
static DataTable GetTable(String tableName)
{
DataTable table = new DataTable();
table.TableName = tableName;
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
table.Columns.Add("Dec", typeof(decimal));
table.Rows.Add(25, "Indocin", "David", DateTime.Now, 123m);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now, 123.4m);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now, 123.45m);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now, 123.456m);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now, 123.4567m);
return table;
}
1条答案
按热度按时间eufgjt7s1#
OP确实提到了下面这行,Excel是如何生成的
字符串
这让我相信OP使用的是
ClosedXML
,请参阅他们的github页面中的以下示例https://github.com/ClosedXML/ClosedXML/wiki/Adding-DataTable-as-Worksheet
如果这是正确的,可以添加以下行来格式化所有类型为
decimal
的列。型
完整样本:
型