Por favor, eche un vistazo al siguiente fragment de código. Simplemente abro el file excel myfile.xlsx
y añado filas desde un object de tipo List<Account>
(donde mi object Account
solo tiene properties Date
, Account
y Amount
), y myoutputfile.xlsx
el file con el nombre myoutputfile.xlsx
. Me gustaría que las celdas donde escribo las dates tengan un formatting de date, y las celdas donde tengo montos tengan un formatting numérico. Sin embargo, si pruebo el código a continuación, todas las celdas están formateadas con el formatting #.00
(dates también). He intentado todo, ¿alguien puede decirme qué está pasando? Estoy usando 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(); }
Esta es la razón por la que no está funcionando: las celdas que está creando comparten una reference al mismo object CellStyle
de forma pnetworkingeterminada. Dentro del ciclo está configurando el DataFormat
en esa instancia de estilo en "dd/MM/yyyy"
, luego configura ese mismo DataFormat
en "#.00"
. El último gana, por lo que, en última instancia, todas sus celdas numéricas (una date se considera un valor numérico en Excel) se formateará como "#.00"
.
Lo que necesita hacer es crear styles de celda separados para sus celdas de date y cantidad, establecer los DataFormats
en esos styles, luego establecer la propiedad CellStyle
para cada celda creada con el estilo apropiado.
Pruébalo así:
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; }