I use this function to read excel file to datatable:
public static DataTable exceldata(string filePath)
{
try
{
DataTable dtexcel = new DataTable();
bool hasHeaders = false;
string HDR = hasHeaders ? "Yes" : "No";
string strConn;
if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=YES;TypeGuessRows=0;ImportMixedTypes=Text\"";
else
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;IMEX=1;HDR=YES;TypeGuessRows=0;ImportMixedTypes=Text\"";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
DataRow schemaRow = schemaTable.Rows[0];
string sheet = schemaRow["TABLE_NAME"].ToString();
if (!sheet.EndsWith("_"))
{
string query = "SELECT * FROM [" + sheet + "]";
OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
dtexcel.Locale = CultureInfo.CurrentCulture;
daexcel.Fill(dtexcel);
}
conn.Close();
return dtexcel;
}
catch (Exception ex)
{
return null;
}
}
My trouble is: When Excel file have some cells that format look like number (ex: 301/1, 181/3 .... ), the datatable return empty value in that cells.
How can read Excel files to datatable that cells as string, not number detected ?
I know you've specifically asked to use an excel sheet. As someone who has faced the exact same issue, I would recommend you to use ClosedXML instead of using an Oledb connection.
Closed XML is much faster to read and allows you to get contents of an entire sheet or a cell very easily.
I've answered another question similar to this one here
https://stackoverflow.com/a/47235686/6729097
I am reading values from Excel sheet. Columns generally contain String but sometimes it may contain numeric values. While reading Excel sheet into datatable numeric value is read as blank.
It reads 90004 as null, But if I sort this column by numeric the it reads numeric value and gives string value as null and if I sort this column by string then it reads string value and gives numeric as null.
AC62614 abc EA MISC
AC62615 pqr EA MISC
AC62616 xyz EA MISC
AC62617 test EA 90004
AC62618 test3 TO MISC
AC62619 test3 TO STEEL
my code:
public static DataTable ReadExcelFile(FileUpload File1, string strSheetName)
{
string strExtensionName = "";
string strFileName = System.IO.Path.GetFileName(File1.PostedFile.FileName);
DataTable dtt = new DataTable();
if (!string.IsNullOrEmpty(strFileName))
{
//get the extension name, check if it's a spreadsheet
strExtensionName = strFileName.Substring(strFileName.IndexOf(".") + 1);
if (strExtensionName.Equals("xls") || strExtensionName.Equals("xlsx"))
{
/*Import data*/
int FileLength = File1.PostedFile.ContentLength;
if (File1.PostedFile != null && File1.HasFile)
{
//upload the file to server
//string strServerPath = "~/FolderName";
FileInfo file = new FileInfo(File1.PostedFile.FileName);
string strServerFileName = file.Name;
string strFullPath = HttpContext.Current.Server.MapPath("UploadedExcel/" + strServerFileName);
File1.PostedFile.SaveAs(strFullPath);
//open connection out to read excel
string strConnectionString = string.Empty;
if (strExtensionName == "xls")
strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ strFullPath
+ ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
else if (strExtensionName == "xlsx")
strConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ strFullPath
+ ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
if (!string.IsNullOrEmpty(strConnectionString))
{
OleDbConnection objConnection = new OleDbConnection(strConnectionString);
objConnection.Open();
DataTable oleDbSchemaTable = objConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
bool blExists = false;
foreach (DataRow dtr in oleDbSchemaTable.Rows)
{
//reads from the spreadsheet called 'Sheet1'
if (dtr["TABLE_NAME"].ToString() == "" + strSheetName + "$")
{
blExists = true;
break;
}
}
if (blExists)
{
OleDbCommand objCmd = new OleDbCommand(string.Format("Select * from [{0}$]", strSheetName), objConnection);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmd;
DataSet objDataSet = new DataSet();
objAdapter1.Fill(objDataSet);
objConnection.Close();
dtt = objDataSet.Tables[0];
}
}
}
}
}
return dtt;
}
If you change IMEX=2 in you connectionstring to IMEX = 1 the columns will be interpreted as text. Then you can get all data of the Sheet and check with Int32.TryParse() if the value is numeric or not.
Connecting string:
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"
IMEX=1 For Read All value as Text from Excel file
HDR =Yes For Excel First row as column read
IMEX=1 not use Than Numeric value will be NULL read
I am trying to import an excel to database from asp.net website through dataset.
Here is my first part.
int xlColCount = 1;
wb = app.Workbooks.Open(FilePath, 0, false, 5, "", "", true, Ex.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
ws = (Ex.Worksheet)wb.ActiveSheet;
xlColCount = ws.Columns.Count;
xlColCount = ws.UsedRange.Columns.Count;
ws.Columns.ClearFormats();
xlColCount = ws.UsedRange.Columns.Count;
//creating datacolumns
for (int i = 0; i < xlColCount; i++)
{
try
{
DSname.Tables[0].Columns.Add(((Ex.Range)ws.Cells[1,strColArr[i]]).Value2.ToString().Trim());
}
catch(Exception ex)
{
//error occured
}
}
First I am creating the column name based on the excel heading into dataset column. here xlColCount=198 (total no.of columns from the excel template and all are filled ) but when reaching 172th column (i=172) it is giving index out of range error.
What could be the reason? I need to create a dataset with column names from all excel column names.
Check your strColArr[i] array capacity..may be initialized with 172 or less in size.
May be you will have better results (and performance) with ADO.NET and System.Data.OleDb :
string filePath = #"C:\Workbook1.xls";
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0\";";
OleDbConnection connection = new OleDbConnection(connectionString);
string cmdText = "SELECT * FROM [Sheet1$]";
OleDbCommand command = new OleDbCommand(cmdText, connection);
command.Connection.Open();
OleDbDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader[0].ToString(), reader[1].ToString());
}
}
string filePath = "":
OleDbCommand cmd = new OleDbCommand(); ;
OleDbDataAdapter oleda = new OleDbDataAdapter();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
UserBase loginUser = (UserBase)Session["LoggedUser"];
SearchFilter filter = new SearchFilter();
string action = "ExportDocumentType";
filter.DocumentTypeID = Convert.ToInt32(cmbDocumentType.SelectedValue);
filter.DepartmentID = Convert.ToInt32(cmbDepartment.SelectedValue);
try
{
Logger.Trace("Started Extracting Soft Data", Session["LoggedUserId"].ToString());
// need to pass relative path after deploying on server
oledbConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
filePath + ";Extended Properties='Excel 12.0;';");
try
{
oledbConn.Open();
}
catch
{
string con = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + "Extended Properties=Excel 8.0;HDR=Yes;IMEX=1";
oledbConn = new OleDbConnection(con);
oledbConn.Open();
}
// Get the data table containg the schema guid.
dt = oledbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
throw new Exception(" No sheets available!");
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
cmd.Connection = oledbConn;
cmd.CommandType = CommandType.Text;
// Get column names of selected document type
string SelectCommand = getIndexFieldsList();
SelectCommand = "SELECT " + SelectCommand + " FROM [" + excelSheets[0] + "]";
cmd.CommandText = SelectCommand;
oleda = new OleDbDataAdapter(cmd);
try
{
oleda.Fill(ds);
}
catch
{
throw new Exception("Selected file is not matching to " + cmbDocumentType.SelectedItem.Text + ".");//Bug Wrtier DMS ENHSMT 1-1012 M
}
string strXml = string.Empty;
if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
// note: Do ur code here.. i prefer to create a insert satement from here using looping it out
}
else
{
throw new Exception(" No data available in uploaded file!");//Bug Wrtier DMS ENHSMT 1-1012 M
}
}
catch (Exception ex)
{
Logger.Trace("Exception:" + ex.Message, Session["LoggedUserId"].ToString());
throw new Exception(ex.Message.ToString());
}
finally
{
// Clean up.
if (oledbConn != null)
{
oledbConn.Close();
oledbConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
if (ds != null)
{
ds.Dispose();
}
}
}
I use following code to save data from excel file into table
private void RetrieveAndStoreExcelData(String filePath)
{
String excelConnectionStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source='" + filePath + "'; Extended Properties='Excel 8.0;'";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionStr);
excelConnection.Open();
try
{
//Get the name of the first worksheet
DataTable schema = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (schema == null || schema.Rows.Count < 1)
{
throw new Exception("Error: Could not determine the name of the first worksheet.");
}
string firstSheetName = schema.Rows[0]["TABLE_NAME"].ToString();
//Retrieve data from worksheet into reader
string query = "SELECT * FROM [" + firstSheetName + "]";
OleDbCommand command = new OleDbCommand(query, excelConnection);
OleDbDataReader dbReader = command.ExecuteReader(); //IEnumerable
//populate IEnumerable
if (dbReader.HasRows)
{
populateRecords(dbReader);
}
}
finally
{
excelConnection.Close();
}
}
This works fine. But if one of the fields length is greater than 255 characters then it truncates the string to 255 and that is also when that row appears after 10th row in excel sheet.
So, if first 10 rows is having length less than 255, it assumes that all rows will have length less than 255 characters.
So is there any way to solve this?
I'm hoping someone here can point me in the right direction - I'm trying to create a fairly robust utility program to read the data from an Excel sheet (may be .xls OR .xlsx) into a DataTable as quickly and leanly as possible.
I came up with this routine in VB (although I'd be just as happy with a good C# answer):
Public Shared Function ReadExcelIntoDataTable(ByVal FileName As String, ByVal SheetName As String) As DataTable
Dim RetVal As New DataTable
Dim strConnString As String
strConnString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & FileName & ";"
Dim strSQL As String
strSQL = "SELECT * FROM [" & SheetName & "$]"
Dim y As New Odbc.OdbcDataAdapter(strSQL, strConnString)
y.Fill(RetVal)
Return RetVal
End Function
I'm wondering if this is the best way to do it or if there are better / more efficent ways (or just more intelligent ways - Maybe Linq / native .Net providers) to use instead?
ALSO, just a quick and silly additional question - Do I need to include code such as y.Dispose() and y = Nothing or will that be taken care of since the variable should die at the end of the routine, right??
Thanks!!
If you want to do the same thing in C# based on CiarĂ¡n Answer
string sSheetName = null;
string sConnection = null;
DataTable dtTablesList = default(DataTable);
OleDbCommand oleExcelCommand = default(OleDbCommand);
OleDbDataReader oleExcelReader = default(OleDbDataReader);
OleDbConnection oleExcelConnection = default(OleDbConnection);
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Test.xls;Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\"";
oleExcelConnection = new OleDbConnection(sConnection);
oleExcelConnection.Open();
dtTablesList = oleExcelConnection.GetSchema("Tables");
if (dtTablesList.Rows.Count > 0)
{
sSheetName = dtTablesList.Rows[0]["TABLE_NAME"].ToString();
}
dtTablesList.Clear();
dtTablesList.Dispose();
if (!string.IsNullOrEmpty(sSheetName)) {
oleExcelCommand = oleExcelConnection.CreateCommand();
oleExcelCommand.CommandText = "Select * From [" + sSheetName + "]";
oleExcelCommand.CommandType = CommandType.Text;
oleExcelReader = oleExcelCommand.ExecuteReader();
nOutputRow = 0;
while (oleExcelReader.Read())
{
}
oleExcelReader.Close();
}
oleExcelConnection.Close();
here is another way read Excel into a DataTable without using OLEDB
very quick
Keep in mind that the file ext would have to be .CSV for this to work properly
private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
csvData = new DataTable(defaultTableName);
try
{
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[]
{
tableDelim
});
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == string.Empty)
{
fieldData[i] = string.Empty; //fieldData[i] = null
}
//Skip rows that have any csv header information or blank rows in them
if (fieldData[0].Contains("Disclaimer") || string.IsNullOrEmpty(fieldData[0]))
{
continue;
}
}
csvData.Rows.Add(fieldData);
}
}
}
catch (Exception ex)
{
}
return csvData;
}
I have always used OLEDB for this, something like...
Dim sSheetName As String
Dim sConnection As String
Dim dtTablesList As DataTable
Dim oleExcelCommand As OleDbCommand
Dim oleExcelReader As OleDbDataReader
Dim oleExcelConnection As OleDbConnection
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Test.xls;Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
oleExcelConnection = New OleDbConnection(sConnection)
oleExcelConnection.Open()
dtTablesList = oleExcelConnection.GetSchema("Tables")
If dtTablesList.Rows.Count > 0 Then
sSheetName = dtTablesList.Rows(0)("TABLE_NAME").ToString
End If
dtTablesList.Clear()
dtTablesList.Dispose()
If sSheetName <> "" Then
oleExcelCommand = oleExcelConnection.CreateCommand()
oleExcelCommand.CommandText = "Select * From [" & sSheetName & "]"
oleExcelCommand.CommandType = CommandType.Text
oleExcelReader = oleExcelCommand.ExecuteReader
nOutputRow = 0
While oleExcelReader.Read
End While
oleExcelReader.Close()
End If
oleExcelConnection.Close()
The ACE.OLEDB provider will read both .xls and .xlsx files and I have always found the speed quite good.
public DataTable ImportExceltoDatatable(string filepath)
{
// string sqlquery= "Select * From [SheetName$] Where YourCondition";
string sqlquery = "Select * From [SheetName$] Where Id='ID_007'";
DataSet ds = new DataSet();
string constring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
OleDbConnection con = new OleDbConnection(constring + "");
OleDbDataAdapter da = new OleDbDataAdapter(sqlquery, con);
da.Fill(ds);
DataTable dt = ds.Tables[0];
return dt;
}
This seemed to work pretty well for me.
private DataTable ReadExcelFile(string sheetName, string path)
{
using (OleDbConnection conn = new OleDbConnection())
{
DataTable dt = new DataTable();
string Import_FileName = path;
string fileExtension = Path.GetExtension(Import_FileName);
if (fileExtension == ".xls")
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Import_FileName + ";" + "Extended Properties='Excel 8.0;HDR=YES;'";
if (fileExtension == ".xlsx")
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Import_FileName + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'";
using (OleDbCommand comm = new OleDbCommand())
{
comm.CommandText = "Select * from [" + sheetName + "$]";
comm.Connection = conn;
using (OleDbDataAdapter da = new OleDbDataAdapter())
{
da.SelectCommand = comm;
da.Fill(dt);
return dt;
}
}
}
}
You can use OpenXml SDK for *.xlsx files. It works very quickly. I made simple C# IDataReader implementation for this sdk. See here. Now you can easy read excel file to DataTable and you can import excel file to sql server database (use SqlBulkCopy). ExcelDataReader reads very fast. On my machine 10000 records less 3 sec and 60000 less 8 sec.
Read to DataTable example:
class Program
{
static void Main(string[] args)
{
var dt = new DataTable();
using (var reader = new ExcelDataReader(#"data.xlsx"))
dt.Load(reader);
Console.WriteLine("done: " + dt.Rows.Count);
Console.ReadKey();
}
}
I found it pretty easy like this
using System;
using System.Data;
using System.IO;
using Excel;
public DataTable ExcelToDataTableUsingExcelDataReader(string storePath)
{
FileStream stream = File.Open(storePath, FileMode.Open, FileAccess.Read);
string fileExtension = Path.GetExtension(storePath);
IExcelDataReader excelReader = null;
if (fileExtension == ".xls")
{
excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (fileExtension == ".xlsx")
{
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
var test = result.Tables[0];
return result.Tables[0];
}
Note: you need to install SharpZipLib package for this
Install-Package SharpZipLib
neat and clean! ;)
This is the way to read from excel oledb
try
{
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet DtSet;
System.Data.OleDb.OleDbDataAdapter MyCommand;
string strHeader7 = "";
strHeader7 = (hdr7) ? "Yes" : "No";
MyConnection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fn + ";Extended Properties=\"Excel 12.0;HDR=" + strHeader7 + ";IMEX=1\"");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + wks + "$]", MyConnection);
MyCommand.TableMappings.Add("Table", "TestTable");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dgv7.DataSource = DtSet.Tables[0];
MyConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
The below code is tested by myself and is very simple, understandable, usable and fast.
This code, initially takes all sheet names, then puts all tables of that excel file in a DataSet.
public static DataSet ToDataSet(string exceladdress, int startRecord = 0, int maxRecord = -1, string condition = "")
{
DataSet result = new DataSet();
using (OleDbConnection connection = new OleDbConnection(
(exceladdress.TrimEnd().ToLower().EndsWith("x"))
? "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + exceladdress + "';" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'"
: "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + exceladdress + "';Extended Properties=Excel 8.0;"))
try
{
connection.Open();
DataTable schema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow drSheet in schema.Rows)
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
string s = drSheet["TABLE_NAME"].ToString();
if (s.StartsWith("'")) s = s.Substring(1, s.Length - 2);
System.Data.OleDb.OleDbDataAdapter command =
new System.Data.OleDb.OleDbDataAdapter(string.Join("", "SELECT * FROM [", s, "] ", condition), connection);
DataTable dt = new DataTable();
if (maxRecord > -1 && startRecord > -1) command.Fill(startRecord, maxRecord, dt);
else command.Fill(dt);
result.Tables.Add(dt);
}
return result;
}
catch (Exception ex) { return null; }
finally { connection.Close(); }
}
Enjoy...
''' <summary>
''' ReadToDataTable reads the given Excel file to a datatable.
''' </summary>
''' <param name="table">The table to be populated.</param>
''' <param name="incomingFileName">The file to attempt to read to.</param>
''' <returns>TRUE if success, FALSE otherwise.</returns>
''' <remarks></remarks>
Public Function ReadToDataTable(ByRef table As DataTable,
incomingFileName As String) As Boolean
Dim returnValue As Boolean = False
Try
Dim sheetName As String = ""
Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & incomingFileName & ";Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
Dim tablesInFile As DataTable
Dim oleExcelCommand As OleDbCommand
Dim oleExcelReader As OleDbDataReader
Dim oleExcelConnection As OleDbConnection
oleExcelConnection = New OleDbConnection(connectionString)
oleExcelConnection.Open()
tablesInFile = oleExcelConnection.GetSchema("Tables")
If tablesInFile.Rows.Count > 0 Then
sheetName = tablesInFile.Rows(0)("TABLE_NAME").ToString
End If
If sheetName <> "" Then
oleExcelCommand = oleExcelConnection.CreateCommand()
oleExcelCommand.CommandText = "Select * From [" & sheetName & "]"
oleExcelCommand.CommandType = CommandType.Text
oleExcelReader = oleExcelCommand.ExecuteReader
'Determine what row of the Excel file we are on
Dim currentRowIndex As Integer = 0
While oleExcelReader.Read
'If we are on the First Row, then add the item as Columns in the DataTable
If currentRowIndex = 0 Then
For currentFieldIndex As Integer = 0 To (oleExcelReader.VisibleFieldCount - 1)
Dim currentColumnName As String = oleExcelReader.Item(currentFieldIndex).ToString
table.Columns.Add(currentColumnName, GetType(String))
table.AcceptChanges()
Next
End If
'If we are on a Row with Data, add the data to the SheetTable
If currentRowIndex > 0 Then
Dim newRow As DataRow = table.NewRow
For currentFieldIndex As Integer = 0 To (oleExcelReader.VisibleFieldCount - 1)
Dim currentColumnName As String = table.Columns(currentFieldIndex).ColumnName
newRow(currentColumnName) = oleExcelReader.Item(currentFieldIndex)
If IsDBNull(newRow(currentFieldIndex)) Then
newRow(currentFieldIndex) = ""
End If
Next
table.Rows.Add(newRow)
table.AcceptChanges()
End If
'Increment the CurrentRowIndex
currentRowIndex += 1
End While
oleExcelReader.Close()
End If
oleExcelConnection.Close()
returnValue = True
Catch ex As Exception
'LastError = ex.ToString
Return False
End Try
Return returnValue
End Function
Use the below snippet it will be helpfull.
string POCpath = #"G:\Althaf\abc.xlsx";
string POCConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + POCpath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
OleDbConnection POCcon = new OleDbConnection(POCConnection);
OleDbCommand POCcommand = new OleDbCommand();
DataTable dt = new DataTable();
OleDbDataAdapter POCCommand = new OleDbDataAdapter("select * from [Sheet1$] ", POCcon);
POCCommand.Fill(dt);
Console.WriteLine(dt.Rows.Count);
I've used this method and for me, it is so efficient and fast.
// Step 1. Download NuGet source of Generic Parsing by Andrew Rissing
// Step 2. Reference this to your project
// Step 3. Reference Microsoft.Office.Interop.Excel to your project
// Step 4. Follow the logic below
public static DataTable ExcelSheetToDataTable(string filePath) {
// Save a copy of the Excel file as CSV
var xlApp = new XL.Application();
var xlWbk = xlApp.Workbooks.Open(filePath);
var tempPath =
Path.Combine(Environment
.GetFolderPath(Environment.SpecialFolder.UserProfile)
, "AppData"
, "Local",
, "Temp"
, Path.GetFileNameWithoutExtension(filePath) + ".csv");
xlApp.DisplayAlerts = false;
xlWbk.SaveAs(tempPath, XL.XlFileFormat.xlCSV);
xlWbk.Close(SaveChanges: false);
xlApp.Quit();
// The actual parsing
using (var parser = new GenericParserAdapter(tempPath)) {
parser.FirstRowHasHeader = true;
return parser.GetDataTable();
}
}
Generic Parsing by Andrew Rissing
Here is another way of doing it
public DataSet CreateTable(string source)
{
using (var connection = new OleDbConnection(GetConnectionString(source, true)))
{
var dataSet = new DataSet();
connection.Open();
var schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (schemaTable == null)
return dataSet;
var sheetName = "";
foreach (DataRow row in schemaTable.Rows)
{
sheetName = row["TABLE_NAME"].ToString();
break;
}
var command = string.Format("SELECT * FROM [{0}$]", sheetName);
var adapter = new OleDbDataAdapter(command, connection);
adapter.TableMappings.Add("TABLE", "TestTable");
adapter.Fill(dataSet);
connection.Close();
return dataSet;
}
}
//
private string GetConnectionString(string source, bool hasHeader)
{
return string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};
Extended Properties=\"Excel 12.0;HDR={1};IMEX=1\"", source, (hasHeader ? "YES" : "NO"));
}