首页 > 编程语言 >C# 数据导出成Excel的流

C# 数据导出成Excel的流

时间:2024-06-18 22:59:35浏览次数:19  
标签:C# Excel 导出 rowIndex book Thin var BorderStyle row

导出的帮助类

public class ExcelHelper
{
        /// <summary>
        /// 将给定的模型列表转换为 Excel 内存流,第一行和第二行是居中对齐加粗的
        /// </summary>
        /// <typeparam name="T">模型类型</typeparam>
        /// <param name="models">模型列表</param>
        /// <param name="firstRow">Excel 第一行数据</param>
        /// <param name="secondRow">Excel 第二行数据</param>
        /// <returns>Excel 内存流</returns>
        public static MemoryStream ExportExcelStream<T>(List<T> models, string firstRow, string secondRow)
        {
            NPOIMemoryStream ms = new NPOIMemoryStream();//使用自定义类

            IWorkbook workbook = Parse(models, firstRow, secondRow);

            workbook.Write(ms);
            ms.Position = 0;

            return ms;
        }


        /// <summary>
        /// 将数据导出到Excel内存流中
        /// </summary>
        /// <typeparam name="T">类型参数</typeparam>
        /// <param name="models">要导出的数据列表</param>
        /// <param name="firstRow">第一行的信息</param>
        /// <param name="secondRow">第二行的信息</param>
        /// <param name="hashtable">Hashtable类型的参数</param>
        /// <returns>Excel内存流</returns>
        public static MemoryStream ExportExcelStream<T>(List<T> models, string firstRow, string secondRow,Hashtable hashtable)
        {
            NPOIMemoryStream ms = new NPOIMemoryStream();//使用自定义类

            IWorkbook workbook = Parse(models, hashtable, firstRow, secondRow);

            workbook.Write(ms);
            ms.Position = 0;

            return ms;
        }
    
    
        /// <summary>
        ///     内存流保存到Excel文件中
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string ConvertStreamToExcel(MemoryStream stream, string filePath)
        {
            using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                fileStream.Write(buffer, 0, buffer.Length);
            }
            return filePath;
        }
    
        /// <summary>
        ///     将数据传输对象列表解析为HSSFWorkbook对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="models"></param>
        /// <param name="firstRow"></param>
        /// <param name="secondRow"></param>
        /// <returns></returns>
        private static HSSFWorkbook Parse<T>(List<T> models, string firstRow = "", string secondRow = "")
        {
            var book = new HSSFWorkbook();
            var sheet = book.CreateSheet();
            var headerStyle = GetHeaderStyle(book);
            headerStyle.Alignment = HorizontalAlignment.Center;
            headerStyle.BorderBottom = BorderStyle.Thin;
            headerStyle.BorderLeft = BorderStyle.Thin;
            headerStyle.BorderRight = BorderStyle.Thin;
            headerStyle.BorderTop = BorderStyle.Thin;
            var itemStyle = GetItemStyle(book);
            itemStyle.Alignment = HorizontalAlignment.Center;
            itemStyle.BorderBottom = BorderStyle.Thin;
            itemStyle.BorderLeft = BorderStyle.Thin;
            itemStyle.BorderRight = BorderStyle.Thin;
            itemStyle.BorderTop = BorderStyle.Thin;


            var properties = typeof(T).GetProperties();
            var columns = properties.Select(x => new ColumnEntry
            {
                Property = x,
                Header = x.GetCustomAttribute<ExportHeaderAttribute>()
            })
            .Where(x => x.Header != null)
            .OrderBy(x => x.Header.Order)
            .ToList();

            //  列数
            var columnCount = columns.Count();
            //  行数
            var rowCount = models.Count();

            SetColumnWith(sheet, columnCount);

            WriteMergeRow(0, firstRow, 0, columnCount - 1);
            WriteMergeRow(1, secondRow, 0, columnCount - 1);

            WriteRow(2, columns.Select(x => x.Header.Name).ToList());

            for (var rowIndex = 3; rowIndex <= rowCount + 2; rowIndex++)
            {
                var values = new List<string>();
                var model = models[rowIndex - 3];

                foreach (var column in columns)
                {
                    var value = column.Property.GetValue(model)?.ToString();
                    values.Add(value);
                }

                WriteRow(rowIndex, values);
            }

            return book;

            void WriteRow(int rowIndex, List<string> rows)
            {
                var row = sheet.CreateRow(rowIndex);

                if (rowIndex == 0)
                {
                    //  设置表头高度
                    row.Height = row.Height;
                }

                for (int i = 0; i < columnCount; i++)
                {
                    var cell = row.CreateCell(i);

                    if (rowIndex == 2)
                    {
                        //  设置表头单元格样式
                        cell.CellStyle = headerStyle;
                        cell.SetCellValue(rows[i]?.ToString());
                    }
                    else
                    {
                        cell.CellStyle = itemStyle;
                        if (double.TryParse(rows[i], out double tryNumberValue))
                        {
                            cell.SetCellType(CellType.Numeric);
                            //cell.CellStyle.DataFormat = book.CreateDataFormat().GetFormat("#.######");
                            cell.SetCellValue(tryNumberValue);
                        }
                        else
                        {
                            cell.SetCellValue(rows[i]?.ToString());
                        }

                    }
                }
            }

            void WriteMergeRow(int rowIndex, string rowValue, int fromCell, int toCell)
            {
                var row = sheet.CreateRow(rowIndex);

                if (rowIndex == 0)
                {
                    //  设置表头高度
                    row.Height = row.Height;
                }

                var cell = row.CreateCell(0);
                cell.CellStyle = headerStyle;
                cell.SetCellValue(rowValue);

                var region = new NPOI.SS.Util.CellRangeAddress(rowIndex, rowIndex, 0, columnCount - 1);
                HSSFRegionUtil.SetBorderBottom(BorderStyle.Thin, region, (HSSFSheet)row.Sheet, book);
                HSSFRegionUtil.SetBorderTop(BorderStyle.Thin, region, (HSSFSheet)row.Sheet, book);
                HSSFRegionUtil.SetBorderLeft(BorderStyle.Thin, region, (HSSFSheet)row.Sheet, book);
                HSSFRegionUtil.SetBorderRight(BorderStyle.Thin, region, (HSSFSheet)row.Sheet, book);
                row.Sheet.AddMergedRegion(region);
            }
        }

        /// <summary>
        ///     将数据传输对象列表解析为HSSFWorkbook对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="models"></param>
        /// <param name="hashtable"></param>
        /// <param name="firstRow"></param>
        /// <param name="secondRow"></param>
        /// <returns></returns>
        private static HSSFWorkbook Parse<T>(List<T> models,Hashtable hashtable ,string firstRow = "", string secondRow = "")
        {
            var book = new HSSFWorkbook();
            var sheet = book.CreateSheet();
            var headerStyle = GetHeaderStyle(book);
            headerStyle.Alignment = HorizontalAlignment.Center;
            headerStyle.BorderBottom = BorderStyle.Thin;
            headerStyle.BorderLeft = BorderStyle.Thin;
            headerStyle.BorderRight = BorderStyle.Thin;
            headerStyle.BorderTop = BorderStyle.Thin;
            var itemStyle = GetItemStyle(book);
            itemStyle.Alignment = HorizontalAlignment.Center;
            itemStyle.BorderBottom = BorderStyle.Thin;
            itemStyle.BorderLeft = BorderStyle.Thin;
            itemStyle.BorderRight = BorderStyle.Thin;
            itemStyle.BorderTop = BorderStyle.Thin;


            var properties = typeof(T).GetProperties();
            var columns = properties.Select(x => new ColumnHeaderEntity
            {
                Property = x,
                Header = hashtable[x.Name].ToString()
            })
            .Where(x => x.Header != null)
            .ToList();

            //  列数
            var columnCount = columns.Count();
            //  行数
            var rowCount = models.Count();

            SetColumnWith(sheet, columnCount);

            WriteMergeRow(0, firstRow, 0, columnCount - 1);
            WriteMergeRow(1, secondRow, 0, columnCount - 1);

            WriteRow(2, columns.Select(x => x.Header).ToList());

            for (var rowIndex = 3; rowIndex <= rowCount + 2; rowIndex++)
            {
                var values = new List<string>();
                var model = models[rowIndex - 3];

                foreach (var column in columns)
                {
                    var value = column.Property.GetValue(model)?.ToString();
                    values.Add(value);
                }

                WriteRow(rowIndex, values);
            }

            return book;

            void WriteRow(int rowIndex, List<string> rows)
            {
                var row = sheet.CreateRow(rowIndex);

                if (rowIndex == 0)
                {
                    //  设置表头高度
                    row.Height = row.Height;
                }

                for (int i = 0; i < columnCount; i++)
                {
                    var cell = row.CreateCell(i);

                    if (rowIndex == 2)
                    {
                        //  设置表头单元格样式
                        cell.CellStyle = headerStyle;
                        cell.SetCellValue(rows[i]?.ToString());
                    }
                    else
                    {
                        cell.CellStyle = itemStyle;
                        if (double.TryParse(rows[i], out double tryNumberValue))
                        {
                            cell.SetCellType(CellType.Numeric);
                            //cell.CellStyle.DataFormat = book.CreateDataFormat().GetFormat("#.######");
                            cell.SetCellValue(tryNumberValue);
                        }
                        else
                        {
                            cell.SetCellValue(rows[i]?.ToString());
                        }

                    }
                }
            }

            void WriteMergeRow(int rowIndex, string rowValue, int fromCell, int toCell)
            {
                var row = sheet.CreateRow(rowIndex);

                if (rowIndex == 0)
                {
                    //  设置表头高度
                    row.Height = row.Height;
                }

                var cell = row.CreateCell(0);
                cell.CellStyle = headerStyle;
                cell.SetCellValue(rowValue);

                var region = new NPOI.SS.Util.CellRangeAddress(rowIndex, rowIndex, 0, columnCount - 1);
                HSSFRegionUtil.SetBorderBottom(BorderStyle.Thin, region, (HSSFSheet)row.Sheet, book);
                HSSFRegionUtil.SetBorderTop(BorderStyle.Thin, region, (HSSFSheet)row.Sheet, book);
                HSSFRegionUtil.SetBorderLeft(BorderStyle.Thin, region, (HSSFSheet)row.Sheet, book);
                HSSFRegionUtil.SetBorderRight(BorderStyle.Thin, region, (HSSFSheet)row.Sheet, book);
                row.Sheet.AddMergedRegion(region);
            }
        }

        /// <summary>
        ///     获取表头样式
        /// </summary>
        /// <param name="book"></param>
        /// <returns></returns>
        private static ICellStyle GetHeaderStyle(HSSFWorkbook book)
        {
            ICellStyle cellStyle = book.CreateCellStyle();
            IFont font = book.CreateFont();
            font.Color = new HSSFColor.Black().Indexed;
            font.IsBold = true;
            cellStyle.SetFont(font);
            cellStyle.FillPattern = FillPattern.SolidForeground;
            return cellStyle;
        }

        /// <summary>
        ///     获取内容单元格样式
        /// </summary>
        /// <param name="book"></param>
        /// <returns></returns>
        private static ICellStyle GetItemStyle(HSSFWorkbook book)
        {
            var style = book.CreateCellStyle();
            var font = book.CreateFont();
            //font.FontName = "方正舒体";
            font.Color = new HSSFColor.Black().Indexed;
            //font.IsItalic = true;
            //font.FontHeightInPoints = 16;
            font.IsBold = false;
            style.SetFont(font);
            //style.FillBackgroundColor = new HSSFColor.Grey50Percent().Indexed;

            //style.FillForegroundColor = 0;
            style.FillPattern = FillPattern.SolidForeground;
            //((XSSFColor)style.FillForegroundColorColor).SetRgb(new byte[] { 0, 176, 240 });
            return style;
        }

        /// <summary>
        ///     设置列宽
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="columnCount"></param>
        private static void SetColumnWith(ISheet sheet, int columnCount)
        {
            int num = 4096;
            for (int i = 0; i < columnCount; i++)
            {
                sheet.SetColumnWidth(i, num);
            }
        }
}

