ke_junjie
2025-06-04 101c57ec4c28bc3c36e49c50a926e9e7c0dd0247
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
using EnumType;
using NPOI.SS.UserModel;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
 
namespace IWareDataAccess.Helper
{
   public static  class ExcelHelper
    {
 
       public static bool UploadFiles(HttpPostedFile file,  string hostpath, out string msg)//
       {
           try
           {
               msg = "";
               if (file == null)
               {
                   msg="上传的文件为空,请重新上传";
                   return false;
               }
               string filename = Path.GetFileName(file.FileName);
               string fileEx = Path.GetExtension(filename);//获取上传文件的扩展名
               string NoFileName = Path.GetFileNameWithoutExtension(filename);//获取无扩展名的文件名
               string FileType = ".xls,.xlsx";//定义上传文件的类型字符串
               if (!FileType.Contains(fileEx))
               {
                   msg="无效的文件类型,只支持.xls和.xlsx文件";
                   return false;
               }
       
               //源数据
               MemoryStream msSource = new MemoryStream();
               var fstream = file.InputStream;
               byte[] b = new byte[fstream.Length];
               fstream.Read(b, 0, b.Length);
               msSource.Write(b, 0, b.Length);
               msSource.Seek(0, SeekOrigin.Begin);
               DataTable sourceExcel = ReadStreamToDataTable(msSource, "", true);
 
               //模板数据
               string dataDir = hostpath;//获得当前服务器程序的运行目录  
               dataDir = Path.Combine(dataDir, "ExcelTemplate");
               var path = dataDir + "//冲压计划.xlsx";
               MemoryStream msModel = new MemoryStream();
               FileStream stream = new FileStream(path, FileMode.Open);
               stream.CopyTo(msModel);
               msModel.Seek(0, SeekOrigin.Begin);
               DataTable templateExcel = ReadStreamToDataTable(stream, "", true);
               //验证是否同模板相同 
               string columnName = templateExcel.Columns[0].ColumnName;
               if (columnName != sourceExcel.Columns[0].ColumnName)
               {
                   msg="上传的模板文件不正确";
                   return false;
               }
               // 处理后台逻辑 执行 插入操作
 
     
               return true;
           }
           catch (Exception ex)
           {
                msg="上传的模板文件不正确";
                return false;
           }
       }
    
 
       public static DataTable ReadStreamToDataTable(Stream fileStream, string sheetName = null, bool isFirstRowColumn = true)
       {
           //定义要返回的datatable对象
           DataTable data = new DataTable();
           //excel工作表
           ISheet sheet = null;
           //数据开始行(排除标题行)
           int startRow = 0;
           try
           {
               //根据文件流创建excel数据结构,NPOI的工厂类WorkbookFactory会自动识别excel版本,创建出不同的excel数据结构
               IWorkbook workbook = WorkbookFactory.Create(fileStream);
               //如果有指定工作表名称
               if (!string.IsNullOrEmpty(sheetName))
               {
                   sheet = workbook.GetSheet(sheetName);
                   //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
                   if (sheet == null)
                   {
                       sheet = workbook.GetSheetAt(0);
                   }
               }
               else
               {
                   //如果没有指定的sheetName,则尝试获取第一个sheet
                   sheet = workbook.GetSheetAt(0);
               }
               if (sheet != null)
               {
                   IRow firstRow = sheet.GetRow(0);
                   //一行最后一个cell的编号 即总的列数
                   int cellCount = firstRow.LastCellNum;
                   //如果第一行是标题列名
                   if (isFirstRowColumn)
                   {
                       for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                       {
                           ICell cell = firstRow.GetCell(i);
                           if (cell != null)
                           {
                               string cellValue = cell.StringCellValue;
                               if (cellValue != null)
                               {
                                   DataColumn column = new DataColumn(cellValue);
                                   data.Columns.Add(column);
                               }
                           }
                       }
                       startRow = sheet.FirstRowNum + 1;
                   }
                   else
                   {
                       startRow = sheet.FirstRowNum;
                   }
                   //最后一列的标号
                   int rowCount = sheet.LastRowNum;
                   for (int i = startRow; i <= rowCount; ++i)
                   {
                       IRow row = sheet.GetRow(i);
                       if (row == null || row.FirstCellNum < 0) continue; //没有数据的行默认是null       
 
                       DataRow dataRow = data.NewRow();
                       for (int j = row.FirstCellNum; j < cellCount; ++j)
                       {
                           //同理,没有数据的单元格都默认是null
                           ICell cell = row.GetCell(j);
                           if (cell != null)
                           {
                               if (cell.CellType == CellType.Numeric)
                               {
                                   //判断是否日期类型
                                   if (DateUtil.IsCellDateFormatted(cell))
                                   {
                                       dataRow[j] = row.GetCell(j).DateCellValue;
                                   }
                                   else
                                   {
                                       dataRow[j] = row.GetCell(j).ToString().Trim();
                                   }
                               }
                               else
                               {
                                   dataRow[j] = row.GetCell(j).ToString().Trim();
                               }
                           }
                       }
                       data.Rows.Add(dataRow);
                   }
               }
               return data;
           }
           catch (Exception ex)
           {
               throw ex;
           }
 
       }
 
 
       public static List<object> FromExcelByEPPlus<T>(string path, string sheetname,T  t,out string msg)
       {
           msg = "";
 
           //文件不存在
           if (!File.Exists(path))
           {
               msg = "需要的excel文件不存在";
               return null;
           }
 
           //文件后缀不是xls或xlsx
           var fileSuffix = Path.GetExtension(path).ToUpper();
 
           if (!".XLS".Equals(fileSuffix) && !".XLSX".Equals(fileSuffix))
           {
               msg = "该文件不是excel文件";
               return null;
           }
 
           try
           {
               var result = new List<List<object>>();
               var package = new ExcelPackage(new FileInfo(path));
 
                var worksheet = package.Workbook.Worksheets[sheetname];
 
                if (worksheet == null || !sheetname.Equals(worksheet.Name))
                   {
                       msg = string.Format("未找到Excel工作页{0}", sheetname);
                       return null;
                   }
 
                Type type = t.GetType();
                var tProps = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
                var propNames = new List<string>();
                var tPropDic = new Dictionary<string, PropertyInfo>();
 
 
                   //遍历S的所有属性,将符合修改的存入字典中 
                tProps.ForEach(p => { propNames.Add(p.Name); tPropDic.Add(p.Name, p); });
 
                   var datas = new List<object>();
 
                   var dataStartLine = 2;
 
                   //是否到最后一行
                   bool endOfLine = false;
 
                   //当前行数
                   int lineIndex = 0;
 
                   while (!endOfLine)
                   {
                       //判断是否为空数据
                       bool nullFlag = true;
 
                       var data = type.Assembly.CreateInstance(type.ToString());
 
                       for (int j = 0; j < propNames.Count; j++)
                       {
                           var workCell = tPropDic[propNames[j]];
 
                           object value = ((ExcelRangeBase)worksheet.Cells[dataStartLine + lineIndex, j + 1]).Value;
                           var pty = workCell.PropertyType.FullName;//获得属性的类型
                           if (value != null && !string.IsNullOrEmpty(value.ToString()))
                           {
                               nullFlag = false;
                               if (pty == typeof(int).FullName)
                               {
                                   value = Convert.ToInt32(value.ToString().Trim());
                               }
                               else if (pty == typeof(double).FullName)
                               {
                                   value = Convert.ToDouble(value.ToString().Trim());
                               }
                               else if (pty == typeof(DateTime).FullName)
                               {
                                   value = Convert.ToDateTime(value.ToString().Trim());
                               }
                               else if (pty == typeof(string).FullName)
                               {
                                   value = value.ToString().Trim();
                                   if (value.ToString().EndsWith("\r\n"))
                                   {
                                       value = value.ToString().Substring(0, value.ToString().Length - 2);
                                   }
                               }
                               tPropDic[propNames[j]].SetValue(data, value, null);
                           }
                           else
                           {
                               if (pty == typeof(int).FullName)
                               {
                                   value = 0;
                    
                               }
                               else if (pty == typeof(double).FullName)
                               {
                                   value = 0.0;
                               }
                               else if (pty == typeof(DateTime).FullName)
                               {
                                   value = DateTime.Now; ;
                               }
                               else if (pty == typeof(string).FullName)
                               {
                                   value = "";
                               }
 
                               tPropDic[propNames[j]].SetValue(data, value, null);
                           }
                       }
                       if (!nullFlag)
                       {
                           datas.Add(data);
                           lineIndex++;
                           continue;
                       }
                       endOfLine = true;
                   }
 
 
               return datas;
           }
           catch (Exception ex)
           {
               msg = ex.Message;
               return null;
           }
       }
 
    }
}