栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

.net中后端动态生成excel表格

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

.net中后端动态生成excel表格

需求是根据传过来的两个集合 动态生成excel表格模板 并下载
以下面为例:
先NuGet安装包


代码:

 /// 
    /// 下载批量导入模板window版本
    /// 
    /// 
    /// 
    [HttpPost("GetImportFile")]
    public IActionResult GetImportFile(ImportTemplateInDto inDto)
    {
        //需求是根据传过来的两个集合Students和Projects 动态生成下载模板 其中前三列代表学生基本信息且根据所选择的给每一个单元格附上值Projects每一个单元格的值为空即可但是表头需要动态添加进去

        //下载下来的文件名
        string fileName = $"批量导入.xlsx";
        System.Data.DataTable dt = new DataTable();
        //添加前三列 表头
        dt.Columns.Add(new DataColumn("学生姓名(不可更改)", typeof(string)));
        dt.Columns.Add(new DataColumn("学号(不可更改)", typeof(string)));
        dt.Columns.Add(new DataColumn("性别(填”男/女“)", typeof(string)));
        //根据所选的项目集合 动态添加表头
        foreach (var item in inDto.Projects)
        {
            dt.Columns.Add(new DataColumn($"{item.Name}", typeof(string)));
        }
        //为前三列的学生赋值
        for (int i = 0; i < inDto.Students.Count; i++)
        {
            DataRow dataRow = dt.NewRow();
            dataRow[0] = inDto.Students[i].StudentName;
            dataRow[1] = inDto.Students[i].StudentNo;
            dataRow[2] = inDto.Students[i].Sex;

            dt.Rows.Add(dataRow);
        }
        //通过帮助类中的方法把DataTable转化为Excel
        System.IO.MemoryStream ms = AsposeOfficeHelper.DataTableToExcel(dt);
        ms.Position = 0;

        return File(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
     
    }

新建一个帮助类:

帮助类代码:

using Aspose.Cells;
using System.Data;
using System.IO;
using System.Text;

namespace Util
{
    /// 
    /// 使用Aspose组件的Office文件操作帮助类
    /// 
    public class AsposeOfficeHelper
    {
        static AsposeOfficeHelper()
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        }

        /// 
        /// 将DataTable输出为字节数组
        /// 
        /// 表格数据
        /// Byte数组
        public static MemoryStream DataTableToExcel(DataTable dt)
        {
            Workbook book = new Workbook();
            Worksheet sheet = book.Worksheets[0];
            Cells cells = sheet.Cells;
            int Colnum = dt.Columns.Count;//表格列数
            int Rownum = dt.Rows.Count;//表格行数
            //生成行 列名行
            for (int i = 0; i < Colnum; i++)
            {
                cells[0, i].PutValue(dt.Columns[i].ColumnName);
            }
            //生成数据行
            for (int i = 0; i < Rownum; i++) for (int k = 0; k < Colnum; k++) cells[1 + i, k].PutValue(dt.Rows[i][k].ToString());

            //自动行高,列宽
            sheet.AutoFitColumns();
            sheet.AutoFitRows();

            //将DataTable写入内存流
            var ms = new MemoryStream();
            book.Save(ms, SaveFormat.Xlsx);
            return ms;
        }


        /// 
        /// 将DataTable输出为字节数组
        /// 
        /// 表格数据
        /// Byte数组
        public static byte[] DataTableToExcelBytes(DataTable dt)
        {
            return DataTableToExcel(dt).ToArray();
        }

        /// 
        /// 从excel文件导入数据
        /// 注:默认将第一行当作标题行,即不当作数据
        /// 
        /// 文件名
        /// 
        public static DataTable ReadExcel(string fileNmae)
        {
            Workbook book = new Workbook(fileNmae);
            Worksheet sheet = book.Worksheets[0];
            Cells cells = sheet.Cells;

            return cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, true);
        }

        /// 
        /// 从excel文件导入数据
        /// 
        /// 文件名
        /// 起始行
        /// 
        public static DataTable ReadExcel(string fileName, int startRowIndex)
        {
            Workbook book = new Workbook(fileName);
            Worksheet sheet = book.Worksheets[0];
            Cells cells = sheet.Cells;

            return cells.ExportDataTable(startRowIndex, 0, cells.MaxDataRow - (startRowIndex - 1), cells.MaxDataColumn + 1);
        }
        /// 
        /// 从excel文件导入数据
        /// 
        /// 文件名
        /// 是否将第一行当作标题行
        /// 
        public static DataTable ReadExcel(string fileNmae, bool exportColumnName)
        {
            Workbook book = new Workbook(fileNmae);
            Worksheet sheet = book.Worksheets[0];
            Cells cells = sheet.Cells;

            return cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, exportColumnName);
        }

        /// 
        /// 从excel文件字节源导入
        /// 注:默认将第一行当作标题行,即不当作数据
        /// 
        /// 文件字节源
        /// 
        public static DataTable ReadExcel(byte[] fileBytes)
        {
            return ReadExcel(fileBytes, true);
        }

        /// 
        /// 从excel文件字节源导入
        /// 
        /// 文件字节源
        /// 是否将第一行当作标题行
        /// 
        public static DataTable ReadExcel(byte[] fileBytes, bool exportColumnName)
        {
            using (MemoryStream ms = new MemoryStream(fileBytes))
            {
                Workbook book = new Workbook(ms);
                Worksheet sheet = book.Worksheets[0];
                Cells cells = sheet.Cells;

                return cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, exportColumnName);
            }
        }
    }
}

运行结果如下:第一个集合学生列表有三个学生 学生名为: 会,哈哈哈,hello1。第二个集合项目有:400米,800米,体重,跳绳 。因为前三列 是我固定写死的不需要变得

注意:这个只是windows版本,如果是linux操作系统这个方法会报错,目前的话我也是有写了linux版本的,后续可能会更新一下。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/923123.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号