导出需要用到的Model

    public class ColumnHeaderEntity
    {
        public PropertyInfo Property { get; set; }
        public string Header { get; set; }
    }


    public class ColumnEntry
    {
        public PropertyInfo Property { get; set; }

        public ExportHeaderAttribute Header { get; set; }
    }

public class ExportHeaderAttribute : Attribute
{
    //
    // 摘要:
    //     列名称
    public string Name { get; }

    //
    // 摘要:
    //     列顺序
    public short Order { get; }

    public ExportHeaderAttribute(string name)
        : this(name, -1)
    {
    }

    public ExportHeaderAttribute(string name, short order)
    {
        Name = name;
        Order = order;
    }
}

标签:C#,Excel,导出,rowIndex,book,Thin,var,BorderStyle,row
From: https://www.cnblogs.com/eago/p/18255360

相关文章

  • C++数据格式化2 - 将文件大小转换为人类易读的格式
    1.关键词2.strfmt.h3.strfmt.cpp4.测试代码5.运行结果6.源码地址1.关键词C++数据格式化字符串处理std::string文件大小跨平台2.strfmt.h#pragmaonce#include<string>#include<cstdint>#include<sstream>#include<iomanip>namespacecutl{......
  • Vitis HLS 学习笔记--Vitis Accelerated Libraries介绍
    目录1.简介2.库的组织结构 2.1结构级别L1/L2/L32.2文件内容3.分类介绍3.1 blas3.2codec3.3 data_analytics3.4 data_compression3.5 data_mover3.6 database3.7 dsp3.8graph3.9 hpc3.10 motor_control3.11 quantitative_finance3.12 securi......
  • Vitis HLS 学习笔记--Stream Chain Matrix Multiplication
    目录1.简介2.示例解析2.1示例功能说明2.2函数说明 2.2.1 mmult函数2.2.2 mm2s函数2.2.3 s2mm函数2.2.4总示意图3.总结1.简介这是一个包含使用数据流的级联矩阵乘法的内核。该内核启用了ap_ctrl_chain,以展示如何重叠多个内核调用队列以提供更高的性......
  • Vitis HLS 学习笔记--函数例化(Function Instantiation)
    目录1.简介2.功能分析3.示例分析3.1不使用 FUNCTION_INSTANTIATE3.2使用 FUNCTION_INSTANTIATE4.总结1.简介函数例化(FunctionInstantiation)是VitisHLS中的一个高级优化技术。它允许开发者在保持函数层次结构的同时,对函数的特定实例进行局部优化。如果函......
  • 【Spring Cloud应用框架】
    ......
  • Dynamics CRM 365 验证客户端的网络容量和吞吐量
    如何检查延迟CustomerEngagement应用包括一个基本的诊断工具,用于分析客户端与组织的连接并生成报告。若要运行诊断工具,请按照下列步骤操作。在用户的计算机或设备上,启动Web浏览器,然后登录到组织。输入以下URLhttps://myorg.crm.dynamics.com/tools/diagnostics/diag.asp......
  • C++数据格式化1 - uint转换成字符串 & double转换成字符串
    1.关键词2.strfmt.h3.strfmt.cpp4.测试代码5.运行结果6.源码地址1.关键词C++数据格式化字符串处理std::stringintdouble跨平台2.strfmt.h#pragmaonce#include<string>#include<cstdint>#include<sstream>#include<iomanip>namespacecutl{......
  • css_9_伪元素选择器
    伪元素选择器作用:选中元素的一些特殊位置常用的一些伪元素1.选中元素中的第一个文字(第一个字母)::first-letter/*选中的是div的第一个文字*/div::first-letter{color:blueviolet;font-size:50px;}2.选中的是......
  • css_8_复合选择器_伪类选择器_目标伪类&语言伪类
    一.目标伪类作用:选中锚点指向的元素(特定id)结构::target举例:div:target{background-color:gray;}<ahref="#d1">去目标伪类1</a><ahref="#d2">去目标伪类2</a><divid="d1">这是在说目标伪......
  • css_7_复合选择器_伪类选择器_否定伪类&UI伪类
    一.否定伪类作用:排除满足括号中条件的元素结构:not(选择器)举例:<body><div><p>否定伪类1</p><p>否定伪类2</p><pclass="fail"title="否定伪类3">否定伪类3</p><pclass="fail"ti......