`
lovnet
  • 浏览: 6693532 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
文章分类
社区版块
存档分类
最新评论

NPOI把Excel导入到数据库

 
阅读更多

一,如何把Excel中的数据导入到数据库?

(1)可以使用多种方式,但是较好的一种是使用NPOI。

(2)NPOI的缺陷:只能在Office2003中使用,Office2007无法使用NPOI,同时对于WPS也不能使用。

(3)使用是要引入NPOI的dll外部文件,下面的代码使用了简单三层的思想。

二,把Excel中的数据导入到数据库的具体步骤:


protected void Button1_Click(object sender, EventArgs e)
{
try
{
//文件流
using (Stream stream = new FileStream(@"G:\userInfo.xls", FileMode.Open, FileAccess.Read))
{
HSSFWorkbook workbook = new HSSFWorkbook(stream);
HSSFSheet sheet = workbook.GetSheetAt(0);

//Execel第一行是标题,不是要导入数据库的数据
for (int i = 1; i <= sheet.LastRowNum; i++)
{
HSSFRow row = sheet.GetRow(i);
UserInfo userinfo = new UserInfo();
userinfo.UserName = row.GetCell(0).StringCellValue;
//判断Excel中的Age的类型,根据不同的类型来用不同的方式取值
if (row.GetCell(1).CellType == HSSFCell.CELL_TYPE_NUMERIC)
{
userinfo.Age = row.GetCell(1).NumericCellValue;
}
else
{
userinfo.Age =Convert.ToInt32(row.GetCell(1).StringCellValue);
}
userinfo.Email = row.GetCell(2).StringCellValue;
//电话号码同样如此
if (row.GetCell(3).CellType == HSSFCell.CELL_TYPE_NUMERIC)
{
userinfo.Telephone = row.GetCell(3).NumericCellValue.ToString();
}
else
{
userinfo.Telephone = row.GetCell(3).StringCellValue;
}
userinfo.AddDate = row.GetCell(4).DateCellValue;
userinfo.Address = row.GetCell(5).StringCellValue;
//注意:Excel中可空的地方,Remark可以不填,因此我们需要判断。
if (row.GetCell(6)==null)
{
userinfo.Remarks = "";
}
else
{
userinfo.Remarks = row.GetCell(6).StringCellValue;
}
new UserInfoBLL().AddNew(userinfo);

}
}
Response.Write("导入数据成功");
}
catch (Exception ex)
{
Response.Write("错误:" + ex.Message);
}
}

三,如何把数据库中的数据导入到Excel,参考本博客其他文章。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics