都是没装Microsoft Office Excel 2007惹的祸
上周,同事去客户现场部署,部署完后,他进行测试。
测试到Excel导入数据功能时,他说系统报"请检查Excel文件!导入失败!原因是:
Object reference not set to an instance of an object.”
于是叫他发那个Excel文件(后缀为xlsx)回来,我试着导入,也没有问题啊,排除了是Excel文件内容的问题。于是去查相关代码。
Code
try
{
KpimsUtil.PrepareTmpUploadPath();
path = Server.MapPath(KpimsUtil.TmpUploadPath) +Guid.NewGuid().ToString() + "_" + FileUpload1.FileName;
FileUpload1.SaveAs(path);
if (path.ToLower().IndexOf(".xlsx") > 0)
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
}
if (path.ToLower().IndexOf(".xls") > 0 && path.EndsWith("xls"))
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path + ";Extended Properties=\"Excel 8.0;IMEX=1;\"";
}
DataTable dt = CreateDataSource(path, strConn);
Response.Write("<script>alert('导入成功!')</script>");
}
catch (Exception ex)
{
Response.Write(string.Format("<script>alert(\"请检查Excel文件!导入失败!原因是:{0}\")</script>",
ex.Message.Replace(Environment.NewLine,"\\r\\n")));
}
}
try
{
KpimsUtil.PrepareTmpUploadPath();
path = Server.MapPath(KpimsUtil.TmpUploadPath) +Guid.NewGuid().ToString() + "_" + FileUpload1.FileName;
FileUpload1.SaveAs(path);
if (path.ToLower().IndexOf(".xlsx") > 0)
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
}
if (path.ToLower().IndexOf(".xls") > 0 && path.EndsWith("xls"))
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path + ";Extended Properties=\"Excel 8.0;IMEX=1;\"";
}
DataTable dt = CreateDataSource(path, strConn);
Response.Write("<script>alert('导入成功!')</script>");
}
catch (Exception ex)
{
Response.Write(string.Format("<script>alert(\"请检查Excel文件!导入失败!原因是:{0}\")</script>",
ex.Message.Replace(Environment.NewLine,"\\r\\n")));
}
}
由于是Excel2007的文件,肯定是走
Code
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
这段了,突然间脑子里闪过一个念头,是不是生产机服务器没装Excel 2007啊?因为代码是一样的,出错肯定是因为环境不一样,而我们公司默认所有机子都有装Office 2007套装的。所以就叫同事将那个2007格式(xlsx)的文件另存为2003格式(xls)再试着导入,成功!
发现原因,解决方法就相应出来了,来招狠的,干脆就不让上传xlsx的文件,呵呵!因为客户那边Office现在都是清一色的2003!!