NPOI操作之一EXCEL数据导入数据库

一、概要

前面讲到NPOI操作EXCEL导出功能,下面讲下从EXCEL里获取数据添加进数据库。

二、代码

 1 HSSFWorkbook hssfworkbook;
 2         public void ExcelDataToDataBase()
 3         {
 4             string filePath = HttpContext.Current.Server.MapPath("~/123.xls");
 5             DAL.TodaySoftHRAMSContext context = new DAL.TodaySoftHRAMSContext();
 6             #region//初始化信息
 7             try
 8             {
 9                 using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
10                 {
11                     hssfworkbook = new HSSFWorkbook(file);
12                 }
13             }
14             catch (Exception e)
15             {
16                 throw e;
17             }
18             #endregion
19 
20             NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
21             System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
22             ArchivesBase archivesBase = new ArchivesBase();
23             while (rows.MoveNext())
24             {
25                 HSSFRow row = (HSSFRow)rows.Current;
26                 archivesBase.PeopleName = row.Cells[1].ToString().Trim();
27                 if (archivesBase.PeopleName == "")
28                 {
29                     continue;
30                 }
31                 if (archivesBase.PeopleName.Length <= 1)
32                 {
33                     archivesBase.PeopleName += "*";
34                 }
35                 archivesBase.PeopleSex = "";
36                 archivesBase.AddTime = DateTime.Now;
37                 archivesBase.GraduateYear = 2012;
38                 context.ArchivesBases.Add(archivesBase);
39                 context.SaveChanges();
40             }
41         }

嘴比较笨,不知道该怎么详细解释,代码都是我调试通过的,一切都在不言中,o(∩_∩)o 

posted @ 2013-11-12 15:26  情若天_RunUp  阅读(500)  评论(0编辑  收藏  举报