ASP.NET EXCEL导入

最近准备总结一些在开发中常用的代码,这是截取在某次开发工程中导入功能的代码

aspx代码

点击下载模板 上传Excel文件

aspx.cs代码

protected void Putin_Click(object,EventArgs e)
{
if(PutinFild.HasFile)
{
if(Path.GetExtension(PutinField.FileName==”.xls”))
{
putinFild.PosteFile.SaveAs(server.MapPath(“~/upfile/Excel/temporary.xls”))
ArrayList al = ExcelSheetName(Server.MapPath(“~/upfile/Excel/temporary.xls”));/获取文档的工作列表

                DataTable dt = ExcelDataSource(Server.MapPath("~/upfile/Excel/temporary.xls"), al[1].ToString()).Tables[0];//将Execl文件读入内存保存在DataSet中
                 PutinAmMeterDatabase(dt);//将内容导入到数据库
  }
  }

}

ArrayList ExcelSheetName(string filepath)//获取文档的工作簿
{
ArrayList al = new ArrayList();
string strConn;
strConn = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + filepath + “;Extended Properties=Excel 8.0;”;
OleDbConnection conn = new OleDbConnection(strConn);
try
{
conn.Open();
DataTable sheetNames = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, “TABLE” });
conn.Close();

        foreach (DataRow dr in sheetNames.Rows)
        {
            al.Add(dr[2]);
        }
    }
    catch
    {
        conn.Close();
        ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('导入失败!上传的文档格式不对!')</script>");
    }
    return al;
}

public DataSet ExcelDataSource(string filepath, string sheetname)//将文档读取保存到DataSet中
{
    string strConn;
    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;";
    OleDbConnection conn = new OleDbConnection(strConn);
    OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + sheetname + "]", strConn);
    DataSet ds = new DataSet();
    oada.Fill(ds);
    return ds;
}

void PutinAmMeterDatabase(DataTable dt)
{

    foreach (DataRow dr in dt.Rows)
    {

        string dept = dr[1].ToString();             //部门
        if (dept!="部门")
        {
            string emp_id = dr[2].ToString();                        //工号
            string emp_name = dr[3].ToString();                      //姓名
            string emp_cid = dr[4].ToString();                       //身份证号
            string emp_password = emp_cid.Substring(12, 6);          //密码
            DataTable empdt = SqlHelper.ExecuteDataset(SqlHelper.connStr, CommandType.Text, string.Format("select emp_id from t_employee where emp_id='" + emp_id + "'  ")).Tables[0];
            if (empdt.Rows.Count==0)
            {
                SqlHelper.ExecuteNonQuery(SqlHelper.connStr, CommandType.Text, "insert into t_employee (emp_id,emp_name,emp_password,emp_cid)VALUES('" + emp_id + "','" + emp_name + "','" + emp_password + "','" + emp_cid + "')");
            }
        }
       }
   }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值