I need to retrieve data from an Excel file and insert the data into a database. Im trying now to just retrieve the data but i keep getting an HRESULT:0x800A03EC exception error.
my code:
public void ReadFile()
{
try
{
Excel.Application ep = new Excel.Application();
Excel.Workbook ewb = ep.Workbooks.Open(@"C:/Temp/Copy of AGCO Transport Schedule.xlsx");
Excel.Worksheet ews = ewb.Sheets[1];
Excel.Range range = ews.UsedRange;
int rowCount = range.Rows.Count;
int columnCount = range.Columns.Count;
for (int i = 1; i < rowCount; i++)
{
for (int j = 1; j < columnCount; j++)
{
string str = (string)(range.Cells[i, j] as Excel.Range).Value2;
Console.WriteLine(str);
}
}
}
catch (Exception e)
{
Console.WriteLine("YOLO "+e.Message);
}
}
}
After getting the solution for the code above from a user here. The loop indexes should be changed to 1 instead of 0. I have corrected the code above. But the thing is that I need to select only 2 columns from the data in Excel, so i went on using sql for retrieving the data from the Excel file. But this time i keep getting “failed to create file” error and this happens when i try to open my connection.
my code:
public void ReadExcelFile()
{
string connectionString = string.Format(ConfigurationManager.ConnectionStrings["ExcelConnection"].ConnectionString.Replace("'", "\""), "@C:/Temp/Copy.xlsx");
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
try
{
connection.Open();
string sqlCmd = "SELECT * FROM [Ark1$]";
using (OleDbCommand command = new OleDbCommand(sqlCmd, connection))
{
command.CommandType = System.Data.CommandType.Text;
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader.ToString());
}
}
}
}
catch (Exception exception)
{
Console.WriteLine("ERROR in ReadExcelFile() method. Error Message : " + exception.Message);
}
}
}
can anyone help me with this ?
Something i would like to add:
Your method is SLOW – really, really slow.
To speed it up, you have two alternatives:
Use EPPLUS, it is a fast and free library for excel reading/writing.
Oder get the data from excel in one go, simply “pull” the data from your range object into an array (dim values() = range.value2 in VB.net) and iterate over that array. That is a lot faster than enumerating each cell.