ClosedXML does not give me option to format column
Asked Answered
R

1

5

I'm having an issue when I try to change the format of an entire column.

My issue is that I don't get the XLCellValues operand. I am able to choose XLDataType.Text but that does not work. This is what I have:

eventSheet.Column("A").CellsUsed().SetDataType(XLDataType.Text); I have also tried replacing the A with 1. No luck that way either. Could it be a newer revision of the ClosedXML package? Thank you!

Respire answered 1/3, 2018 at 15:50 Comment(0)
R
9

The IXLCell.SetDataType method does not change the display format. It just changes the type of the underlying value. To change the display format, use IXLCell.Style.NumberFormat

Example:

var workbook = new XLWorkbook();
var ws = workbook.Worksheets.Add("Style NumberFormat");

var co = 2;
var ro = 1;

// Using a custom format
ws.Cell(++ro, co).Value = "123456.789";
ws.Cell(ro, co).Style.NumberFormat.Format = "$ #,##0.00";

ws.Cell(++ro, co).Value = "12.345";
ws.Cell(ro, co).Style.NumberFormat.Format = "0000";

// Using a OpenXML's predefined formats
ws.Cell(++ro, co).Value = "12.345";
ws.Cell(ro, co).Style.NumberFormat.NumberFormatId = 3;

ws.Column(co).AdjustToContents();

workbook.SaveAs("StylesNumberFormat.xlsx");

You can find more information on the ClosedXML wiki, e.g. at https://github.com/ClosedXML/ClosedXML/wiki/Styles-NumberFormat

Rash answered 2/3, 2018 at 8:40 Comment(2)
To format as US dollar currency use: cells.Style.NumberFormat.Format = @"[$$-en-US]#,##0.00_);[Red]([$$-en-US]#,##0.00)" (no need to set NumberFormatId)Igbo
And remember that Excel column numbers start at 1, not zero.Vanadinite

© 2022 - 2024 — McMap. All rights reserved.