gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:12:58 28 4
gpt4 key购买 nike

请看下面的代码片段。我只是打开 excel 文件 myfile.xlsx我从 List<Account> 类型的对象中添加行(我的 Account 对象只有 DateAccountAmount 属性),并使用名称 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();
}

最佳答案

这就是它不起作用的原因:默认情况下,您正在创建的单元格共享对同一 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;
}

关于c# - NPOI 以相同的方式格式化所有单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40308711/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com