c# 导入导出excel方法封装
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 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 | public class ExportAttribute : Attribute { public ExportAttribute( bool needExport = true ) { _NeedExport = needExport; } private bool _NeedExport { set ; get ; } /// /// 是否需要导出的字段 /// public bool NeedExport { get { return _NeedExport; } set { _NeedExport = value; } } } /// /// 导出excel帮助类 /// /// public class ExcelHelper { /// /// 属性描述与类集合缓存 /// private static Dictionary<Type, List> _propertyNameDic; /// /// 属性与类集合缓存 /// private static Dictionary<Type, PropertyInfo[]> _propertyDic; /// /// 属性与描述对应关系集合缓存 /// public static Dictionary<Type, List> _displayMappProperty; private string fileName = null ; //文件名 private HSSFWorkbook workbook = null ; private XSSFWorkbook xworkbook = null ; private FileStream fs = null ; private bool disposed; public ExcelHelper() { } /// /// 有参构造函数 导入EXCEL 时使用 /// /// public ExcelHelper( string fileName) { this .fileName = fileName; disposed = false ; } /// /// 将excel中的数据导入到实体集合中 /// 使用说明:1.传入的实体属性中displayName描述对应excel中的列名 /// ///文件 ///sheet名称 ///起始第一行(excel列名开始行) ///返回的指定的实体集合 public List ExcelToModel(HttpPostedFileBase file, string sheetName = null , int firstRow = 0) where T : new () { var models = new List(); DataTable data = new DataTable(); try { using (Stream fs = file.InputStream) { fileName = file.FileName; var fileNameArray = fileName.Split( '.' ); if (fileNameArray.Length == 2) { ISheet sheet = null ; if (fileNameArray[1].ToLower().Trim() == "xls" ) { workbook = new HSSFWorkbook(fs); if (sheetName != null ) { sheet = xworkbook.GetSheet(sheetName); if (sheet == null ) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet { sheet = xworkbook.GetSheetAt(0); } } else { sheet = xworkbook.GetSheetAt(0); } } else { xworkbook = new XSSFWorkbook(fs); if (sheetName != null ) { sheet = xworkbook.GetSheet(sheetName); if (sheet == null ) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet { sheet = xworkbook.GetSheetAt(0); } } else { sheet = xworkbook.GetSheetAt(0); } } models = GetModel(sheet, models, firstRow); } else { return null ; } } return models; } catch (Exception ex) { Console.WriteLine( "Exception: " + ex.Message); return null ; } } /// /// 保存文件到本地,并且数据转化为实体 /// ///文件 ///文件保存路径 ///sheet名称 ///起始第一行(excel列名开始行) /// public List ExcelToModelAndSave(HttpPostedFileBase file, string savePath, string sheetName = null , int firstRow = 0) where T : new () { var models = new List(); DataTable data = new DataTable(); if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } try { using (Stream fs = file.InputStream) { fileName = file.FileName; var fileNameArray = fileName.Split( '.' ); if (fileNameArray.Length == 2) { ISheet sheet = null ; if (fileNameArray[1].ToLower().Trim() == "xls" ) { savePath = $ "{savePath}\\{DateTime.Now.ToString(" dd-HH-mm-ss ")}.xls" ; workbook = new HSSFWorkbook(fs); if (sheetName != null ) { sheet = xworkbook.GetSheet(sheetName); if (sheet == null ) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet { sheet = xworkbook.GetSheetAt(0); } } else { sheet = xworkbook.GetSheetAt(0); } } else { savePath = $ "{savePath}\\{DateTime.Now.ToString(" dd-HH-mm-ss ")}.xlsx" ; xworkbook = new XSSFWorkbook(fs); if (sheetName != null ) { sheet = xworkbook.GetSheet(sheetName); if (sheet == null ) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet { sheet = xworkbook.GetSheetAt(0); } } else { sheet = xworkbook.GetSheetAt(0); } } models = GetModel(sheet, models, firstRow); } else { return null ; } } file.SaveAs(savePath); return models; } catch (Exception ex) { Console.WriteLine( "Exception: " + ex.Message); return null ; } } /// /// 导出Excel /// 使用说明:1.实体中属性的displayName为导出excel中对应的列名,如果没有则按照属性名称 /// 2.实体的属性最好都是字符串或者数字类型的,在展示过程中,不会进行数据转化 /// ///需要导出的实体模型(实体的属性最好都是字符串或者数字类型的,在展示过程中,不会进行数据转化) ///请求上下文 ///导出的文件名(默认时间) ///文件头备注 ///文件底部备注(eg:统计数据的添加) public void Export(List models, HttpResponseBase Response, string fileName, string remark, string addUp) { //首先获取excel中的列名 Type type = typeof (T); List propertyNames = GetDisplayNames(type); //Create a new workbook var workbook = new XSSFWorkbook(); //create a new sheet var sheet = workbook.CreateSheet( "User Accounts" ); // Add header labels var rowIndex = 0; var rowLength = 0; //存储文件头备注 if (! string .IsNullOrEmpty(remark)) { var rowRemark = sheet.CreateRow(rowIndex); rowRemark.CreateCell(rowIndex).SetCellValue(remark); //合并单元格 sheet.AddMergedRegion( new CellRangeAddress(0, 0, 0, propertyNames.Count - 1)); rowIndex++; } var row = sheet.CreateRow(rowIndex); //存储列名 foreach ( var propertyName in propertyNames) { row.CreateCell(rowLength).SetCellValue(propertyName); rowLength++; } //存储值 var propertieValues = _propertyDic[type]; foreach ( var model in models) { rowIndex++; row = sheet.CreateRow(rowIndex); for ( var m = 0; m < rowLength; m++) { var value = propertieValues[m].GetValue(model, null ); row.CreateCell(m).SetCellValue(value?.ToString()); } } //存储文件尾备注(EG:统计数据) if (! string .IsNullOrEmpty(addUp)) { row = sheet.CreateRow(rowIndex + 1); row.CreateCell(0).SetCellValue(addUp); //合并单元格 sheet.AddMergedRegion( new CellRangeAddress(rowIndex + 1, rowIndex + 2, 0, propertyNames.Count - 1)); } fileName = $ "{fileName}{DateTime.Now.ToString(" yyyy-MM-dd-HH-mm-ss ")}" ; ExportExcel(workbook, Response, fileName); } /// /// 导出文件到浏览器 /// /// /// ///文件名称 private void ExportExcel(XSSFWorkbook workbook, HttpResponseBase Response, string fileName) { using ( var exportData = new MemoryStream()) { workbook.Write(exportData); Response.Buffer = true ; Response.Clear(); Response.ClearHeaders(); Response.ClearContent(); //response.ContentType = "application/ms-excel"; Response.ContentType = "application/vnd.openxmlformats - officedocument.spreadsheetml.sheet" ; Response.AppendHeader( "Content-Type" , "text/html; charset=GB2312" ); Response.AddHeader( "Content-Disposition" , string .Format( "attachment; filename={0}.xlsx" , fileName)); Response.Charset = "GB2312" ; Response.ContentEncoding = Encoding.GetEncoding( "GB2312" ); Response.BinaryWrite(exportData.GetBuffer()); Response.Flush(); } } /// /// 根据类型获取实体的描述集合 /// ///类型 private List GetDisplayNames(Type type) { List propertyNames = new List(); if (_propertyNameDic != null && _propertyNameDic.ContainsKey(type)) { propertyNames = _propertyNameDic[type]; } else { var properties = type.GetProperties(); var propertyResult = new List(); propertyNames = GetDisplayNames(properties, out propertyResult); //添加到缓存 if (_propertyNameDic == null ) { _propertyNameDic = new Dictionary<Type, List>(); } if (_propertyDic == null ) { _propertyDic = new Dictionary<Type, PropertyInfo[]>(); } _propertyNameDic.Add(type, propertyNames); _propertyDic.Add(type, propertyResult.ToArray()); } return propertyNames; } /// /// 获取属性描述对应关系 /// ///类型 public List GetMapping(Type type) { List mapping = new List(); if (_displayMappProperty != null && _displayMappProperty.ContainsKey(type)) { mapping = _displayMappProperty[type]; } else { var properties = type.GetProperties(); mapping = GetMapping(properties); //添加到缓存 if (_displayMappProperty == null ) { _displayMappProperty = new Dictionary<Type, List>(); } if (_propertyDic == null ) { _propertyDic = new Dictionary<Type, PropertyInfo[]>(); } _displayMappProperty.Add(type, mapping); _propertyDic.Add(type, properties); } return mapping; } /// /// 获取实体的描述集合 /// ///实体属性组 private List GetDisplayNames(PropertyInfo[] propertyInfos, out List propertyInfoList) { List propertyNames = new List(); propertyInfoList = new List(); if (propertyInfos != null ) { for ( var i = 0; i < propertyInfos.Length; i++) { //判断是否是不需要导出的字段 var expoertAttribute = propertyInfos[i].GetCustomAttribute(); if (expoertAttribute == null || expoertAttribute.NeedExport) { var propertyName = propertyInfos[i].GetCustomAttribute(); if (propertyName != null && ! string .IsNullOrEmpty(propertyName.DisplayName)) { propertyNames.Add(propertyName.DisplayName); } else { propertyNames.Add(propertyInfos[i].Name); } propertyInfoList.Add(propertyInfos[i]); } } } return propertyNames; } /// /// 获取实体中的属性和描述对应关系数据 /// ///属性集合 private List GetMapping(PropertyInfo[] propertyInfos) { List mapping = new List(); if (propertyInfos != null ) { for ( var i = 0; i < propertyInfos.Length; i++) { var propertyName = propertyInfos[i].GetCustomAttribute(); if (propertyName != null && ! string .IsNullOrEmpty(propertyName.DisplayName)) { mapping.Add( new DisplayMappProperty { Property = propertyInfos[i], DisplayName = propertyName.DisplayName }); } } } return mapping; } /// /// 获取excel中映射的实体数据 /// /// /// /// /// /// private List GetModel(ISheet sheet, List models, int firstRowNum = 0) where T : new () { //首先获取excel中的列名 Type type = typeof (T); List mappings = GetMapping(type); int startRow = 0; if (sheet != null ) { IRow firstRow = sheet.GetRow(firstRowNum); //一行最后一个cell的编号 即总的列数 int cellCount = firstRow.LastCellNum; var cellValues = new string [cellCount]; //获取excel中的列名 for ( int i = firstRow.FirstCellNum; i < cellCount; i++) { ICell cell = firstRow.GetCell(i); if (cell != null ) { string cellValue = cell.StringCellValue; if (cellValue != null ) { cellValues[i] = cellValue; } } } //数据开始行 startRow = firstRowNum + 1; //最后一行的标号 int rowCount = sheet.LastRowNum; //读取数据 for ( int i = startRow; i <= rowCount; i++) { var singT = new T(); IRow row = sheet.GetRow(i); if (row == null ) continue ; //没有数据的行默认是null for ( int j = row.FirstCellNum; j < cellCount; j++) { //获取Excel中列名 var cellValue = "" ; if (j < cellValues.Length) { cellValue = cellValues[j]; } if (row.GetCell(j) != null ) //同理,没有数据的单元格都默认是null //给实体赋值 { //根据列名找到对应关系的属性值 var property = mappings.FirstOrDefault(n => n.DisplayName == cellValue)?.Property; if (property != null ) { property.SetValue(singT, row.GetCell(j)?.ToString()); } } } models.Add(singT); } } return models; } } /// /// 将excel转化为DataTable /// public class ExcelHelper : IDisposable { private string fileName = null ; //文件名 private IWorkbook workbook = null ; private FileStream fs = null ; private bool disposed; public ExcelHelper( string fileName) { this .fileName = fileName; disposed = false ; } /// /// 将excel中的数据导入到实体中 /// ///excel工作薄sheet的名称 ///第一行是否是DataTable的列名 /// 返回的DataTable public DataTable ExcelToDataTable( string sheetName = null , bool isFirstRowColumn = true ) { ISheet sheet = null ; DataTable data = new DataTable(); int startRow = 0; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); if (fileName.IndexOf( ".xlsx" ) > 0) // 2007版本 workbook = new XSSFWorkbook(fs); else if (fileName.IndexOf( ".xls" ) > 0) // 2003版本 workbook = new HSSFWorkbook(fs); if (sheetName != null ) { sheet = workbook.GetSheet(sheetName); if (sheet == null ) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet { sheet = workbook.GetSheetAt(0); } } else { sheet = workbook.GetSheetAt(0); } if (sheet != null ) { IRow firstRow = sheet.GetRow(0); int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数 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 ) continue ; //没有数据的行默认是null DataRow dataRow = data.NewRow(); for ( int j = row.FirstCellNum; j < cellCount; ++j) { if (row.GetCell(j) != null ) //同理,没有数据的单元格都默认是null dataRow[j] = row.GetCell(j).ToString(); } data.Rows.Add(dataRow); } } return data; } catch (Exception ex) { Console.WriteLine( "Exception: " + ex.Message); return null ; } } public void Dispose() { Dispose( true ); GC.SuppressFinalize( this ); } protected virtual void Dispose( bool disposing) { if (! this .disposed) { if (disposing) { if (fs != null ) fs.Close(); } fs = null ; disposed = true ; } } } /// /// 属性描述对应关系 /// public class DisplayMappProperty { /// /// 属性 /// public PropertyInfo Property { set ; get ; } /// /// 属性描述 描述对应excel中的列名 /// public string DisplayName { set ; get ; } } 调用方法实例,首先是导入,其中ImportModel是excel对应的实体类型: public ActionResult Import(HttpPostedFileBase importFile) { ExcelHelper important = new ExcelHelper(); var agentInfos = important.ExcelToModel(importFile, null , 1); } 导出实例,其中exportModels是需要导出的数据集合: new ExcelHelper.Export(exportModels, Response, "活动分润" , null , null ); |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构