Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a data type for a column with ClosedXML?

Tags:

c#

closedxml

I see a lot of examples in documentation where data type for a cell is set:

ws.Cell(1, 1).SetDataType(XLCellValues.Text);

But when I try to set a data type for a column:

ws.Column(1).SetDataType(XLCellValues.Text)

ClosedXML generates a 5MB file and data type is not actually set.

This operation works as expected in Excel (right-click on the column header, format cells, ...).

If it is a limitation of ClosedXML, can it be easily fixed, or is there a workaround?

like image 380
astef Avatar asked Nov 18 '15 08:11

astef


People also ask

How read data from Excel in C# using ClosedXML?

C# read Excel file using ClosedXML. Excel; using var wbook = new XLWorkbook("simple. xlsx"); var ws1 = wbook. Worksheet(1); var data = ws1.

Does ClosedXML require Excel?

ClosedXML allows you to create Excel files without the Excel application.

What is ClosedXML?

ClosedXML is a . NET library for reading, manipulating and writing Excel 2007+ (. xlsx, . xlsm) files. It aims to provide an intuitive and user-friendly interface to dealing with the underlying OpenXML API.


1 Answers

ClosedXML sets the data type for all cells in the column, down to the maximum (row 1 million or so). Use this to only set the data type for the used cells in the column:

ws.Column(1).CellsUsed().SetDataType(XLDataType.Text);

Furthermore, the data type in ClosedXML is not the same as the cell format in Excel (have a look at the example file from the documentation to see the difference).

like image 121
Raidri Avatar answered Oct 07 '22 17:10

Raidri