Hi all,
I want to read an excel file using C#.
I have to get following information about an excel file.
1. Column list
2. Data type of data particular column is having like Numeric data, Alphanumric etc.
3. Maxlength/ max size of data contained in a column.
e.g. If there is one of the column of excel file as EmployeeNo then
1. EmplyeeNo
2. Alphanumeric
3. Maxlength(size) of data = 20
I got solution to read all coulmn names of excel file but could not get solution for finding data type of column and maxlength.
How can i do this in dotnet? Any help would be appreaciated.
Thank you
Amit MohantyPosted May 4, 2023, 10:52 AM
To read an Excel file using C# and obtain the column list, data types of each column, and the maximum length of data in each column, you can use the
ExcelDataReaderlibrary, which is available as a NuGet package.Leon DPosted May 5, 2023, 9:25 AM
You can install Spire.XLS through NuGet and then use it to read Excel files with ease.
https://www.nuget.org/packages/Spire.XLS/
The code sample below explains how to read data in an Excel worksheet into a data table:
Tuhin PaulPosted May 4, 2023, 12:15 PM
The code assumes that the Excel file exists and can be successfully opened. You could add error handling to catch any exceptions that may occur and provide better feedback to the user. The `using` statement is a great way to ensure that unmanaged resources are properly disposed of, but you can make it even simpler by using the C# feature of try-with-resources. This will ensure that the `ExcelReader` is always properly disposed of, even if an exception is thrown.
In the current code, the `ToString()` method is called on every cell value, which can be slow for large Excel files. A more efficient way to get the maximum length is to use the `ToString().Length` method on the raw `object` value, like this: `value?.ToString().Length ?? 0`. Instead of checking if the data type is not equal to each possible type individually, you could use a switch statement to make the code more concise and easier to read.
dip sPosted May 4, 2023, 11:46 AM
@Amit Mohanty thank you. its working
Jignesh KumarPosted May 4, 2023, 10:50 AM
Hello,
You can refer this article, You can use IronXL library to achieve this one and it will allow you to convert sheet to datatable.
https://www.c-sharpcorner.com/UploadFile/6b8651/read-excel-file-in-windows-application-using-C-Sharp/