ASP.NET 实现上传EXCEL,利用NOPI操作,转换得到DataTable

   这几天正好用到上传Excel,并根据Excel中的数据做相应的处理,故整理以备用。

   如果需要将Excel中的数据对应写到数据库表中请参见后学用SqlBulkCopy一次性将多条数据赋值到表中:http://www.cnblogs.com/MichaelWillLee/p/6843862.html

      用到的资源:

  (1)NOPI 2.2.0.0 可自己官网下载,也可点击:http://pan.baidu.com/s/1jIRxivW

  (2)用到一些常见处理文件的公共方法类,可以添加到项目中:http://pan.baidu.com/s/1dEWGKNZ 

   如过上述连接因故无法使用,可在评论留下邮箱,我打包发送过去,如有更好的建议,欢迎指导。

 

       后台的提示方法ShowMsgHelper,根据自己的改写即可。

      ===========前台开始===============

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head runat="server">
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 5     <title>导入EXCEL,生成DataTable</title>
 6     <script src="../../Themes/Scripts/jquery-1.8.2.min.js"></script>
 7     <link href="/Themes/Styles/Site.css" rel="stylesheet" type="text/css" />
 8     <script src="/Themes/Scripts/FunctionJS.js" type="text/javascript"></script>
 9     
10     <script type="text/javascript">
11         $(document).ready(function () {
12             $("#Import").click(function () {
13                 var filename = $("#FileUpload1").val();
14                 if (filename == '') {
15                     alert('请选择上传的EXCEL文件');
16                     return false;
17                 }
18                 else {
19                     var exec = (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename.toLowerCase()) : '';
20                     if (!(exec == "xlsx" || exec == "xls")) {
21                         alert("文件格式不对,请上传Excel文件!");
22                         return false;
23                     }
24                 }
25                 return true;
26             });
27         });
28     </script>
29 </head>
30 <body>
31     <form id="form1" runat="server">
32     <div>
33         <asp:FileUpload ID="FileUpload1" runat="server" /><asp:Button ID="Import" runat="server" Text="导入" OnClick="ImpClick" />
34     </div>
35     </form>
36 </body>
37 </html>
View Code

  ===========前台结束===============

  ===========后台开始===============

  1  protected void ImpClick(object sender, EventArgs e)
  2         {
  3             try
  4             {
  5                 #region 校验
  6                 var fileName = this.FileUpload1.FileName;
  7                 if (string.IsNullOrWhiteSpace(fileName))
  8                 {
  9                     //提示信息
 10                     ShowMsgHelper.Alert("请选择上传Excel文件");
 11                     return;
 12                 }
 13 
 14                 //获取上传文件扩展名称
 15                 if (!(fileName.IndexOf(".xlsx") > 0 || fileName.IndexOf(".xls") > 0))
 16                 {
 17                     ShowMsgHelper.Alert("上传文件格式不正确,请核对!");
 18                     return;
 19                 }
 20                 
 21 
 22                 #endregion
 23 
 24                 #region 将Excel文件上传到服务器上临时文件夹中
 25                 //临时文件夹,根目录下/Upload/tmp/,根据自己配置选择
 26                 string path = Server.MapPath("~/") + "Upload\\tmp\\";
 27                 string retStr=UploadHelper.FileUpload(path, this.FileUpload1);
 28                 if (!retStr.Equals("上传成功")) {
 29                     ShowMsgHelper.Alert(retStr);
 30                     return;
 31                 }
 32                 #endregion
 33 
 34                 #region 读取Excel文件第一个表获取内容并转换成DataTable,删除临时文件,也可以自己加时间戳,维护处理
 35                 DataTable dt = this.ExcelToDataTable(path + this.FileUpload1.FileName, true);
 36                 if (dt == null) {
 37                     ShowMsgHelper.Alert_Error("获取失败");
 38                     return;
 39                 }
 40 
 41                 //示例:获取dt中的值
 42                 string test = dt.Rows[0]["name"].ToString();
 43                 string test2 = dt.Rows[1]["class"].ToString();
 44 
 45                 //删除临时文件
 46                 DirFileHelper.DeleteFile("Upload\\tmp\\" + fileName);
 47                 #endregion 
 48         
 49             }
 50             catch (Exception ex) {
 51                 throw ex;
 52             }
 53 
 54         }
 55 
 56         /// <summary>
 57         /// 将excel导入到datatable
 58         /// </summary>
 59         /// <param name="filePath">excel路径</param>
 60         /// <param name="isColumnName">第一行是否是列名</param>
 61         /// <returns>返回datatable</returns>
 62         public DataTable ExcelToDataTable(string filePath, bool isColumnName)
 63         {
 64             DataTable dataTable = null;
 65             FileStream fs = null;
 66             DataColumn column = null;
 67             DataRow dataRow = null;
 68             IWorkbook workbook = null;
 69             ISheet sheet = null;
 70             IRow row = null;
 71             ICell cell = null;
 72             int startRow = 0;
 73             try
 74             {
 75                 using (fs = File.OpenRead(filePath))
 76                 {
 77                     // 2007版本
 78                     if (filePath.IndexOf(".xlsx") > 0)
 79                         workbook = new XSSFWorkbook(fs);
 80                     // 2003版本
 81                     else if (filePath.IndexOf(".xls") > 0)
 82                         workbook = new HSSFWorkbook(fs);
 83 
 84                     if (workbook != null)
 85                     {
 86                         sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet
 87                         dataTable = new DataTable();
 88                         if (sheet != null)
 89                         {
 90                             int rowCount = sheet.LastRowNum;//总行数
 91                             if (rowCount > 0)
 92                             {
 93                                 IRow firstRow = sheet.GetRow(0);//第一行
 94                                 int cellCount = firstRow.LastCellNum;//列数
 95 
 96                                 //构建datatable的列
 97                                 if (isColumnName)
 98                                 {
 99                                     startRow = 1;//如果第一行是列名,则从第二行开始读取
100                                     for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
101                                     {
102                                         cell = firstRow.GetCell(i);
103                                         if (cell != null)
104                                         {
105                                             if (cell.StringCellValue != null)
106                                             {
107                                                 column = new DataColumn(cell.StringCellValue);
108                                                 dataTable.Columns.Add(column);
109                                             }
110                                         }
111                                     }
112                                 }
113                                 else
114                                 {
115                                     for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
116                                     {
117                                         column = new DataColumn("column" + (i + 1));
118                                         dataTable.Columns.Add(column);
119                                     }
120                                 }
121 
122                                 //填充行
123                                 for (int i = startRow; i <= rowCount; ++i)
124                                 {
125                                     row = sheet.GetRow(i);
126                                     if (row == null) continue;
127 
128                                     dataRow = dataTable.NewRow();
129                                     for (int j = row.FirstCellNum; j < cellCount; ++j)
130                                     {
131                                         cell = row.GetCell(j);
132                                         if (cell == null)
133                                         {
134                                             dataRow[j] = "";
135                                         }
136                                         else
137                                         {
138                                             //CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
139                                             switch (cell.CellType)
140                                             {
141                                                 case CellType.Blank:
142                                                     dataRow[j] = "";
143                                                     break;
144                                                 case CellType.Numeric:
145                                                     short format = cell.CellStyle.DataFormat;
146                                                     //对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
147                                                     if (format == 14 || format == 31 || format == 57 || format == 58)
148                                                         dataRow[j] = cell.DateCellValue;
149                                                     else
150                                                         dataRow[j] = cell.NumericCellValue;
151                                                     break;
152                                                 case CellType.String:
153                                                     dataRow[j] = cell.StringCellValue;
154                                                     break;
155                                             }
156                                         }
157                                     }
158                                     dataTable.Rows.Add(dataRow);
159                                 }
160                             }
161                         }
162                     }
163                 }
164                 return dataTable;
165             }
166             catch (Exception)
167             {
168                 if (fs != null)
169                 {
170                     fs.Close();
171                 }
172                 return null;
173             }
174         }
View Code

  ===========后台结束===============

  

posted @ 2017-03-28 12:37  Michael我想念你  阅读(1018)  评论(0编辑  收藏  举报