NPOI以相同的方式格式化所有单元格

edd*_*edd 5 c# excel npoi

请查看以下代码段.我只是打开excel文件,myfile.xlsx然后从类型的对象List<Account>(我的Account对象只有Date,AccountAmount属性)添加行,并使用名称存储文件myoutputfile.xlsx.我希望我写日期的单元格具有日期格式,而我所拥有的单元格则具有数字格式.但是,如果我尝试下面的代码,所有单元格都格式化#.00(日期也是如此).我已经尝试了一切,有人可以告诉我发生了什么事吗?我正在使用NPOI.

    XSSFWorkbook wb;
    var fileName = "C:/tmp/myfile.xlsx";
    var outputFileName = "C:/tmp/myoutputfile.xlsx";
    using (var file = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite))
    {
        wb = new XSSFWorkbook(file);
    }

    XSSFSheet sheet = (XSSFSheet) wb.GetSheetAt(0);
    for (int i = 0; i < accountRecs.Count(); ++i) {
        var rec = accountRecs[i];
        var row = sheet.CreateRow(i);
        var dateCell = row.CreateCell(3);
        dateCell.SetCellValue(rec.Date);
        dateCell.CellStyle.DataFormat = wb.CreateDataFormat().GetFormat("dd/MM/yyyy");
        var accountCell = row.CreateCell(4);
        accountCell.SetCellValue(rec.Account);
        var totalValueCell = row.CreateCell(16);
        totalValueCell.SetCellValue(rec.Amount);
        totalValueCell.CellStyle.DataFormat = wb.CreateDataFormat().GetFormat("#.00");
    }
    using (var file = new FileStream(outputFileName, FileMode.Create, FileAccess.Write))
    {
        wb.Write(file);
        file.Close();
    }
Run Code Online (Sandbox Code Playgroud)

Bri*_*ers 5

这就是为什么它不起作用:CellStyle默认情况下,您创建的单元格共享对同一对象的引用.在循环内部,您DataFormat将该样式实例"dd/MM/yyyy"设置为,然后将其设置DataFormat"#.00".最后一个获胜,因此最终所有数字单元格(日期在Excel中被视为数字值)将被格式化为"#.00".

您需要做的是为日期单元格和金额单元格创建单独的单元格样式,设置DataFormats这些样式,然后将CellStyle每个创建的单元格的属性设置为适当的样式.

试试这样:

    IDataFormat format = wb.CreateDataFormat();

    ICellStyle dateStyle = wb.CreateCellStyle();
    dateStyle.DataFormat = format.GetFormat("dd/MM/yyyy");

    ICellStyle amountStyle = wb.CreateCellStyle();
    amountStyle.DataFormat = format.GetFormat("#.00");

    XSSFSheet sheet = (XSSFSheet)wb.GetSheetAt(0);
    for (int i = 0; i < accountRecs.Count(); ++i)
    {
        var rec = accountRecs[i];
        var row = sheet.CreateRow(i);
        var dateCell = row.CreateCell(3);
        dateCell.SetCellValue(rec.Date);
        dateCell.CellStyle = dateStyle;
        var accountCell = row.CreateCell(4);
        accountCell.SetCellValue(rec.Account);
        var totalValueCell = row.CreateCell(16);
        totalValueCell.SetCellValue(rec.Amount);
        totalValueCell.CellStyle = amountStyle;
    }
Run Code Online (Sandbox Code Playgroud)