简体   繁体   English

如何将 ClosedXML 中的货币格式化为数字

[英]How to format currency in ClosedXML as numeric

we're using ClosedXML to convert datatable objects into Excel spreadsheets for presentation to the user.我们正在使用 ClosedXML 将数据表对象转换为 Excel 电子表格以呈现给用户。 The DataTable object is build simply by assigning all db values (from NHibernate) to strings and then formating them like below: DataTable object 是通过将所有 db 值(来自 NHibernate)分配给字符串然后像下面这样格式化它们来构建的:

  //formatting
EstimatedCost = Currency.SafeToString(Currency.Create(n.EstimatedCost)),

We then set the column type to the property type, ie String in all cases.然后我们将列类型设置为属性类型,即所有情况下的 String。

What happens in the output Excel sheet as that the column is set for currency but has the number as text warning, then it won't sort correctly.在 output Excel 工作表中发生了什么,因为该列设置为货币但具有数字作为文本警告,然后它不会正确排序。

My problem is that since we build all the data into a DataTable, I don't have a chance to decorate the ClosedXML columns correctly.我的问题是,由于我们将所有数据构建到 DataTable 中,所以我没有机会正确装饰 ClosedXML 列。 Is there a quick way to do this that I am not thinking of?有没有一种我没有想到的快速方法?

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;

You can format your currency values this way:您可以通过以下方式格式化您的货币值:

worksheet.Cell(rowIndex, columnIndex).Style.NumberFormat.Format = "$0.00";
worksheet.Cell(rowIndex, columnIndex).DataType = XLCellValues.Number;

You can get all of the columns you know are currency and set the NumberFormat.Format.您可以获取所有您知道的货币列并设置 NumberFormat.Format。 Below is a sample of how it might be done.下面是如何完成的示例。 The correct format to use for US dollar currency is "[$$-en-US]#,##0.00_);[Red]([$$-en-US]#,##0.00)" .用于美元货币的正确格式是"[$$-en-US]#,##0.00_);[Red]([$$-en-US]#,##0.00)" When this format is used, if you open the spreadsheet in Excel and go to Cell Format, you will see it set as Currency.使用此格式时,如果您在 Excel 中打开电子表格并转到单元格格式,您将看到它设置为货币。

    // Assume all columns that have "price" in the heading are currency types and format as currency.
    var priceColumns = table.Columns(c => c.FirstCell().Value.ToString().Contains("price", StringComparison.InvariantCultureIgnoreCase));
    foreach (var priceColumn in priceColumns)
    {
        try
        {
            // Get all the cells in this column, except for the header row
            var cells = priceColumn.Cells(2, rowCount);
            cells.Style.NumberFormat.Format = @"[$$-en-US]#,##0.00_);[Red]([$$-en-US]#,##0.00)";
        }
        catch { } // Exception here means not all of the cells have a numeric value.
    }

One easy way to get the format right is to go to excel itself, choose the format you want your cell to be, then right click in the cell and choose Format Cells, after that you can copy the Format Code from your chosen format and you are good to go.获得正确格式的一种简单方法是 go 到 excel 本身,选择您希望单元格的格式,然后右键单击单元格并选择格式单元格,之后您可以从您选择的格式复制格式代码,然后您对 go 很好。

在此处输入图像描述

// I had to escape double quotes though
string myFormat = "\"$\"#,##0;[RED]-\"$\"#,##0";
worksheet.Cell("A1").Style.NumberFormat.Format = myFormat;
ws.Cell(ro, co).Style.NumberFormat.Format = "[$$-en-US] #,##0.00";
ws.Cell(ro, co).DataType = XLDataType.Number;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM