mganss / ExcelMapper

An Excel to object mapper. Maps POCOs to and from Excel. Configuration via convention, attributes, or fluent methods.
MIT License
793 stars 122 forks source link

CustomFormat for a specific cell #290

Open lsouzaoliveira opened 9 months ago

lsouzaoliveira commented 9 months ago

Hello guys, is it possible to format a cell inside the AddMapping method?

Thanks!

mganss commented 9 months ago

You can set the CustomFormat and BuiltinFormat properties on the ColumnInfo object returned by AddMapping(). Does that work for your use case?

lsouzaoliveira commented 9 months ago

It sets for the entire column, I have one column on the first 4 rows with years like (2021, 2022, 2023, 2024) and the next rows with numbers like ($123.213.123), when I use ColumnInfo approach it formats the year like ($2.001, $2.002...)

mganss commented 9 months ago

Try the SetCellUsing() method, see https://github.com/mganss/ExcelMapper?tab=readme-ov-file#custom-mapping. This allows you to style each individual cell.

lsouzaoliveira commented 9 months ago

I tried with CellStyle = new XSSFCellStyle() but I have no clue how to use it. That cell content is a formula.

_excelMapper.AddMapping<MyModel>("Bla", p => Bla) .SetCellUsing((c, o) => { switch (c.Row.RowNum) { case 6: c.SetCellValue("Total..."); break; case 7: c.CellFormula = GetTotal...Formula(); break; default: { if(o != null) { c.CellFormula = o.ToString(); } break; } } });

mganss commented 9 months ago

Here's the code that sets the default column format: https://github.com/mganss/ExcelMapper/blob/681546d8d6c78d1a58fb78e48d49657ea39bed37/ExcelMapper/ColumnInfo.cs#L283-L298

And here's an example on how to set cell color: https://github.com/mganss/ExcelMapper/issues/144#issuecomment-913193871

Perhaps you can work from there.