由于我的excel文件是用Response.Write(a)生成的。 a为由换行\n、分隔符\t组成的字符串。所以该excel文件实际上并不是“真正的”excel文件(用记事本打开无乱码,真正的excel用记事本打开是有的),它只是一些纯字符串。所以,当我 Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";data source=.... 试图去open的时候,就报错了:External table is not in the expected format进一步验证,我把导出的excel另存为“真正的”.xls格式,再open就正常了!
有什么办法可以优雅快捷的解决这个问题? 改用Excel.Application太麻烦了..
有什么办法可以优雅快捷的解决这个问题? 改用Excel.Application太麻烦了..
// string strConn ="Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + Dir + "\\"+fileName + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1;\"
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
string query = "SELECT * FROM [Sheet1$]";
OleDbCommand oleCommand = new OleDbCommand(query, new OleDbConnection(strConn));
OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleCommand);
DataSet myDataSet = new DataSet();
// 将 Excel 的[Sheet1]表内容填充到 DataSet 对象
try
{
oleAdapter.Fill(myDataSet, "[Sheet1$]");
// 数据绑定
this.dgExportProject.DataSource = myDataSet;
this.dgExportProject.DataMember = "[Sheet1$]";
this.dgExportProject.DataBind(); this.dgExportProject.Visible = true;
this.btnSave.Visible = true;
}
catch (Exception exx)
{
Response.Write(exx.Message);
//Comm.Jscript.Alert("注意:请用默认的Sheet1$页名称!");
}
finally
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}