我们正在使用ClosedXML将数据表对象转换为Excel电子表格,以呈现给用户。只需将所有db值(来自NHibernate)分配给字符串,然后按如下所示格式化它们即可构建DataTable对象:
//formatting
EstimatedCost = Currency.SafeToString(Currency.Create(n.EstimatedCost)),
然后,将列类型设置为属性类型,即在所有情况下均为String。
在输出Excel工作表中会发生什么,因为该列设置为货币,但其数字为文本警告,因此无法正确排序。
我的问题是,由于我们将所有数据都构建到一个DataTable中,因此我没有机会正确装饰ClosedXML列。有没有我想到的快速方法?
public const string ExcelDataType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml";
public static MemoryStream GenerateExcelFileFromData(IEnumerable<KeyValuePair<string, DataTable>> tabs, int colWidth = 100)
{
var workbook = new XLWorkbook { ColumnWidth = colWidth };
foreach (var enumerable in tabs)
{
workbook.Worksheets.Add(enumerable.Value, enumerable.Key);
}
...
public static DataTable ConvertToDataTable<T>(IEnumerable<T> varlist, List<string> excludedColumns, bool titleizeColumn = false)
{
var dtReturn = new DataTable();
// column names
PropertyInfo[] oProps = null;
if (varlist == null) return dtReturn;
foreach (T rec in varlist)
{
// Use reflection to get property names, to create table, Only first time, others will follow
if (oProps == null)
{
oProps = rec.GetType().GetProperties();
foreach (PropertyInfo pi in oProps)
{
if (excludedColumns.Contains(pi.Name))
{
continue;
}
var colType = pi.PropertyType;
dtReturn.Columns.Add(new DataColumn(GetColumnName(pi, titleizeColumn), colType));
}
}
DataRow dr = dtReturn.NewRow();
foreach (var pi in oProps.Where(pi => !excludedColumns.Contains(pi.Name)))
{
try
{
dr[GetColumnName(pi, titleizeColumn)] = pi.GetValue(rec, null) ?? DBNull.Value;
}
catch (ArgumentException)
{
dr[GetColumnName(pi, titleizeColumn)] = DBNull.Value;
}
}
dtReturn.Rows.Add(dr);
}
return dtReturn;
您可以通过以下方式设置货币值的格式:
worksheet.Cell(rowIndex, columnIndex).Style.NumberFormat.Format = "$0.00";
worksheet.Cell(rowIndex, columnIndex).DataType = XLCellValues.Number;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句