C# .Net Excel上传&后台解析成DataTable

Http请求 讀取,解析

 1 [AcceptVerbs(HttpVerbs.Post)]
 2 public ActionResult importExcel()
 3 {
 4     try
 5     {
 6         HttpFileCollectionBase files = HttpContext.Request.Files;
 7         if (files != null)
 8         {
 9             foreach (string key in files.Keys)
10             {
11                 #region MyRegion
12                 HttpPostedFileBase fileData = files[key];
13                 if (fileData != null)
14                 {
15                     HttpContext.Request.ContentEncoding = Encoding.GetEncoding("UTF-8");
16                     HttpContext.Response.ContentEncoding = Encoding.GetEncoding("UTF-8");
17                     HttpContext.Response.Charset = "UTF-8";
18 
19                     //1. Excel 轉 DataTable
20                     Stream sileStream = fileData.InputStream;
21                     //string sheetName = "";
22                     string fileName = fileData.FileName;
23                     ExcelHelper excelHelper = new ExcelHelper();
24                     DataTable importedExcelDt = excelHelper.ExcelToDataTable("默認第一頁", 1, fileName, sileStream);
25                 }
26             }
27         }
28     }
29     catch (Exception ex)
30     {
31         string ls_ErrMsg = "--> *Exception Error:" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\r\n     Message:" + ex.Message;
32         Log4net.ErrorLog(ls_ErrMsg);//log 
33         return Json(new { IsSuccess = false, Message = "NG", Data = ex.Message });
34     }
35 }
View Code

Excel 转DataTable

  1 /// <summary>
  2     /// Excel To DataTable
  3     /// </summary>
  4     /// <param name="sheetName">默認第一頁</param>
  5     /// <param name="headerRow">表頭行 index</param>
  6     /// <param name="fileName"></param>
  7     /// <param name="sileStream"></param>
  8     /// <returns></returns>
  9     public DataTable ExcelToDataTable(string sheetName, int headerRow, string fileName, Stream sileStream)
 10     {
 11         ISheet sheet = null;
 12         DataTable data = new DataTable();
 13         int startRow = 0;
 14         try
 15         {
 16             //var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
 17             if (fileName.IndexOf(".xlsx") > 0)
 18                 workbook = new XSSFWorkbook(sileStream);
 19             else if (fileName.IndexOf(".xls") > 0)
 20                 workbook = new HSSFWorkbook(sileStream);
 21 
 22             if (sheetName != null)
 23             {
 24                 sheet = workbook.GetSheet(sheetName);
 25                 if (sheet == null)
 26                 {
 27                     sheet = workbook.GetSheetAt(0);
 28                 }
 29             }
 30             else
 31             {
 32                 sheet = workbook.GetSheetAt(0);
 33             }
 34             if (sheet != null)
 35             {
 36                 IRow firstRow = sheet.GetRow(1);
 37                 int cellCount = firstRow.LastCellNum;
 38 
 39                 for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
 40                 {
 41                     ICell cell = firstRow.GetCell(i);
 42                     if (cell != null)
 43                     {
 44                         string cellValue = "";
 45                         if (cell.CellType == CellType.Numeric)
 46                         {
 47                             cellValue = cell.NumericCellValue.ToString();
 48                         }
 49                         if (cell.CellType == CellType.Formula)
 50                         {
 51                             cellValue = cell.CellFormula.ToString();
 52                         }
 53                         else
 54                         {
 55                             cellValue = cell.StringCellValue;
 56                         }
 57                         if (cellValue != null)
 58                         {
 59                             DataColumn column = new DataColumn(cellValue);
 60                             data.Columns.Add(column);
 61                         }
 62                     }
 63                 }
 64                 
 65                 //startRow = headerRow + 1; //從第3行開始,根據表數據進行調整
 66 
 67 
 68                 int rowCount = sheet.LastRowNum;
 69                 for (int i = startRow; i <= rowCount; ++i)
 70                 {
 71                     IRow row = sheet.GetRow(i);
 72                     if (row == null) continue;
 73 
 74                     DataRow dataRow = data.NewRow();
 75                     for (int j = row.FirstCellNum; j < cellCount; ++j)
 76                     {
 77                         if (row.GetCell(j) == null)
 78                         {
 79                             dataRow[j] = "";
 80                             continue;
 81                         }
 82                         if (row.GetCell(j).CellType == CellType.Formula)
 83                         {
 84                             row.GetCell(j).SetCellType(CellType.String);
 85                             //dataRow[j] = row.GetCell(j).StringCellValue;
 86 
 87                             string r_num = row.GetCell(j).StringCellValue;
 88                             //double num= Convert.ToDouble(r_num);
 89                             //double r_num1 =Math.Round(Convert.ToDouble(r_num), 4, MidpointRounding.AwayFromZero);
 90                             string percentage = (Math.Round(Convert.ToDouble(row.GetCell(j).StringCellValue), 4, MidpointRounding.AwayFromZero) * 100) + "%";
 91                             dataRow[j] = percentage;
 92                             continue;
 93                         }
 94                         if (row.GetCell(j) != null)
 95                             dataRow[j] = row.GetCell(j).ToString();
 96                     }
 97                     data.Rows.Add(dataRow);
 98                 }
 99             }
100             //去除空行
101             data = RemoveEmpty(data);
102             return data;
103         }
104         catch (Exception ex)
105         {
106             Console.WriteLine("Exception: " + ex.Message);
107             return null;
108         }
109     }
View Code

去除空行数据

 1     /// <summary>
 2     /// 去除空行及之後的數據
 3     /// </summary>
 4     /// <param name="data"></param>
 5     /// <returns></returns>
 6     protected DataTable RemoveEmpty(DataTable data)
 7     {
 8         try
 9         {
10             int cutline = 0;
11             List<DataRow> removelist = new List<DataRow>();
12             for (int i = 0; i < data.Rows.Count; i++)
13             {
14                 bool IsNull = true;
15                 for (int j = 0; j < data.Columns.Count; j++)
16                 {
17                     if (!string.IsNullOrEmpty(data.Rows[i][j].ToString().Trim()))
18                     {
19                         IsNull = false;
20                     }
21                 }
22                 if (IsNull)
23                 {
24                     cutline = i;
25                     break;
26                     //removelist.Add(data.Rows[i]);
27                 }
28             }
29             DataTable cutDt = data.Clone();
30             if (cutline > 0)
31             {
32                 var query = data.AsEnumerable().Skip(0).Take(cutline);
33                 foreach (DataRow item in query)
34                 {
35                     cutDt.Rows.Add(item.ItemArray);
36                 }
37                 return cutDt;
38             }
39             return data;
40 
41             //for (int i = 0; i < removelist.Count; i++)
42             //{
43             //    data.Rows.Remove(removelist[i]);
44             //}
45             //return data;
46         }
47         catch (Exception ex)
48         {
49             return null;
50         }
51     }
View Code

猜你喜欢

转载自www.cnblogs.com/aDoc/p/12924613.html