简体   繁体   中英

(C#) OpenXML import xlsx into DataTable with correct column data type

I am using OpenXML library to import excelsheet(.xslx) into a DataTable using C#.

The first row of the xlsx contains the column name, so i start adding the column in the DataTable:

foreach (Cell cell in row.Descendants<Cell>())
{
    dt.Columns.Add(GetXlsxCellValue(sharedStringTableList, cell));
}

Then i loop all the other rows and i fill the DataTable by adding any single row to my DataTable in a similar way with any cell in the current row.

Now, imagine that my excel has two columns like this

excelExample

The first row contain the column name, so the first cell has a DataType = string (the text is stored in sharedStringTableList).

All the other rows contains ONLY Number in the first column (and, in excel, the entire column it's also format as "number").

At the end, in my DataTable, the first column has the correct name ("Number") but the column DataType is STRING .

The question: how can i create my DataTable with the correct column DataType set in the xlsx at the beginning? The method "Columns.Add()" allow you to specify the column dataType, but in the first row all the cell have DataType = string, so i need to check the column DataType in other way.

Thanks in advance,

Andrea

...

Well, You are going to have to determine the cell type and then create the column based on that. Try look at this post. Afterwards, you should be able to create your columns based upon the cell type (after you translate it to .NET types). However, if you know your types in advanced and want your data as a List of T, I'd suggest looking at something like ClassToExcel.OpenXml or a similar wrapper library to save yourself the trouble of writing the code.

There is a library called ClosedXML that is a friendly wrapper for OpenXML I found much easier to use than straight OpenXML. There is an Enum (XLCellValues) that tells you what the excel data type is. This can be used to help you build the correct data column type.

Here is an example of how to navigate and parse the rows and columns into a simple class using closed xml, pretty similar to your example (but for a class instead of data table). There is also a method in that link/example that maps C# sharp types to excel column types that you could use in reverse (XLCellValues enum). It gets more complicated if you don't trust the given excel data type.

If you have a simple target class you are trying to extract out of the excel this nuget could work out of the box, but I think you want a DataTable output.

Hope this helps.

您必须查看以下内容,才能将整个列数据类型设置为text:

Worksheet.Column(9).Style.NumberFormat.Format = "@";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM