NPOI 1.1

1 .NPOI 版本2.1

2. NPOI 读取execl 

3.导入数据(SqlBulkCopy)

示例代码:

  1 public class ImportServerData
  2     {
  3 
  4         DataTable dt_ItemInfo = new DataTable();
  5 
  6         public StringBuilder WaringMsg { get; set; }
  7 
  8         public string ParentDeptCode { get; set; }
  9         /// <summary>
 10         /// 初始化结构
 11         /// </summary>
 12         public ImportServerData()
 13         {
 14             #region dt_ItemInfo
 15             dt_ItemInfo.Columns.Add("ID", typeof(string));
 16             dt_ItemInfo.Columns.Add("NeedUnit", typeof(string));
 17             dt_ItemInfo.Columns.Add("ItemType", typeof(string));
 18             dt_ItemInfo.Columns.Add("Name", typeof(string));
 19             dt_ItemInfo.Columns.Add("ItemInfo", typeof(string));
 20             dt_ItemInfo.Columns.Add("Leader", typeof(string));
 21             dt_ItemInfo.Columns.Add("SugDoUnit", typeof(string));
 22             dt_ItemInfo.Columns.Add("State", typeof(int));
 23             dt_ItemInfo.Columns.Add("LinkMan", typeof(string));
 24             dt_ItemInfo.Columns.Add("IsDel", typeof(string));
 25             dt_ItemInfo.Columns.Add("IsShow", typeof(string));
 26             dt_ItemInfo.Columns.Add("AddTime", typeof(DateTime));
 27             dt_ItemInfo.Columns.Add("SourceType", typeof(string));
 28             dt_ItemInfo.Columns.Add("ParentDeptCode", typeof(string));
 29             dt_ItemInfo.Columns.Add("OperateSpeed", typeof(string));
 30             dt_ItemInfo.Columns.Add("Approval", typeof(string));
 31             dt_ItemInfo.Columns.Add("Year", typeof(int));
 32             dt_ItemInfo.Columns.Add("LinkTel", typeof(string));
 33             dt_ItemInfo.Columns.Add("SugDoUnitMan", typeof(string));
 34             dt_ItemInfo.Columns.Add("SugDoUnitTel", typeof(string));
 35             dt_ItemInfo.Columns.Add("NodeState", typeof(string));
 36             dt_ItemInfo.Columns.Add("Remark", typeof(string));
 37             dt_ItemInfo.Columns.Add("SugDoUnitName", typeof(string));
 38             dt_ItemInfo.Columns.Add("Source", typeof(string));
 39             dt_ItemInfo.AcceptChanges();
 40             #endregion
 41         }
 42 
 43         /// <summary>
 44         /// 将excel中的数据导入到DataTable中
 45         /// </summary>
 46         /// <returns>返回的DataTable</returns>
 47         public bool ExcelToDataTable(string fileName)
 48         {
 49             ISheet sheet = null;
 50             FileStream fs;
 51             //事件类型  来源
 52             string sql = "select Id,Name From  dbo.Per_Dictionary where type in ('36','37')";
 53             DataTable dtDictionary = Ruihua.Common.DapperHelper.Query(sql).Tables[0];
 54 
 55             //需求部门
 56             string sqlbaseinfo = "select Id,unitName Name from dbo.DS_DW_BaseIfo ";
 57             DataTable dtBaseInfo = Ruihua.Common.DapperHelper.Query(sqlbaseinfo).Tables[0];
 58 
 59             //承办单位
 60             string sqlSugDoUnit = "select ArchitectureId Id, Caption Name  From dbo.Architecture";
 61             DataTable dtSugDoUnit = Ruihua.Common.DapperHelper.Query(sqlSugDoUnit).Tables[0];
 62 
 63             //领导
 64             string sqlleader = "select Id,username Name From  usr_user  ";
 65             DataTable dtLeader = Ruihua.Common.DapperHelper.Query(sqlleader).Tables[0];
 66 
 67             bool flag = false;
 68             string currindex = "";
 69             try
 70             {
 71                 fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
 72                 HSSFWorkbook workbook = new HSSFWorkbook(fs);
 73 
 74                 for (int i = 0; i < 3; i++)
 75                 {
 76                     sheet = workbook.GetSheetAt(i);
 77 
 78                     System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
 79                     string scouretext = (i == 0 ? "市外联办研提事项" : i == 1 ? "区领导走访征询事项" : "中央单位来函事项");
 80                     var scoureDr = dtDictionary.AsEnumerable().Where(w => w.Field<string>("Name") == scouretext).FirstOrDefault();
 81                     string scoureId = scoureDr != null ? scoureDr["Id"].ToString() : "";
 82                     int year = 0;
 83                     int index = 0;
 84                     while (rows.MoveNext())
 85                     {
 86                         IRow row = (HSSFRow)rows.Current;
 87                         currindex = GetValue<string>(row, 0, 0);
 88                         if (currindex == "") continue;
 89                         if (index == 0)
 90                         {
 91                             string name = GetValue<string>(row, index, 100);
 92                             if (name != "") year = Convert.ToInt32(name.Substring(0, 4));
 93                         }
 94                         string waringinfo = "";
 95                         if (index >= 2)
 96                         {
 97                             
 98                             string guid = Guid.NewGuid().ToString();
 99                          
100                             #region 需求单位 1
101                            
102                             string unitname = Regex.Replace(GetValue<string>(row, 1, 0), @"s", "");
103 
104                           
105 
106                             string needunitId = "";
107                             bool isneedunit = false;
108                             for (int n = 0; n < dtBaseInfo.Rows.Count; n++)
109                             {
110                                 bool falg = false;
111                                 for (int j = 0; j < unitname.Length; j++)
112                                 {
113                                     string result = IsMatch(dtBaseInfo.Rows[n]["Name"].ToString(), unitname[j].ToString());
114                                     if (result == "")
115                                     {
116                                         break;
117                                     }
118                                     else
119                                     {
120                                         falg = true;
121                                     }
122                                     if (unitname.Length - 1 == j && falg)
123                                     {
124                                         //这里只需要一条数据 就跳出循环
125                                         isneedunit = true;
126                                         needunitId = dtBaseInfo.Rows[n]["Id"].ToString();
127                                         break;
128 
129                                     }
130                                     if (isneedunit) break;
131                                 }
132 
133                             }
134                            
135                             if (needunitId == "")
136                             {
137                                 waringinfo += "[需求单位匹配失败]";
138                             }
139                             #endregion
140 
141                             #region 事项类型
142                             //事项类型(有多个类型) 3 、
143 
144                             string itemtypename = GetValue<string>(row, 3, 0).Replace("
", "").Replace("
", "");
145                             string[] itemNames = itemtypename != "" ? Regex.Replace( itemtypename, @"s", "" ).Split('') : null;
146                             string itemTypeId = "";
147                             if (itemNames != null)
148                             {
149                                 var itemTypeDr = dtDictionary.AsEnumerable().Where(w => itemNames.Contains(w.Field<string>("Name")));
150 
151                                 if (itemTypeDr == null || itemTypeDr.Count() == 0)
152                                 {
153                                     waringinfo += "[事项类型匹配失败多个类型用、分割]";
154                                 }
155                                 else
156                                 {
157                                     foreach (var item in itemTypeDr)
158                                     {
159                                         itemTypeId += item != null ? item["Id"].ToString() + "," : "";
160                                     }
161                                     itemTypeId = itemTypeId.Substring(0, itemTypeId.Length - 1);
162                                 }
163                             }
164                             else
165                             {
166                                 waringinfo += "[事项类型匹配失败多个类型用、分割]";
167                             }
168                             #endregion
169 
170                             //承办单位 7
171                             var itemSugDoUnit = dtSugDoUnit.AsEnumerable().Where(w => w.Field<string>("Name") == GetValue<string>(row, 7, 0)).FirstOrDefault();
172                             string sugDoUnitId = "";
173                             if (itemSugDoUnit != null)
174                             {
175                                 sugDoUnitId = itemSugDoUnit["Id"].ToString();
176                             }
177                             //else{
178                             //    waringinfo += "[承办单位匹配失败]";
179                             //}
180                             string SugDoUnitName = GetValue<string>(row, 7, 100);
181                             if (SugDoUnitName == "" && sugDoUnitId == "")
182                             {
183                                 waringinfo += "[承办单位不能为空]";
184                             }
185                             //主管区领导 6
186                             var itemLeader = dtLeader.AsEnumerable().Where(w => w.Field<string>("Name") == GetValue<string>(row, 6, 0)).FirstOrDefault();
187                             string leaderId = "";
188                             if (itemLeader != null)
189                             {
190                                 leaderId = itemLeader["Id"].ToString();
191                             }
192                             else
193                             {
194                                 waringinfo += "[主管区领导匹配失败]";
195                             }
196                             string ItemName = GetValue<string>(row, 2, 100);
197                             if (ItemName == "ERROROVERTOP")
198                             {
199                                 waringinfo += "[事项名称字符超出]";
200                             }
201                             string ItemInfo = GetValue<string>(row, 4, 4000);
202                             if (ItemInfo == "ERROROVERTOP")
203                             {
204                                 waringinfo += "[需求事项字符超出]";
205                             }
206                             int State = GetStateByName(GetValue<string>(row, 8, 15).Trim());
207                             if (State == -1)
208                             {
209                                 waringinfo += "[办理状态匹配失败]";
210                             }
211                             string LinkMan = GetValue<string>(row, 10, 200);
212                             if (LinkMan == "ERROROVERTOP")
213                             {
214                                 waringinfo += "[中央单位联系人字符超出]";
215                             }
216                             string OperateSpeed = GetValue<string>(row, 9, 2000);
217                             if (OperateSpeed == "ERROROVERTOP")
218                             {
219                                 waringinfo += "[办理结果(进展情况)字符超出]";
220                             }
221                             //string cc = MergedRegionValue(sheet, index,5);
222                             string Approval = MergedRegionValue(sheet, index, 5);
223                             if (Approval == "ERROROVERTOP")
224                             {
225                                 waringinfo += "[领导批示字符超出]";
226                             }
227                             string LinkTel = GetValue<string>(row, 11, 50);
228                             if (LinkTel == "ERROROVERTOP")
229                             {
230                                 waringinfo += "[联系电话字符超出]";
231                             }
232                             string SugDoUnitMan = GetValue<string>(row, 12, 200);
233                             if (SugDoUnitMan == "ERROROVERTOP")
234                             {
235                                 waringinfo += "[承办单位联系人字符超出]";
236                             }
237                             string SugDoUnitTel = GetValue<string>(row, 13, 50);
238                             if (SugDoUnitTel == "ERROROVERTOP")
239                             {
240                                 waringinfo += "[联系电话字符超出]";
241                             }
242                             string Remark = GetValue<string>(row, 14, 500);
243                             if (Remark == "ERROROVERTOP")
244                             {
245                                 waringinfo += "[备注字符超出]";
246                             }
247                             if (waringinfo != "")
248                             {
249                                 string sheetname = (i == 0 ? "研提事项" : i == 1 ? "走访(来访)事项" : "来函事项");
250                                 if (WaringMsg == null)
251                                 {
252                                     WaringMsg = new StringBuilder();
253                                 }
254                                 WaringMsg.Append(sheetname + "提示信息:序号[" + currindex + "]" + waringinfo + "
");
255                             }
256 
257 
258                             if (waringinfo == "")
259                             {
260                                 //处理ItemInfo
261                                 dt_ItemInfo.Rows.Add(guid,
262                                     needunitId,
263                                     itemTypeId,
264                                     ItemName,
265                                     ItemInfo,
266                                     leaderId,
267                                     sugDoUnitId,
268                                     State,
269                                     LinkMan,
270                                     0, 1,
271                                     DateTime.Now,
272                                     1, ParentDeptCode,
273                                     OperateSpeed,
274                                     Approval, year,
275                                     LinkTel,
276                                     SugDoUnitMan,
277                                     SugDoUnitTel,
278                                     GetNodeStateByName(GetValue<string>(row, 9, 200)),
279                                     Remark,
280                                     SugDoUnitName,
281                                     scoureId
282                                     );
283                             }
284 
285                            
286                         }
287                         index++;
288                     }
289 
290                 }
291                 dt_ItemInfo.AcceptChanges();
292                 flag = true;
293             }
294             catch (Exception ex)
295             {
296                 flag = false;
297                 Ruihua.Log4Net.LogHelper.SaveLogError(new Log4Net.LogMessage { Info = "Exception: " + currindex + "序号" + ex.Message.ToString(), UserID = "" });
298             }
299             return flag;
300         }
301         private string MergedRegionValue(ISheet sheet, int rowNum, int colNum)
302         {
303             for (int i = 0; i < sheet.NumMergedRegions; i++)
304             {
305                 CellRangeAddress range = sheet.GetMergedRegion(i);
306                 sheet.IsMergedRegion(range);
307                 if (range != null)
308                 {
309                     if (range.FirstRow <= rowNum && range.LastRow >= rowNum && range.FirstColumn <= colNum && range.LastColumn >= colNum)
310                     {
311 
312                         return sheet.GetRow(range.FirstRow).GetCell(range.FirstColumn).StringCellValue.ToString();
313                     }
314                 }
315             }
316             return "";
317         }
318 
319         private string GetValue<T>(IRow row, int index, int strlength)
320         {
321 
322             string result = "";
323 
324             if (typeof(string) == typeof(T))
325             {
326                 ICell cell = row.GetCell(index);
327                 if (cell != null)
328                 {
329                     if (cell.IsMergedCell)
330                     {
331                         result = cell.StringCellValue.ToString();
332                     }
333                     else if (strlength == 0)
334                     {
335                         result = cell.ToString();
336                     }
337                     else if (strlength > 0 && cell.ToString().Length < strlength)
338                     {
339                         result = cell.ToString();
340                     }
341                     else
342                     {
343                         result = "ERROROVERTOP";
344                     }
345                 }
346             }
347             else if (typeof(int) == typeof(T))
348             {
349                 ICell cell = row.GetCell(index);
350 
351                 if (cell != null)
352                 {
353                     if (IsInteger(cell.ToString()))
354                     {
355                         result = cell.ToString();
356 
357                     }
358                 }
359             }
360             else if (typeof(DateTime) == typeof(T))
361             {
362                 ICell cell = row.GetCell(index);
363 
364                 if (cell != null)
365                 {
366                     if (IsDatetTime(cell.ToString()))
367                     {
368                         result = cell.ToString();
369 
370                     }
371                 }
372             }
373             return result;
374         }
375 
376         private int GetStateByName(string name)
377         {
378             int result = -1;
379             switch (name)
380             {
381                 case "未办结":
382                 case "以主动对接,建立工作关系":
383                 case "召开专项协调会":
384                 case "组织现场踏勘":
385                 case "正在处理":
386                 case "正在商有关单位":
387                     result = 0;
388                     break;
389                 case "已办结":
390                 case "已办结并反馈":
391                     result = 1;
392                     break;
393                 case "现行政策不能办理":
394                     result = 2;
395                     break;
396             }
397             return result;
398         }
399 
400         private string GetNodeStateByName(string name)
401         {
402             string NodeState = "";
403 
404             string[] nodename = name.Split(',');
405             for (int i = 0; i < nodename.Length; i++)
406             {
407                 switch (nodename[i].Trim())
408                 {
409                     case "以主动对接,建立工作关系":
410                         NodeState += "0,";
411                         break;
412                     case "召开专项协调会":
413                         NodeState += "1,";
414                         break;
415                     case "组织现场踏勘":
416                         NodeState += "2,";
417                         break;
418                     case "正在处理":
419                         NodeState += "3,";
420                         break;
421                     case "正在商有关单位":
422                         NodeState += "4,";
423                         break;
424                     case "已办结":
425                         NodeState += "5,";
426                         break;
427                     case "已办结并反馈":
428                         NodeState += "6,";
429                         break;
430 
431                 }
432             }
433             return NodeState.Length > 1 ? NodeState.Substring(0, NodeState.Length - 1) : NodeState;
434         }
435 
436         /// 
437         /// </summary>
438         /// <param name="connectionString">目标连接字符</param>
439         /// <param name="TableName">目标表</param>
440         /// <param name="dt">源数据</param>
441         private void SqlBulkCopyByDatatable(string connectionString, string TableName, DataTable dt)
442         {
443             using (SqlConnection conn = new SqlConnection(connectionString))
444             {
445                 using (SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction))
446                 {
447                     try
448                     {
449                         sqlbulkcopy.DestinationTableName = TableName;
450                         sqlbulkcopy.BulkCopyTimeout = 120;
451                         sqlbulkcopy.BatchSize = 600;
452                         for (int i = 0; i < dt.Columns.Count; i++)
453                         {
454                             sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName);
455                         }
456                         sqlbulkcopy.WriteToServer(dt);
457                     }
458                     catch (System.Exception ex)
459                     {
460                         throw ex;
461                     }
462                 }
463             }
464         }
465 
466         /// <summary>  
467         /// 验证整数  
468         /// </summary>  
469         /// <param name="input">待验证的字符串</param>  
470         /// <returns>是否匹配</returns>  
471         public static bool IsInteger(string input)
472         {
473 
474             bool foundMatch = false;
475             try
476             {
477                 foundMatch = Regex.IsMatch(input, @"-?d+$");
478             }
479             catch (ArgumentException ex)
480             {
481                 // Syntax error in the regular expression
482             }
483             return foundMatch;
484         }
485 
486         /// <summary>
487         /// 验证日期 yyyy-MM-dd
488         /// </summary>
489         /// <param name="input"></param>
490         /// <returns></returns>
491         public static bool IsDatetTime(string input)
492         {
493 
494             bool foundMatch = false;
495             try
496             {
497                 foundMatch = Regex.IsMatch(input, "(19|20)[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])");
498             }
499             catch (ArgumentException ex)
500             {
501                 // Syntax error in the regular expression
502             }
503             return foundMatch;
504         }
505 
506         public string ImportData(string fileName)
507         {
508             try
509             {
510                 ExcelToDataTable(fileName);
511                 int count = dt_ItemInfo.Rows.Count;
512                 if (count > 0)
513                 {
514                     SqlBulkCopyByDatatable(DapperHelper.connectionString, "DS_FW_ItemInfo", dt_ItemInfo);
515 
516                     return "成功导入:" + count.ToString() + "条数据!
" + (WaringMsg != null ? WaringMsg.ToString() : "");
517 
518                 }
519                 else
520                 {
521                     return WaringMsg != null ? WaringMsg.ToString() : "NO";
522                 }
523             }
524             catch (Exception)
525             {
526             }
527             return WaringMsg != null ? WaringMsg.ToString() : "NO";
528         }
529 
530         public string IsMatch(string inputstr, string regexstr)
531         {
532 
533             if (Regex.IsMatch(inputstr, regexstr))
534             {
535                 return inputstr;
536             }
537             return "";
538         }
539     }
原文地址:https://www.cnblogs.com/linsu/p/4664425.html