Excel之导入数据

Posted mirzhai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Excel之导入数据相关的知识,希望对你有一定的参考价值。

在工作中遇到了Excel导入功能的开发,在这总结梳理一下。如果导入Excel表格次数较少,我们可以选择直接导入SQLserver数据库,但是如果需要经常需要导入数据,就需要单独开发一个导入功能,也就是今天的说的功能开发。

原理

因为我们做的是一个物资管理系统,经常需要导入入库数据,所以就非常需要Excel导入数据功能。

我们在前端使用了Uploadify这个jQuery的插件进行Excel文档传递到后端做处理,在后端我们使用Request.Files来接收Excel数据,并InputStream.Read读取文档。

前端

 html代码

 1 <form>
 2     <script>
 3         function xiazai() {
 4             window.open(URL(/Areas/WLGL/Scripts/Material/物资编码模板.xls));
 5         }
 6     </script>
 7     <input type="hidden" name="ID" />
 8     <table class="dialog-table" style="width: 100%; height: 100%;" border="0" align="center" cellpadding="0" cellspacing="0" id="__01">
 9         <tr style="height: 70%">
10             <td class="col-name">物资编码模板:</td>
11             <td>
12                 <a href="javascript:xiazai();" class="btn btn-info">点击下载</a></td>
13         </tr>
14         <tr style="height: 70%">
15             <td align="center" valign="middle" colspan="2">
16                 <div id="uploadProcess" style="padding: 3px;">
17                 </div>
18                 <div id="uploadBTN"></div>
19             </td>
20         </tr>
21     </table>
22 </form>

JavaScript代码

方法讲解:

