【发布时间】:2018-01-11 08:30:47
【问题描述】:
我从 Excel 获取数据时出现连接问题。它在 .xlsx 文件中运行良好,但不适用于 Excel 8.0 格式的 .xls 文件。我怎么解决这个问题?我尝试添加“HDR:YES”或“IMEX:1”但没有工作。这是我的代码;
string connString = "";
if (sFileExtension == ".xls")
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(string.Format("Upload/Belgeler/Tmp/{0}_{1}/{2}", DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString(), sFileName)) + ";Extended Properties=Excel 8.0";
else if (sFileExtension == ".xlsx")
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(string.Format("Upload/Belgeler/Tmp/{0}_{1}/{2}", DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString(), sFileName)) + ";Extended Properties=Excel 12.0";
// Create the connection object
OleDbConnection oledbConn = new OleDbConnection(connString);
try
{
// Open connection
oledbConn.Open();
DataTable dtSheetName = oledbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dtSheetName == null || dtSheetName.Rows.Count == 0)
{
if (oledbConn.State == ConnectionState.Open)
oledbConn.Close();
throw new Exception("Excel belgesi içinde Sayfa[Sheet] bulunamadı!");
}
// Create OleDbCommand object and select data from worksheet Sheet1
DataSet ds = new DataSet();
using (OleDbCommand cmdSheet = new OleDbCommand("SELECT * FROM [" + dtSheetName.Rows[0]["TABLE_NAME"].ToString() + "]", oledbConn))
{
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmdSheet;
oleda.Fill(ds, "ExcelFields");
}
oledbConn.Close();
【问题讨论】:
-
尝试同时使用 Excel 12.0。根据我的经验,司机把它整理得很好。如果这不起作用,则可能是您的 .xls 文件以某种方式损坏,因此请尝试重新保存它并查看是否可以打开它。
-
它不工作。
标签: excel connection-string oledb ole ms-jet-ace