C# code to read Excel (html import)
I trying to read Excel file which is Html type with C# code. I'm getting an 'Unspecified error'.
This is my connection string:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='HTML Import; // c:\1.xls
This is my code:
private string GetTableName(OleDbConnection conn)
{
string tableName = null;
try
{
conn.Open();
var dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
log.Error("Table schema is not available.");
开发者_运维知识库 return tableName;
}
tableName = dt.Rows[0]["TABLE_NAME"].ToString();
}
catch (Exception e)
{
log.Warn(e);
return null;
}
finally
{
conn.Close();
}
return tableName;
}
I looked all over the Internet and Google and nobody had exactly the same issue.
I would like to understand what is wrong with my code or what does it mean the 'Unspecified Error'?!
Thanks !!!
Try using
Provider=Microsoft.ACE.OLEDB.12.0;
Edit:
Use this connection string
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\";"
HDR=Yes means that the header is considered as a data row and not column names (Change it depending on your needs)
IMEX=1 specify that the table contains mixed data
for Excel 2007 change connection string as
Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0 Xml;HDR=YES';
ACE OLEDB 12.0
was released with Office 2007. It is possible to use the Microsoft.ACE.OLEDB.12.0
to connect to older .xls
(Excel 97-2003) workbooks as well.
精彩评论