$h.find(‘#uploadBTN‘).uploadify(‘destroy‘);
//销毁Uploadify实例并将文件上传按钮恢复到原始状态
$h.find("#uploadBTN").uploadify("cancel", "*");
//取消队列中的任务,不管此任务是否已经开始上传
$(‘#file_upload‘).uploadify(‘disable‘, true)

// setDisabled – 设置为true表示禁用,false为启用

 $(‘#file_upload‘).uploadify(‘settings‘,‘buttonText‘,‘BROWSE‘);//设置上传按钮的文字

 $(‘#file_upload‘).uploadify(‘settings‘,‘buttonText‘));//获取上传按钮名称的文字

 // name – 属性名称,如果只提供属性名称则表示获取其值

// value – 属性值
// resetObjects – 设置为true时,更新postData对象将清空现有的值。否则,新的值将被添加到其末尾。
$h.find("#uploadBTN").uploadify("upload", "*");

// 立即上传指定的文件,如果fileID为‘*‘表示上传所有文件,要指定上传多个文件,则将每个文件的fileID作为一个参数

 1 Excel: function () {
 2         var $h = top.$.hDialog({
 3             title: ‘数据导入‘,
 4             width: 340,
 5             height: 300,
 6             href: actions.ExcelPage,
 7             cache: true,
 8             inline: true,
 9             buttons: [{
10                 text: ‘开始上传‘,
11                 handler: function () {
12                     $h.find("#uploadBTN").uploadify("upload", "*");
13                 }
14             },
15               {
16                   text: ‘取消上传‘,
17                   handler: function () {
18                       $h.find("#uploadBTN").uploadify("cancel", "*");
19                       $h.dialog("close");
20                   }
21               }
22             ],
23             onLoad: function () {
24                 var $upload = $h.find(‘#uploadBTN‘).uploadify({
25                     //开启调试
26                     ‘debug‘: false,
27                     //是否自动上传
28                     ‘auto‘: false,
29                     ‘buttonText‘: ‘选择文件‘,
30                     //flash
31                     ‘swf‘: URL("/Scripts/js/Uploadify/js/uploadify3.2.1/uploadify.swf"),
32                     //文件选择后的容器ID
33                     ‘queueID‘: ‘uploadProcess‘,
34                     ‘uploader‘: baseActionPath + "UploadIn",
35                     ‘formData‘: { ‘sysUserID‘: sysUserID, ‘sysSiteDeptID‘: sysDeptID },
36                     ‘width‘: ‘75‘,
37                     ‘height‘: ‘24‘,
38                     ‘multi‘: false,
39                     ‘fileTypeDesc‘: ‘支持的格式:‘,
40                     ‘fileTypeExts‘: ‘*.xlsx;*.xls‘,
41                     ‘fileSizeLimit‘: ‘5MB‘,
42                     ‘removeTimeout‘: 2,
43                     ‘queueSizeLimit‘: 1,
44                     ‘successTimeout‘: 200,
45                     ‘onSelectError‘: function (file, errorCode, errorMsg) {
46                         switch (errorCode) {
47                             case -100:
48                                 alert("上传的文件数量已经超出系统限制的" + this.settings.queueSizeLimit + "个文件!");
49                                 break;
50                             case -110:
51                                 alert("文件 [" + file.name + "] 大小超出系统限制的" + this.settings.fileSizeLimit + "大小!");
52                                 break;
53                             case -120:
54                                 alert("文件 [" + file.name + "] 大小异常!");
55                                 break;
56                             case -130:
57                                 alert("文件 [" + file.name + "] 类型不正确!");
58                                 break;
59                         }
60                     },
61                     //检测FLASH失败调用
62                     ‘onFallback‘: function () {
63                         alert("您未安装FLASH控件,无法上传附件!请安装FLASH控件后再试。");
64                     },
65                     //上传到服务器,服务器返回相应信息到data里
66                     ‘onUploadSuccess‘: function (file, data, response) {
67                         if (data != "") {
68                             alert(data);
69                         }
70                         $h.dialog("close");
71                         CRUD.Read();
72                     }
73                 });
74             },
75             submit: false,
76             onBeforeClose: function () {
77                 $h.find(‘#uploadBTN‘).uploadify(‘destroy‘);
78             }
79         });
80     }

后端

C#代码 之controller方法

 1 /// <summary>
 2         /// 导入Excel数据
 3         /// </summary>
 4         /// <returns></returns>
 5         [HttpPost]
 6         public ActionResult UploadIn(string sysUserID, string sysSiteDeptID)
 7         {
 8             var ser = new MaterialsBLL();
 9             var _File = Request.Files[0];
10             var length = _File.ContentLength;
11             byte[] buffer = new byte[length];
12             _File.InputStream.Read(buffer, 0, length);
13             _File.InputStream.Close();
14 
15             var furl = ser.GetExcelData(buffer, sysUserID, sysSiteDeptID);
16 
17             return Content(furl);
18         }

bll层代码

  1         /// <summary>
  2         /// 导入Excel数据
  3         /// </summary>
  4         /// <param name="_FileContents"></param>
  5         /// <param name="sysUserID"></param>
  6         /// <param name="sysSiteDeptID"></param>
  7         /// <returns></returns>
  8         public string GetExcelData(byte[] _FileContents, string sysUserID, string sysSiteDeptID)
  9         {
 10             IWorkbook _Workbook;
 11             using (var _MemoryStream = new MemoryStream(_FileContents))
 12             {
 13                 _Workbook = new HSSFWorkbook(_MemoryStream);
 14             }
 15 
 16             ISheet _Sheet = _Workbook.GetSheetAt(0);
 17             int rowNum = _Sheet.LastRowNum;
 18 
 19             StringBuilder error_info = new StringBuilder();
 20 
 21             int add_count = 0;
 22 
 23             WL_Materials mod;
 24 
 25             try
 26             {
 27                 for (int rowIndex = 2; rowIndex <= rowNum; rowIndex++)
 28                 {
 29                     #region box
 30 
 31                     mod = new WL_Materials();
 32 
 33                     string materialID = GetStringCellValue(_Sheet, rowIndex, 0);
 34                     string materialName = GetStringCellValue(_Sheet, rowIndex, 1);
 35                     string materialTypeName = GetStringCellValue(_Sheet, rowIndex, 2);
 36                     string standard = GetStringCellValue(_Sheet, rowIndex, 3);
 37                     string type = GetStringCellValue(_Sheet, rowIndex, 4);
 38                     string unit = GetStringCellValue(_Sheet, rowIndex, 5);
 39                     string price = GetStringCellValue(_Sheet, rowIndex, 6);
 40                     string deptment = GetStringCellValue(_Sheet, rowIndex, 7);
 41                     if (string.IsNullOrEmpty(materialID) || string.IsNullOrEmpty(materialName) || string.IsNullOrEmpty(materialTypeName) || string.IsNullOrEmpty(unit) || string.IsNullOrEmpty(deptment))
 42                     {
 43                         error_info.Append("" + (rowIndex + 1) + "行有数据为空");
 44                         continue;
 45                     }
 46 
 47                     //var siteDept = CurrentUser.SiteDeptName;
 48 
 49                     mod.ID = materialID;
 50                     mod.MaterialName = materialName;
 51                     mod.MaterialTypeName = materialTypeName;
 52                     mod.Standard = standard;
 53                     mod.Type = type;
 54                     mod.Unit = unit;
 55                     if (!string.IsNullOrEmpty(price))
 56                     {
 57                         mod.Price = Convert.ToDecimal(price);
 58                     }
 59                     mod.Deptment = deptment;
 60                     //mod.Source = "导入";
 61                     mod.CreateID = sysUserID;
 62                     mod.IsDel = "N";
 63                     Repository.Add(mod, false);
 64 
 65                     #endregion
 66                 }
 67 
 68                 add_count = Repository.SaveChange();
 69                 return "导入" + add_count + "条成功;" + error_info.ToString();
 70             }
 71             catch (Exception ex)
 72             {
 73                 return ex.Message + "----------" + error_info.ToString();
 74             }
 75 
 76         }
 77 
 78         private string GetStringCellValue(ISheet _Sheet, int _RowIndex, int _CellNum)
 79         {
 80             try
 81             {
 82                 IRow _Row = _Sheet.GetRow(_RowIndex);
 83                 ICell _Cell = _Row.GetCell(_CellNum);
 84                 if (_Cell.IsMergedCell)
 85                     _Cell = this.GetMergedRegionValue(_Sheet, _RowIndex, _CellNum);
 86                 return this.GetStringCellValue(_Cell);
 87             }
 88             catch
 89             {
 90                 return string.Empty;
 91             }
 92         }
 93 
 94         /// <summary>
 95         /// 获取合并单元格的第一个单元格
 96         /// </summary>
 97         /// <param name="_Sheet"></param>
 98         /// <param name="rowIndex"></param>
 99         /// <param name="columnIndex"></param>
100         /// <returns></returns>
101         private ICell GetMergedRegionValue(ISheet _Sheet, int _RowIndex, int _ColumnIndex)
102         {
103             int sheetMergeCount = _Sheet.NumMergedRegions;
104 
105             for (int i = 0; i < sheetMergeCount; i++)
106             {
107                 CellRangeAddress _CellRangeAddress = _Sheet.GetMergedRegion(i);
108                 int _FirstColumn = _CellRangeAddress.FirstColumn;
109                 int _LastColumn = _CellRangeAddress.LastColumn;
110                 int _FirstRow = _CellRangeAddress.FirstRow;
111                 int _LastRow = _CellRangeAddress.LastRow;
112 
113                 if (_RowIndex >= _FirstRow && _RowIndex <= _LastRow)
114                 {
115 
116                     if (_ColumnIndex >= _FirstColumn && _ColumnIndex <= _LastColumn)
117                     {
118                         IRow _Row = _Sheet.GetRow(_FirstRow);
119                         ICell _Cell = _Row.GetCell(_FirstColumn);
120 
121                         return _Cell;
122                     }
123                 }
124             }
125             return null;
126         }
127 
128         private String GetStringCellValue(ICell _Cell)
129         {
130             string _Value = string.Empty;
131             try
132             {
133                 switch (_Cell.CellType)
134                 {
135                     case CellType.String:
136                         _Value = _Cell.StringCellValue;
137                         break;
138                     case CellType.Numeric:
139                         if (DateUtil.IsCellDateFormatted(_Cell))
140                             _Value = _Cell.DateCellValue.ToString("yyyy-MM-dd");
141                         else
142                             _Value = _Cell.NumericCellValue.ToString();
143                         break;
144                     case CellType.Boolean:
145                         _Value = _Cell.BooleanCellValue.ToString();
146                         break;
147                     case CellType.Formula:
148                         switch (_Cell.CachedFormulaResultType)
149                         {
150                             case CellType.String:
151                                 _Value = _Cell.StringCellValue;
152                                 break;
153                             case CellType.Numeric:
154                                 if (DateUtil.IsCellDateFormatted(_Cell))
155                                     _Value = _Cell.DateCellValue.ToString("yyyy-MM-dd");
156                                 else
157                                     _Value = _Cell.NumericCellValue.ToString();
158                                 break;
159                             case CellType.Boolean:
160                                 _Value = _Cell.BooleanCellValue.ToString();
161                                 break;
162                             case CellType.Unknown:
163                             case CellType.Blank:
164                             default:
165                                 _Value = string.Empty;
166                                 break;
167                         }
168                         break;
169                     case CellType.Unknown:
170                     case CellType.Blank:
171                     default:
172                         _Value = string.Empty;
173                         break;
174                 }
175             }
176             catch
177             {
178                 _Value = string.Empty;
179             }
180             return _Value;
181         }

 

以上是关于Excel之导入数据的主要内容,如果未能解决你的问题,请参考以下文章

python之EXCEL数据导入数据库

Excel之导入数据

「免费开源」基于Vue和Quasar的前端SPA项目crudapi后台管理系统实战之EXCEL数据导入

Excel批量导入数据之数据校验

Spring Boot下的一种导入Excel文件的代码框架

Vue小模块之功能全面的表格表格数据的Excel导入