使用NPOI dll在Excel导出中添加货币格式-不起作用

时间:2019-01-20 12:41:54

标签: c# npoi

我正在使用NPOI dll将数据导出到excel文件中。

数据为金额类型,必须以货币格式显示:$#,###。## 以及日期格式。

我已将格式添加到单元格中。但数据不会以Money / date格式导出到Excel

有答案吗?

这是我的代码:

我尝试了在Google搜索中找到的所有频率格式,但没有任何效果, 仍会以文本而不是货币/日期类型的格式导出到Excel

public enum StyleDataTypes { NotDeclared = 0, Money = 1, Percentage = 2, Number = 3, Date = 4 }

     public class ColumnInfoAttribute : Attribute


 {


    private string displayNoValue = "";

    public string DisplayNoValue
    {
        get { return displayNoValue; }
        set { displayNoValue = value; }
    }

    private StyleDataTypes styleType = StyleDataTypes.NotDeclared;

    public StyleDataTypes StyleType
    {
        get { return styleType; }
        set { styleType = value; }
    }

}


IDataFormat dataFormatCustom = sheet.Workbook.CreateDataFormat();

            ICellStyle dateStyle = sheet.Workbook.CreateCellStyle(); //date
            dateStyle.DataFormat = dataFormatCustom.GetFormat("yyyy/MM/dd HH:mm:ss");

            ICellStyle amountStyle = sheet.Workbook.CreateCellStyle(); //money
            amountStyle.DataFormat = dataFormatCustom.GetFormat("$#,##0.00");

  StyleDataTypes dataType = ((ColumnInfoAttribute)attr).StyleType;   
 switch (dataType)
                    {
                        case StyleDataTypes.Date:
                           cell.CellStyle.DataFormat = dateStyle.DataFormat;
                            break;
                        case StyleDataTypes.Number:
                           cell.SetCellType(CellType.Numeric);
                            break;
                        case StyleDataTypes.Percentage:
                            cell.CellStyle.DataFormat = percentagesStyle.DataFormat;
                            break;
                        case StyleDataTypes.Money:
                            cell.CellStyle.DataFormat = amountStyle.DataFormat;
                            break;
                    }

在Excel字段中,它显示为文本字段,而不像我一样自定义。

1 个答案:

答案 0 :(得分:0)

您不是先创建DataFormat。

尝试此示例

ICellStyle amountStyle = sheet.Workbook.CreateCellStyle(); //money
amountStyle.DataFormat = sheet.Workbook.CreateDataFormat().GetFormat(.GetFormat("$#,##0.00");
相关问题