当前位置:编程学习 > asp >>

在一个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();//关闭数据库
    }
其他:先将exceL传到服务器上,然后.net是访问到服务器上的这个excel的,将数据取到,然后插入到数据库中就行了,你可以百度一下,例子挺多的 

上一个:.net怎么讲excel表的一列导入到数据库某张表的一列?
下一个:excel导入sql问题

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,