首页 > 其他分享 >EPPuls Excel 导入导出

EPPuls Excel 导入导出

时间:2023-03-23 10:22:38浏览次数:27  
标签:Style sheet Color Excel cell 导入 var new EPPuls

 /// <summary>
    /// Excel导出
    /// </summary>
    public static class ExcelHelper
    {
        /// <summary>
        /// 设置表格样式
        /// </summary>
        /// <param name="cell"></param>
        /// <param name="bgColor">背景色</param>
        /// <param name="fontColor">字体颜色</param>
        /// <param name="bold">/粗体</param>
        /// <returns></returns>
        private static ExcelRange SetStyle(this ExcelRange cell, Color? bgColor = null, Color? fontColor = null, bool bold = false)
        {
            cell.Style.Fill.PatternType = ExcelFillStyle.Solid;                 //边框样式
            cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;   //水平居中对齐
            cell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;       //垂直居中对齐
            cell.Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Black); //边框颜色
            cell.Style.Font.Bold = bold;                                        //字体加粗
            cell.Style.Numberformat.Format = "@";                               //单元格格式
            cell.Style.Font.Color.SetColor(fontColor ?? Color.Black);           //文本颜色
            cell.Style.Fill.BackgroundColor.SetColor(bgColor ?? Color.White);   //背景颜色
            return cell;
        }


        private static string GetDescription(this PropertyInfo propertyInfo) => propertyInfo.GetCustomAttribute<DescriptionAttribute>()?.Description.Trim() ?? "";


        private static void ForEach<T>(this List<T> ts, Action<T, int> func)
        {

            for (int i = 0; i < ts.Count; i++) func(ts[i], i);
        
        }


        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ts"></param>
        /// <param name="colunms">自定义列头</param>
        /// <param name="ignoreField">忽略的字段</param>
        /// <returns></returns>
        public static FileContentResult ToExcelFixed<T>(this List<T> data, params string[] ignoreFields)
        {

            ExcelPackage.LicenseContext = LicenseContext.NonCommercial; //使用免费的

            using (var ep = new ExcelPackage())
            {
                var columns = typeof(T).GetProperties().Where(x => x.GetDescription() != "" && !ignoreFields.Contains(x.Name)).ToList();

                var sheet = ep.Workbook.Worksheets.Add("Sheet1");

                data.ForEach((t, i) =>
                {

                    columns.ForEach((y, j) =>
                    {

                        if (j == 0) sheet.Cells[1, j + 1].SetStyle(Color.LightSteelBlue, Color.Black, true).Value = y.GetDescription(); //添加表头

                        sheet.Cells[i + 2, j + 1].SetStyle().Value = y.GetValue(t); //添加数据

                    });

                });

                sheet.Rows.Height = 24;

                sheet.Cells.AutoFitColumns();

                return new FileContentResult(ep.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            }
        }

        

        /// <summary>
        /// Excel导入
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="file"></param>
        /// <param name="ignoreField"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static List<T> ToImportFixed<T>(this IFormFile file) where T:new() {

            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            var result = new List<T>();

            var props = typeof(T).GetProperties().ToList();

            var colunms = new Dictionary<int, PropertyInfo>();

            using (var ep = new ExcelPackage(file.OpenReadStream()))
            {

                var sheet = ep.Workbook.Worksheets[0];

                for (int r = 1; r <= sheet.Dimension.End.Row; r++)
                {
                    T t = new T();

                    for (int c = 1; c <= sheet.Dimension.End.Column; c++)
                    {
                        if (r == 1)
                        {

                            var prop = props.Find(x => x.GetDescription() == sheet.Cells[1, c].Value + "");

                            if (prop == null) throw new Exception("文件格式不正确!");

                            colunms.Add(c, prop);

                            continue;

                        }
                        //去除空格
                        colunms[c].SetValue(t, (sheet.Cells[r, c].Value + "").Trim());

                    }

                    if (r > 1) result.Add(t);
                    
                }

            }

            return result;
        }
    }

 

标签:Style,sheet,Color,Excel,cell,导入,var,new,EPPuls
From: https://www.cnblogs.com/87duan/p/17246500.html

相关文章

  • sql server使用bcp导出txt文件然后导入到mysql
     1.导出表bcp"select*fromtryine_kjzx.dbo.tb_test01"queryoutc:\my.txt-S192.168.1.39-U"test"-P"test"-c-t"€"-r"\n" 2.ue打开文件转换dos转unix转......
  • 【informix】数据导入导出操作
    目录informix数据导入导出操作1.表数据导出2.导入表数据3.表结构导出4.informix新建/删除表结构5.informix存储过程执行方法informix数据导入导出操作1.表数据导出可以......
  • Excel数据分析学习笔记
                        ......
  • Qt QXlsx(访问Excel)
    再Qt中已经有了QAxObject来访问Excel,但访问的是微软的com,只能访问正版的Excl中的.xls//xlsx,而且使用起来及其不方便(本人亲测)。在这里使用QXlsx,能更简单的访问Excel数......
  • Cadence入门笔记(五):网表生成和导入
    检查封装在生成网表前要先确认器件封装和实际封装文件是否对应存在如下是之前设计好的封装文件.psm文件打开orcad,和元件属性中的封装内容对比确认一致如果实际封装和......
  • Java 使用 POI 导出Excel,设置同一个单元格的内容显示不同的文字颜色
    要在Java中导出Excel并设置同一单元格的内容显示不同的文字颜色,可以使用ApachePOI库来实现。下面是一个示例代码,演示如何在单元格中设置不同颜色的文本:1//创建......
  • shp导入postgre
    以前的工作,最近有点忘了记录一下   下载postgre 安装postgis    具体怎么安装的,我忘了 百度吧 然后导入就行了......
  • IDEA 如何快速重新导入 Maven 依赖
    当Module依赖的其它Module(需在IDEA内被加载)发生变更后,可以通过MavenHelper插件的Reimport功能快速重新导入步骤如下:使用Alt+Ctrl+Shift+R打开......
  • Matlab 将矩阵循环写入同一个Excel中不同命名的Sheet中
    前言由于需要计算不同行政区划不同年份的某个指标变化情况,实际上是三种变量三维数组,除去在matlab内部保存变量外,写入Excel方便查看制表教程代码参考:https://ww2.mathw......
  • excel函数——做一份简单统计
    基础知识:1.复制一份原始数据并隐藏2.几个重要的函数(sum,sumif,sumifs,subtotal,if,vlookup,match,index)3.数据验证 4.透视图点中数据-插入透视图5.迷你图   应......