tnblog
首页
视频
资源
登录

excel(泛型和datatable)帮助类,含添加和读取表头批注

3372人阅读 2020/9/4 11:50 总访问:15711 评论:1 收藏:1 手机
分类: .net
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using NPOI.HSSF.UserModel;
  7. using NPOI.HSSF.Util;
  8. using NPOI.XSSF.Util;
  9. using NPOI.XSSF.UserModel;
  10. using NPOI.SS.UserModel;
  11. using log4net;
  12. using System.IO;
  13. using System.Reflection;
  14. using System.Data;
  15. namespace Tools
  16. {
  17.     public class ExcelHelper
  18.     {
  19.         internal static readonly log4net.ILog log = LogManager.GetLogger("log4netlogger");
  20.         #region 导入数据
  21.         /// 从Excel中加载数据(泛型)-  npoi   缺点:不能有datetime?类型
  22.         /// </summary>
  23.         /// <typeparam name="T"></typeparam>
  24.         /// <param name="fileName">文件名称(用于判断后缀)</param>
  25.         /// <param name="importType">importType 1物理路径上传 2文件流上传 </param>
  26.         /// <param name="filePath">excel文件路径</param>
  27.         /// <param name="stream">文件流</param>
  28.         /// <param name="beginRowIndex">起始行(从0开始),例如第一行为列头,从第二行开始为数据,则 beginRowIndex = 1</param>
  29.         /// <param name="IsReadComments">是否读取批注 默认为false ;true 读取表头批注 false 读取表头</param>
  30.         /// <returns>泛型列表</returns>
  31.         public static IEnumerable<T> ImportExcel<T>(string fileName, int importType = 1string filePath = "", Stream stream = nullint beginRowIndex = 1,bool IsReadComments=falsewhere T : new()
  32.         {
  33.             List<T> resultList = new List<T>();
  34.             List<string> colName = new List<string>();
  35.             Dictionary<intstring> dicColName = new Dictionary<intstring>();
  36.             try
  37.             {
  38.                 var fileExt = Path.GetExtension(fileName).ToLower();//获取文件后缀
  39.                 IWorkbook workbook;
  40.                 if (importType == 1)
  41.                 {
  42.                     stream = new FileStream(filePath, FileMode.Open);
  43.                 }
  44.                 if (fileExt == ".xls")
  45.                     workbook = new HSSFWorkbook(stream);
  46.                 else if (fileExt == ".xlsx")
  47.                     workbook = new XSSFWorkbook(stream);
  48.                 else
  49.                     return resultList;
  50.                 ISheet sheet = workbook.GetSheetAt(0);//获取sheet
  51.                 int rowStart = sheet.FirstRowNum;//开始行
  52.                 int rowEnd = sheet.LastRowNum;//结束行
  53.                 if (rowEnd >= 0)
  54.                 {
  55.                     int colStart = sheet.GetRow(rowStart).FirstCellNum;//开始列
  56.                     int colEnd = sheet.GetRow(rowStart).LastCellNum;//结束列
  57.                     var firstRow = sheet.GetRow(rowStart);
  58.         
  59.                     //判断读取批注还是表头
  60.                     if (IsReadComments == true)
  61.                     {    
  62.                         //处理表头 
  63.                         for (int i = colStart; i < colEnd; i++)
  64.                         {
  65.                             var value = firstRow.GetCell(i);
  66.                             dicColName[i] = value == null ? "" : value.CellComment.String.String.ToLower();//获取批注
  67.                         }
  68.                     }
  69.                     else
  70.                     {
  71.                         for (int i = colStart; i < colEnd; i++)
  72.                         {
  73.                             var value = firstRow.GetCell(i);
  74.                             dicColName[i] = value == null ? "" : value.ToString();
  75.                         }
  76.                     }
  77.                     List<PropertyInfo> propertyInfoList = new List<PropertyInfo>(typeof(T).GetProperties());
  78.                     propertyInfoList = propertyInfoList.Where(p => dicColName.Values.Contains(p.Name)).ToList();
  79.                     for (int i = rowStart + beginRowIndex; i <= rowEnd; i++)
  80.                     {
  81.                         var row = sheet.GetRow(i);//获取行
  82.                         if (row == null)
  83.                             continue;
  84.                         T t = new T();
  85.                         for (int j = colStart; j <= colEnd; j++)
  86.                         {
  87.                             var cell = row.GetCell(j);//获取列
  88.                             if (cell == null)
  89.                                 continue;
  90.                             var propertyInfo = propertyInfoList.Where(a => a.Name == dicColName[j]).FirstOrDefault();
  91.                             if (propertyInfo != null)
  92.                             {
  93.                                 var cellType = cell.CellType; //propertyInfo.PropertyType.Name.ToLower();
  94.                                 object cellValue = cell.ToString();
  95.                                 cellValue = DatatableAndListHelper.JudgeType(propertyInfo, cellValue);
  96.                                 propertyInfo.SetValue(t, cellValue);//赋值
  97.                             }
  98.                         }
  99.                         resultList.Add(t);
  100.                     }
  101.                 }
  102.                 stream.Close();
  103.                 return resultList;
  104.             }
  105.             catch (Exception ex)
  106.             {
  107.                 log.Error(ex.Message);
  108.                 throw;
  109.             }
  110.         }
  111.         /// <summary>
  112.         /// 从Excel中加载数据(datatable)-  npoi
  113.         /// </summary>
  114.         /// <param name="fileName">文件名称(用于判断后缀)</param>
  115.         /// <param name="importType">importType 1物理路径上传 2文件流上传 </param>
  116.         /// <param name="filePath">excel文件路径</param>
  117.         /// <param name="stream">文件流</param>
  118.         /// <param name="beginRowIndex">起始行(从0开始),例如第一行为列头,从第二行开始为数据,则 beginRowIndex = 1</param>
  119.         /// <param name="IsReadComments">是否读取批注 默认为false ;true 读取表头批注 false 读取表头</param>
  120.         /// <returns></returns>
  121.         public static DataTable ImportExcel(string fileName, int importType = 1string filePath = "", Stream stream = nullint beginRowIndex = 1bool IsReadComments = false)
  122.         {
  123.             DataTable table = new DataTable();
  124.             List<string> colName = new List<string>();
  125.             Dictionary<intstring> dicColName = new Dictionary<intstring>();
  126.             try
  127.             {
  128.                 var fileExt = Path.GetExtension(fileName).ToLower();//获取文件后缀
  129.                 IWorkbook workbook;
  130.                 if (importType == 1)
  131.                 {
  132.                     stream = new FileStream(filePath, FileMode.Open);
  133.                 }
  134.                 if (fileExt == ".xls")
  135.                     workbook = new HSSFWorkbook(stream);
  136.                 else if (fileExt == ".xlsx")
  137.                     workbook = new XSSFWorkbook(stream);
  138.                 else
  139.                     return table;
  140.                 ISheet sheet = workbook.GetSheetAt(0);//获取sheet
  141.                 int rowStart = sheet.FirstRowNum;//开始行
  142.                 int rowEnd = sheet.LastRowNum;//结束行
  143.                 if (rowEnd >= 0)
  144.                 {
  145.                     int colStart = sheet.GetRow(rowStart).FirstCellNum;//开始列
  146.                     int colEnd = sheet.GetRow(rowStart).LastCellNum;//结束列
  147.                     var firstRow = sheet.GetRow(rowStart);
  148.                     //判断读取批注还是表头
  149.                     if (IsReadComments == true)
  150.                     {
  151.                         //处理表头 
  152.                         for (int i = colStart; i < colEnd; i++)
  153.                         {
  154.                             var value = firstRow.GetCell(i);
  155.                             dicColName[i] = value == null ? "" : value.CellComment.String.String.ToLower();//获取批注
  156.                         }
  157.                     }
  158.                     else
  159.                     {
  160.                         for (int i = colStart; i < colEnd; i++)
  161.                         {
  162.                             var value = firstRow.GetCell(i);
  163.                             dicColName[i] = value == null ? "" : value.ToString();
  164.                         }
  165.                     }
  166.                     //处理数据源
  167.                     for (int i = rowStart + beginRowIndex; i <= rowEnd; i++)
  168.                     {
  169.                         var row = sheet.GetRow(i);//获取行
  170.                         if (row == null)
  171.                             continue;
  172.                         DataRow dataRow = table.NewRow();
  173.                         for (int j = colStart; j <= colEnd; j++)
  174.                         {
  175.                             var cell = row.GetCell(j);//获取列
  176.                             if (cell == null)
  177.                                 continue;
  178.                             dataRow[j] = cell.ToString();
  179.                         }
  180.                         table.Rows.Add(dataRow);
  181.                     }
  182.                 }
  183.                 stream.Close();
  184.                 return table;
  185.             }
  186.             catch (Exception ex)
  187.             {
  188.                 log.Error(ex.Message);
  189.                 throw;
  190.             }
  191.         }
  192.         #endregion
  193.         #region 导出数据
  194.         public static MemoryStream ExportExcel<T>(IList<T> list, string fileName = "导出excel")
  195.         {
  196.             try
  197.             {
  198.                 Dictionary<intstring> dicColName = new Dictionary<intstring>();
  199.                 HSSFWorkbook workbook = new HSSFWorkbook();
  200.                 var sheet = workbook.CreateSheet(fileName);
  201.                 var propertyInfos = new List<PropertyInfo>(typeof(T).GetProperties());
  202.                 var colcount = propertyInfos.Count;
  203.                 //创建表头
  204.                 var headCell = sheet.CreateRow(0);
  205.                 for (int i = 0; i < colcount; i++)
  206.                 {
  207.                     dicColName[i] = propertyInfos[i].Name;
  208.                     headCell.CreateCell(i).SetCellValue(propertyInfos[i].Name);
  209.                 }
  210.                 //创建数据列 
  211.                 if (list != null)
  212.                     for (int i = 1; i <= list.Count; i++)
  213.                     {
  214.                         var cell = sheet.CreateRow(i);
  215.                         var info = list[i];
  216.                         for (int j = 0; j < colcount; j++)
  217.                         {
  218.                             var p = propertyInfos.Where(a => a.Name == dicColName[j]).FirstOrDefault();//获取信息
  219.                             if (p == null)
  220.                                 continue;
  221.                             var value = p.GetValue(list[i]) == null ? "" : p.GetValue(list[i]).ToString();//获取值
  222.                             cell.CreateCell(j).SetCellValue(value);
  223.                         }
  224.                     }
  225.                 //内存流
  226.                 MemoryStream ms = new MemoryStream();
  227.                 workbook.Write(ms);
  228.                 return ms;
  229.             }
  230.             catch (Exception ex)
  231.             {
  232.                 log.Error(string.Format("data:{0},错误:{1}", list, ex.Message));
  233.                 throw;
  234.             }
  235.         }
  236.         /// <summary>
  237.         /// datatable导出excel
  238.         /// </summary>
  239.         /// <param name="table">数据源</param>
  240.         /// <param name="fileName">sheet名称</param>
  241.         /// <param name="beginRowIndex"></param>
  242.         /// <returns></returns>
  243.         public static MemoryStream ExportExcel(DataTable table, string fileName = "导出excel")
  244.         {
  245.             try
  246.             {
  247.                 Dictionary<intstring> dicColName = new Dictionary<intstring>();
  248.                 HSSFWorkbook workbook = new HSSFWorkbook();
  249.                 var sheet = workbook.CreateSheet(fileName);
  250.                 var rowcount = table.Rows.Count;
  251.                 var colcount = table.Columns.Count;
  252.                 //创建表头
  253.                 var headCell = sheet.CreateRow(0);
  254.                 for (int i = 0; i < colcount; i++)
  255.                 {
  256.                     headCell.CreateCell(i).SetCellValue(table.Columns[i].ColumnName);
  257.                 }
  258.                 //创建数据列   
  259.                 for (int i = 1; i <= rowcount; i++)
  260.                 {
  261.                     var cell = sheet.CreateRow(i);
  262.                     var info = table.Rows[i];
  263.                     for (int j = 0; j < colcount; j++)
  264.                     {
  265.                         var value = info[j] == null ? "" : info[j].ToString();
  266.                         cell.CreateCell(j).SetCellValue(value);
  267.                     }
  268.                 }
  269.                 MemoryStream ms = new MemoryStream();
  270.                 workbook.Write(ms);
  271.                 return ms;
  272.             }
  273.             catch (Exception ex)
  274.             {
  275.                 log.Error(string.Format("data:{0},错误:{1}", table, ex.Message));
  276.                 throw;
  277.             }
  278.         }
  279.         /// <summary>
  280.         /// 导出自定义表头excel
  281.         /// </summary>
  282.         /// <typeparam name="T"></typeparam>
  283.         /// <param name="list"></param>
  284.         /// <param name="headers">key:字段名 value:表头名称</param>
  285.         /// <param name="fileName"></param>
  286.         /// <param name="IsRequiredComment">是否需要添加批注 默认为false 批注为headers的key</param>
  287.         /// <returns></returns>
  288.         public static MemoryStream ExportExcel<T>(IList<T> list, Dictionary<stringstring> headers, string fileName = "导出excel"bool IsRequiredComment = false)
  289.         {
  290.             try
  291.             {
  292.                 Dictionary<intstring> dicColName = new Dictionary<intstring>();
  293.                 HSSFWorkbook workbook = new HSSFWorkbook();
  294.                 var sheet = workbook.CreateSheet(fileName);
  295.                 var propertyInfos = new List<PropertyInfo>(typeof(T).GetProperties());
  296.                 var colcount = headers.Count();
  297.                 var patr = sheet.CreateDrawingPatriarch();
  298.                 //创建表头
  299.                 var headCell = sheet.CreateRow(0);
  300.                 for (int i = 0; i < colcount; i++)
  301.                 {
  302.                     var cell = headCell.CreateCell(i);
  303.                     cell.SetCellValue(headers.ElementAt(i).Value);
  304.                     if (IsRequiredComment == true)
  305.                     {
  306.                         HSSFComment comment1 = (HSSFComment)patr.CreateCellComment(new HSSFClientAnchor(00001134));
  307.                         comment1.String = new HSSFRichTextString(headers.ElementAt(i).Key);
  308.                         cell.CellComment = comment1;
  309.                     }
  310.                 }
  311.                 //创建数据列 
  312.                 if (list != null)
  313.                     for (int i = 1; i <= list.Count; i++)
  314.                     {
  315.                         var row = sheet.CreateRow(i);
  316.                         var info = list[i];
  317.                         for (int j = 0; j < colcount; j++)
  318.                         {
  319.                             //list.GetType().GetProperty(headers.ElementAt(i).Key);//获取信息写法2
  320.                             var p = propertyInfos.Where(a => a.Name == headers.ElementAt(j).Key).FirstOrDefault();//获取信息
  321.                             if (p == null)
  322.                                 continue;
  323.                             dynamic cellvaule = p.GetValue(list[i]);//获取值
  324.                             var value = cellvaule ? "" : cellvaule.ToString();
  325.                             var type = GetCellType(p.PropertyType.FullName);//获取类型
  326.                             if (p.PropertyType.FullName == typeof(decimal).FullName)
  327.                             {
  328.                                 double deci;
  329.                                 double.TryParse(valueout deci);
  330.                                 value = deci;
  331.                             }
  332.                             var cell = row.CreateCell(j);
  333.                             cell.SetCellType(type);
  334.                             cell.SetCellValue(value);
  335.                         }
  336.                     }
  337.                 //内存流
  338.                 MemoryStream ms = new MemoryStream();
  339.                 workbook.Write(ms);
  340.                 return ms;
  341.             }
  342.             catch (Exception ex)
  343.             {
  344.                 log.Error(string.Format("data:{0},错误:{1}", list, ex.Message));
  345.                 throw;
  346.             }
  347.         }
  348.         /// <summary>
  349.         ///  datatable导出excel
  350.         /// </summary>
  351.         /// <param name="table"></param>
  352.         /// <param name="headers">key:字段名 value:表头名称</param>
  353.         /// <param name="fileName"></param>
  354.         /// <param name="IsRequiredComment">是否需要添加批注 默认为false 批注为headers的key</param>
  355.         /// <returns></returns>
  356.         public static MemoryStream ExportExcel(DataTable table, Dictionary<stringstring> headers, string fileName = "导出excel"bool IsRequiredComment = false)
  357.         {
  358.             try
  359.             {
  360.                 Dictionary<intstring> dicColName = new Dictionary<intstring>();
  361.                 HSSFWorkbook workbook = new HSSFWorkbook();
  362.                 var sheet = workbook.CreateSheet(fileName);
  363.                 var Columns = table.Columns;
  364.                 var rowcount = table.Rows.Count;
  365.                 var colcount = headers.Count;
  366.                 var patr = sheet.CreateDrawingPatriarch();
  367.                 //创建表头
  368.                 var headCell = sheet.CreateRow(0);
  369.                 for (int i = 0; i < colcount; i++)
  370.                 {
  371.                     var cell = headCell.CreateCell(i);
  372.                     cell.SetCellValue(headers.ElementAt(i).Value);
  373.                     if (IsRequiredComment == true)
  374.                     {
  375.                         HSSFComment comment1 = (HSSFComment)patr.CreateCellComment(new HSSFClientAnchor(00001134));
  376.                         comment1.String = new HSSFRichTextString(headers.ElementAt(i).Key);
  377.                         cell.CellComment = comment1;
  378.                     }
  379.                 }
  380.                 //创建数据列   
  381.                 for (int i = 1; i <= rowcount; i++)
  382.                 {
  383.                     var row = sheet.CreateRow(i);
  384.                     var info = table.Rows[i];
  385.                     for (int j = 0; j < colcount; j++)
  386.                     {
  387.                         if (!Columns.Contains(headers.ElementAt(j).Key))//判断该列名是否存在
  388.                             continue;
  389.                         var cellvaule = info[headers.ElementAt(j).Key];
  390.                         var value = cellvaule == null ? "" : cellvaule.ToString();
  391.                         row.CreateCell(j).SetCellValue(value);
  392.                     }
  393.                 }
  394.                 MemoryStream ms = new MemoryStream();
  395.                 workbook.Write(ms);
  396.                 return ms;
  397.             }
  398.             catch (Exception ex)
  399.             {
  400.                 log.Error(string.Format("data:{0},错误:{1}", table, ex.Message));
  401.                 throw;
  402.             }
  403.         }
  404.         #endregion
  405.         internal void GetValueByType(CellType cellType, object cellValue, ICell cell)
  406.         {
  407.             //判断excel表的类型
  408.             switch (cellType)
  409.             {
  410.                 case CellType.String:
  411.                     cellValue = cell.StringCellValue;
  412.                     break;
  413.                 case CellType.Numeric:
  414.                     cellValue = cell.NumericCellValue;
  415.                     break;
  416.                 case CellType.Boolean:
  417.                     cellValue = cell.BooleanCellValue;
  418.                     break;
  419.                 case CellType.Blank://空值
  420.                     cellValue = "";
  421.                     break;
  422.                 case CellType.Formula:
  423.                     cellValue = cell.CellFormula;
  424.                     break;
  425.                 default:
  426.                     break;
  427.             }
  428.         }
  429.         private static CellType GetCellType(dynamic type)
  430.         {
  431.             if (type == typeof(int).FullName || type == typeof(float).FullName || type == typeof(decimal).FullName || type == typeof(double).FullName)
  432.             {
  433.                 return CellType.Numeric;
  434.             }
  435.             if (type == typeof(bool).FullName)
  436.             {
  437.                 return CellType.Boolean;
  438.             }
  439.             return CellType.String;
  440.         }
  441.     }
  442. }


评价

瑾语

2021/3/23 15:27:16

使用OLEDB读取不同版本excel的连接字符串设置

使用OleBD读取excel的时候,excel不同的版本,连接字符串的写法也会不一样。///&lt;summary&gt; ///读取excel ///&lt;/su...

NPOI操作excel 2007/2010版本

HSSFWorkbook:是操作Excel2003以前(包括2003)的版本,扩展名是.xlsXSSFWorkbook:是操作Excel2007的版本,扩展名是.xlsx先...

DevExpress.XtraSpreadsheet.SpreadsheetControl控件 加载excel模板

stringpath=&quot;文件路径&quot;; DevExpress.XtraSpreadsheet.SpreadsheetControlspreadsheetControl=newDevExpress.Xtr...

NPOI读取excelexcel 导入。日期类型读取

NPOI是一个优秀的操作excel的库,可以很方便的进行excel的读取与导出NPOI读取excelpublicActionResultReadExcel() { //打...

NPOI导出excel。根据模板导出excel

使用NPOI导出excel///&lt;summary&gt; ///导出excel(下载excel) ///&lt;/summary&gt; publicvoidToExcel() { HSSFWo...

.net core使用requestresponse下载文件下载excel

使用request获取内容net core中request没有直接的索引方法,需要点里边的Query,或者formstringbase64=Request.Form[&quot;f...

使用NPOI导出excel(包括图片)

Excl模板导出相信我们都会,那么模板上要导出图片呢?嗯~还是来个例子:准备工作:首先要引用NPOI包:然后获取数据集(我这...

excel的一点使用记录

做了这么多年开发,其实对excel的使用其实并不是太了解,记录一下遇到的,用以备忘excel的简单公式比如我们要做这样一个公...

excel文件的读取

童鞋们,好久不见,今天我们来简单的学习一下Excel文件的读取。首先,我们可以手动创建一个Excel文件例如:然后另存为,格...

使用微软本身自带读取excel数据

使用步奏: 1.导入插件using System.Data.OleDb; 2.获取文件路径 3.连接字符串 4.实例化Excel读取连接对象 5.打开连接对象 ...

使用NPOI插件读取excel数据

方法步奏: 1.导入NPOI插件和文件IO 2.获取文件路径 3.打开文件 4.通过文件夹打开表格 ...

excel的创建以及填充数据

在公司实际开发中,我们用到Excel文件的地方很多,下面我来讲解一下如何创建比如我们做一个如下图的报表:前台页面设计:@{...

C下载excel文件并且填充数据

引用NPOI.dll文件库usingNPOI.HSSF.Model; usingNPOI.HSSF.UserModel; usingNPOI.HSSF.Util;在当期项目添加一个Excel模板...

.NET MVC 中 excel的读取操作

经常看到新闻说熬夜可能会猝死,真是吓死我了,以后再也不看新闻了。个如你一般的人今天我们分享的文章是关于mvc框架中对Ex...

.NET mvc excel的导入导出解析

“为什么越靠北方地区的人性格越直接?”“天寒地冻的,谁有时间跟你磨叽?”今天我们讲解的内容是关于在mvc框架里对Excel...

NPOI对excel的读取

publicActionResultIndex() { //打开excel所在的位置 FileStreamstream=newFileStream(Server.MapPath(&quot;~/Content/...
没有个性,不需要签名
排名
72
文章
8
粉丝
3
评论
3
导出SQL脚本小程序
剑轩 : 厉害了!
导出SQL脚本小程序
剑轩 : 厉害了!
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术