在MVC应用程序中,当与Excel连接时出现错误 我只是用excel创建连接,尝试打开时会提示错误
oledbConn.ServerVersion'引发了类型异常 'System.InvalidOperationException
public DataTable Read(string filePath)
{
string extension = System.IO.Path.GetExtension(filePath).ToLower();
string connString = string.Empty;
if (extension.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'";
}
else if (extension.Trim() == ".xlsx")
{
//connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
//connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;Persist Security Info=False";
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'";
}
connString = string.Format(connString, filePath);
var dataTable = ConvertXSLXtoDataTable(filePath, connString);
return dataTable;
}
DataTable ConvertXSLXtoDataTable(string strFilePath, string connString)
{
OleDbConnection oledbConn = new OleDbConnection(connString);
DataTable dt = new DataTable();
try
{
oledbConn.Open();
using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbConn))
{
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds);
dt = ds.Tables[0];
}
}
catch
{
}
finally
{
oledbConn.Close();
}
return dt;
}