ASP.NET 开发一个Excel 导入数据库的小系统,结果读取Excel 时报错了,网上找了好多办法都没法解决
/// <param name="filepath">文件路径</param>
/// <param name="sheetname">Excel 表名</param>
/// <param name="str">提示信息</param>
/// <returns></returns>
public System.Data.DataTable ExcelTable(string filepath, string sheetname, ref string str)
{
string strConn; strConn = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
System.Data.DataTable dt = null; try
{
OleDbConnection conn = new OleDbConnection(strConn);
if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)
{
conn.Open();
} System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string strSql = "select * from [" + sheetname + "]";
OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "#table1");
dt = ds.Tables[0];
str = "";
}
catch (Exception)
{
str = "没有 " + sheetname.Substring(0, sheetname.Length - 1);
} return dt;
}
在到 conn.Open(); 报错了 先弹出无法找到入口,确定,就什么鬼东东版本的
确定后就看到
/// <param name="filepath">文件路径</param>
/// <param name="sheetname">Excel 表名</param>
/// <param name="str">提示信息</param>
/// <returns></returns>
public System.Data.DataTable ExcelTable(string filepath, string sheetname, ref string str)
{
string strConn; strConn = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";
System.Data.DataTable dt = null; try
{
OleDbConnection conn = new OleDbConnection(strConn);
if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)
{
conn.Open();
} System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string strSql = "select * from [" + sheetname + "]";
OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);
DataSet ds = new DataSet();
da.Fill(ds, "#table1");
dt = ds.Tables[0];
str = "";
}
catch (Exception)
{
str = "没有 " + sheetname.Substring(0, sheetname.Length - 1);
} return dt;
}
在到 conn.Open(); 报错了 先弹出无法找到入口,确定,就什么鬼东东版本的
确定后就看到
private DataSet CreateDataSource()
{
String filename = FileUpload1.FileName;
String newpath = this.MapPath("~/excel");
//保存到当前文件夹下
String fullpath = String.Format("{0}/{1}", newpath, filename); this.FileUpload1.SaveAs(fullpath);
string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + this.MapPath("excel/"+filename) + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataSet ds = new DataSet();
OleDbDataAdapter odda = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", conn);
odda.Fill(ds);
conn.Close();
return ds;
}
protected void Button1_Click(object sender, EventArgs e)//前端,添加一个button按钮和一个gridview控件显示excel内容
{
GridView1.DataSource = CreateDataSource();
GridView1.DataBind();
}
吾新手,有错请见谅