public static System.Data.DataSet ExcelSqlConnection(string filepath, string tableName, string IsXls)
{
string strCon = "";
if (IsXls == ".xls")
{
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
}
else
{
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";
}
OleDbConnection ExcelConn = new OleDbConnection(strCon);
try
{
//Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "<script>alert('" + strCon + "');</script>");
string strCom = string.Format("SELECT * FROM [" + Getstname(filepath, IsXls) + "]");
ExcelConn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, ExcelConn);
DataSet ds = new DataSet();
myCommand.Fill(ds, "[" + tableName + "$]");
ExcelConn.Close();
return ds;
}
catch
{
ExcelConn.Close();
return null;
}
}
private static string Getstname(string name, string IsXls)
{
string strConn = "";
if (IsXls == ".xls")
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + name + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
}
else
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + name + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1'";
}
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string tableName = schemaTable.Rows[0][2].ToString().Trim();
conn.Close();
return tableName;
}
string filename = File_ph_order.FileName; //获取Execle文件名 DateTime日期函数
if (!Directory.Exists(Server.MapPath(("~/upfiles/"))))
{
Directory.CreateDirectory(Server.MapPath(("~/upfiles/")));
}
string savePath = Server.MapPath(("~/upfiles/") + filename);//Server.MapPath 获得虚拟服务器相对路径
txt_key.Text = savePath;
File_ph_order.SaveAs(savePath); //SaveAs 将上传的文件内容保存在服务器上
DataSet ds = ExcelSqlConnection(savePath, filename, IsXls); //调用自定义方法
DataRow[] dr = ds.Tables[0].Select(); //定义一个DataRow数组 asdfadf
int rowsnum = ds.Tables[0].Rows.Count;
7 个解决方案
#2
看一下,设置IIS mime, 扩展名为xls,类型/子类型为application/vnd.ms-excel,
#3
你连“抛什么错”都懒得贴出来吗?
#4
路径对么?filepath是什么?这个路径对于IIS账户来说有读写权限么?
#5
将Exception发出来呀,帮你搞定!
#7
先把错误信息帖出来,否则谁也不知道这么解决
#1
#2
看一下,设置IIS mime, 扩展名为xls,类型/子类型为application/vnd.ms-excel,
#3
你连“抛什么错”都懒得贴出来吗?
#4
路径对么?filepath是什么?这个路径对于IIS账户来说有读写权限么?
#5
将Exception发出来呀,帮你搞定!
#6
Excel,不喜欢用微软的引擎
只喜欢用 http://npoi.codeplex.com/
只喜欢用 http://npoi.codeplex.com/
#7
先把错误信息帖出来,否则谁也不知道这么解决