在一个aspx页面中打开了一个excel表,想把表上的数据写到后台数据库中

在页面上添加好数据后,点击按钮将excel上的数据写入sql数据库,后台代码该怎么写?怎么调用可以操作excel的类?workbook、sheet这些关键字现在都不可以使用啊,求指教,谢谢?

给你个例子,自己看看,OK

string filename = FileUpload1.PostedFile.FileName.Substring(FileUpload1.PostedFile.FileName.LastIndexOf("\\"));
FileUpload1.PostedFile.SaveAs(Server.MapPath("fileupload\\") + filename);//上传文件

string conn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("fileupload\\") + filename + ";Extended Properties=Excel 8.0";
string sqlin = "SELECT * FROM [Sheet2$]";
OleDbCommand olecommand = new OleDbCommand(sqlin, new OleDbConnection(conn));
OleDbDataAdapter adapterin = new OleDbDataAdapter(olecommand);
DataSet dsin = new DataSet();
adapterin.Fill(dsin);
DataTable dtin = dsin.Tables[0];//连接并读取excel数据

for (i = 3; i <= totalrow; i++)//将Excel文件中第一个工作表的数据导入到sql数据库scjd_youliaoxiaohaojihua表中
{
string sql = "insert into scjd_youliaoxiaohaojihua(yuexuhao,danwei,youpin,cheliangmingchengxinghao,zichanxingzhi,chepaihao,qiyou,chaiyou,beizhu) values('";
int j;
sql += DropDownList1.SelectedValue.ToString() + DropDownList3.SelectedValue.ToString();
if (DropDownList1.SelectedValue.ToString() != DateTime.Now.Year.ToString() || int.Parse(DateTime.Now.Month.ToString()) != int.Parse(DropDownList3.SelectedValue.ToString()))
{
sql += "20";
}
else
{
if (int.Parse(DateTime.Now.Day.ToString()) < 10)
sql += "0";
sql += DateTime.Now.Day.ToString();
}
if (i-3 + count < 9)
sql += "00";
else if (i-3 + count < 99)
sql += "0";
sql += (i -3 + 1 + count).ToString();
sql += "','";
for (j = 1; j < 8; j++)
{//遍历Excel表中一行的所有列,除最后一列
sql += dtin.Rows[i][j].ToString().Trim();
sql += "','";
}
sql += dtin.Rows[i][8].ToString().Trim();
sql += "')";
try
{
DoSql(sql);
}
catch (Exception eeeeeee)
{
Response.Write("<script>alert('数据导入错误,请检查Excel文件')</script>");
return;
}
}

FileInfo file = new FileInfo(Server.MapPath("fileupload/") + filename);
if (file.Exists)
{//删除文件
file.Delete();
}

protected void DoSql(string sql)//执行sql语句的函数
{
SqlConnection conn = new SqlConnection();//创建连接对象
conn.ConnectionString = ConfigurationManager.AppSettings["conn"].ToString();//给连接字符串赋值
conn.Open();//打开数据库
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();//
conn.Close();//关闭数据库
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-02-22
先将exceL传到服务器上,然后.net是访问到服务器上的这个excel的,将数据取到,然后插入到数据库中就行了,你可以百度一下,例子挺多的

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网