.net导入excel数据到数据库中

在开发过程中我们经常面临着需要将数据导出或者导入到系统中,例如一些生产管理系统,项目管理系统等等都会有这样的需求;

将excel数据到系统中思路:获取excel中每一行的数据,然后存入集合中,批量添加到数据库对应的表中;

下面的demo是将财务部的工资表导入到系统中,细节有待完善。

 protected void BtnUpload_Click(object sender, EventArgs e)

{

#region 导入数据到工资表中
string filepath = salaryDAL.GetFilePathByKeyField(this.Number.Text);
string path = filepath.Replace("HumanResources/Gongzi/", "");
path = Server.MapPath(path);//获取excel文件路径
FileStream files = new FileStream(path, FileMode.Open, FileAccess.Read);//读取文件流
NPOI.SS.UserModel.IWorkbook workbook = WorkbookFactory.Create(files);
//读取sheet
var sheet = workbook.GetSheetAt(0);
var index = sheet.LastRowNum;
for (int i = 1; i <= index; i++)
{

  //注意:for循环中变量 i 的初始值为excel中元数据的行号,我的excel格式:0为表头 ,所以从1开始读取
  var row = sheet.GetRow(i);
  Salary model = new Salary();
  #region 获取单元格的值并赋值給实体对象
  model.RealName = row.GetCell(1).StringCellValue;
  model.UserNo = row.GetCell(2).NumericCellValue.ToString();
  model.Property = row.GetCell(3).StringCellValue;
  model.WorkDaies = Convert.ToInt32(row.GetCell(4).NumericCellValue);
  model.Holidaies = Convert.ToInt32(row.GetCell(5).NumericCellValue);
  model.BasicSalary = Convert.ToDecimal(row.GetCell(6).NumericCellValue);
  model.PostSalary = Convert.ToDecimal(row.GetCell(7).NumericCellValue);
  model.PostAllowance = Convert.ToDecimal(row.GetCell(8).NumericCellValue);
  model.Pension = Convert.ToDecimal(row.GetCell(9).NumericCellValue);
  model.Medical = Convert.ToDecimal(row.GetCell(10).NumericCellValue);

  ...........

   model.DaoZhangDate = Convert.ToDateTime(DateTime.Now.ToShortDateString());
  #endregion

      //也可以将model存到集合中,将集合包含在事务中,循环将集合中的元素新增到数据库中,从而保证数据一致性
  int id = salaryDAL.Add(model);
}

files.Dispose();
base.Response.Write("<script language=javascript>alert('工资导入成功!');window.location.href='SalaryExport.aspx'</script>");
#endregion

}

原文地址:https://www.cnblogs.com/niguang/p/5553171.html