Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CustomFormat for a specific cell #290

Open
lsouzaoliveira opened this issue Feb 1, 2024 · 5 comments
Open

CustomFormat for a specific cell #290

lsouzaoliveira opened this issue Feb 1, 2024 · 5 comments

Comments

@lsouzaoliveira
Copy link

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

Thanks!

@mganss
Copy link
Owner

mganss commented Feb 2, 2024

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

@lsouzaoliveira
Copy link
Author

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
Copy link
Owner

mganss commented Feb 2, 2024

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
Copy link
Author

lsouzaoliveira commented Feb 2, 2024

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
Copy link
Owner

mganss commented Feb 2, 2024

Here's the code that sets the default column format:

/// <summary>Sets the column style.</summary>
/// <param name="sheet">The sheet.</param>
/// <param name="columnIndex">Index of the column.</param>
public void SetColumnStyle(ISheet sheet, int columnIndex)
{
if (BuiltinFormat != 0 || CustomFormat != null)
{
var wb = sheet.Workbook;
var cs = wb.CreateCellStyle();
if (CustomFormat != null)
cs.DataFormat = wb.CreateDataFormat().GetFormat(CustomFormat);
else
cs.DataFormat = BuiltinFormat;
sheet.SetDefaultColumnStyle(columnIndex, cs);
}
}

And here's an example on how to set cell color: #144 (comment)

Perhaps you can work from there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants