123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204 |
- using System;
- using System.Collections.Generic;
- using System.Data;
- using System.IO;
- using System.Linq;
- using NPOI.HSSF.UserModel;
- using NPOI.SS.UserModel;
- using NPOI.XSSF.UserModel;
- namespace Team.Utility
- {
- /// <summary>
- /// poi类库实现的excel工具类
- /// excel文件到table,table到excel
- /// </summary>
- public static class ExcelUtil
- {
- /// <summary>
- /// Excel导入成Datable
- /// </summary>
- /// <param name="file">导入路径(包含文件名与扩展名)</param>
- /// <param name="isFirstRowAsHeader"></param>
- /// <returns>
- /// </returns>
- /// Exception("无效的文件扩展名"),要求xls,xlsx格式
- public static DataTable ExcelToTable(string file,bool isFirstRowAsHeader=true)
- {
- var dt = new DataTable();
- var fileExt = Path.GetExtension(file)?.ToLower();
- using var fs = new FileStream(file, FileMode.Open, FileAccess.Read,FileShare.ReadWrite);
- //XSSFWorkbook 适用XLSX格式,HSSFWorkbook 适用XLS格式
- IWorkbook workbook = fileExt switch
- {
- ".xlsx" => new XSSFWorkbook(fs),
- ".xls" => new HSSFWorkbook(fs),
- _ => throw new Exception("无效的文件扩展名")
- };
- var sheet = workbook.GetSheetAt(0);
- var columns = new List<int>();
- //表头
- var header = sheet.GetRow(sheet.FirstRowNum);
- for (var i = 0; i < header.LastCellNum; i++)
- {
- var obj = GetValueType(header.GetCell(i));
- if (obj == null || obj.ToString() == string.Empty||!isFirstRowAsHeader)
- dt.Columns.Add(new DataColumn("Columns" + i));
- else
- dt.Columns.Add(new DataColumn(obj.ToString()));
- columns.Add(i);
- }
- var firstRow = isFirstRowAsHeader ? sheet.FirstRowNum + 1 : sheet.FirstRowNum;
- //数据
- for (var i = firstRow; i <= sheet.LastRowNum; i++)
- {
- var dr = dt.NewRow();
- var hasValue = false;
- foreach (var j in columns)
- {
- dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
- if (dr[j] != null && dr[j].ToString() != string.Empty)
- {
- hasValue = true;
- }
- }
- if (hasValue)
- {
- dt.Rows.Add(dr);
- }
- }
- return dt;
- }
- /// <summary>
- /// Datable导出成Excel
- /// </summary>
- /// <param name="dt"></param>
- /// <param name="file">导出路径(包括文件名与扩展名)</param>
- /// <param name="isAddHeader">默认添加表头</param>
- /// Exception("无效的文件扩展名"),要求xls,xlsx格式
- public static void TableToExcel(DataTable dt, string file,bool isAddHeader=true)
- {
- var fileExt = Path.GetExtension(file)?.ToLower();
- IWorkbook workbook = fileExt switch
- {
- ".xlsx" => new XSSFWorkbook(),
- ".xls" => new HSSFWorkbook(),
- _ => throw new Exception("无效的文件扩展名")
- };
- var sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);//sheet名
- if (isAddHeader)
- {
- var row = sheet.CreateRow(0);
- for (var i = 0; i < dt.Columns.Count; i++)
- {
- var cell = row.CreateCell(i);
- cell.SetCellValue(dt.Columns[i].ColumnName);
- }
- //数据
- }
- for (var i = 0; i < dt.Rows.Count; i++)
- {
- var row1 = sheet.CreateRow(i + 1);
- for (var j = 0; j < dt.Columns.Count; j++)
- {
- var cell = row1.CreateCell(j);
- cell.SetCellValue(dt.Rows[i][j].ToString());
- }
- }
- //表头
- //转为字节数组
- using var stream = new MemoryStream();
- workbook.Write(stream);
- var buf = stream.ToArray();
- //保存为Excel文件
- using var fs = new FileStream(file, FileMode.Create, FileAccess.Write);
- fs.Write(buf, 0, buf.Length);
- fs.Flush();
- }
- public static IRow ExtensionMethod(ISheet sheet,int rowIndex)
- {
- var row= sheet.CreateRow(rowIndex);
- return row;
- }
- public static void TableToExcel(DataTable []dts, string file)
- {
- IWorkbook workbook;
- var fileExt = Path.GetExtension(file)?.ToLower();
- if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; }
- if (workbook == null) { return; }
- foreach (var dt in dts)
- {
- var sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet($"Sheet{dts.ToList().IndexOf(dt)}") : workbook.CreateSheet(dt.TableName);
- //表头
- var row = sheet.CreateRow(0);
- for (var i = 0; i < dt.Columns.Count; i++)
- {
- var cell = row.CreateCell(i);
- cell.SetCellValue(dt.Columns[i].ColumnName);
- }
- //数据
- for (var i = 0; i < dt.Rows.Count; i++)
- {
- var row1 = sheet.CreateRow(i + 1);
- for (var j = 0; j < dt.Columns.Count; j++)
- {
- var cell = row1.CreateCell(j);
- cell.SetCellValue(dt.Rows[i][j].ToString());
- }
- }
- }
-
- //转为字节数组
- var stream = new MemoryStream();
- workbook.Write(stream);
- var buf = stream.ToArray();
- //保存为Excel文件
- using (var fs = new FileStream(file, FileMode.Create, FileAccess.Write))
- {
- fs.Write(buf, 0, buf.Length);
- fs.Flush();
- }
- }
- /// <summary>
- /// 获取单元格类型
- /// </summary>
- /// <param name="cell"></param>
- /// <returns></returns>
- private static object GetValueType(ICell cell)
- {
- if (cell == null)
- return null;
- switch (cell.CellType)
- {
- case CellType.Blank: //BLANK:
- return null;
- case CellType.Boolean: //BOOLEAN:
- return cell.BooleanCellValue;
- case CellType.Numeric: //NUMERIC:
- return cell.NumericCellValue;
- case CellType.String: //STRING:
- return cell.StringCellValue;
- case CellType.Error: //ERROR:
- return cell.ErrorCellValue;
- default:
- return "=" + cell.CellFormula;
- }
- }
- }
- }
|