首页 > 编程语言 >C#实现Excel导出

C#实现Excel导出

时间:2023-07-29 20:14:36浏览次数:39  
标签:index C# Excel cells 导出 int exStyle workbook col

C#实现Excel导出需要引用Aspose.Cells。Aspose.Cells下载链接,提取码:2n1u

Excel导出方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Aspose.Cells;
using System.Data;

/// <summary>
/// Excel 文件操作
/// </summary>
public class ExcelFile
{

    /// <summary>
    /// 获取工作本
    /// </summary>
    /// <returns>Workbook</returns>
    public static Workbook GetWorkBook()
    {
        Workbook workbook = new Workbook(); //工作簿 
        return workbook;
    }


    /// <summary>
    /// DataTable转Excel
    /// </summary>
    /// <param name="workbook">工作薄</param>
    /// <param name="dataTable">datatable 数据源</param>
    /// <param name="tableName">表格名称</param>
    /// <param name="exStyle">excel 整体样式</param>
    /// <returns>MemoryStream</returns>
    public static System.IO.MemoryStream OutStream(Workbook workbook, DataTable dataTable, string tableName, ExcelStyle exStyle)
    {
        Worksheet sheet = workbook.Worksheets[0]; //工作表 
        Cells cells = sheet.Cells;//单元格 
        int Colnum = dataTable.Columns.Count;//表格列数 
        int Rownum = dataTable.Rows.Count;//表格行数 
        int index = 0;

        if (tableName != null)
        {
            //生成行1 标题行    
            cells.Merge(0, 0, 1, Colnum);//合并单元格 
            cells[index, 0].PutValue(tableName);//填写内容 
            if (exStyle.TableNameStyle != null)
            {
                cells[index, 0].SetStyle(exStyle.TableNameStyle);
            }
            index++;
            cells.SetRowHeight(0, 38);
        }

        //生成行2 列名行 
        for (int i = 0; i < Colnum; i++)
        {
            cells[index, i].PutValue(dataTable.Columns[i].ColumnName);
            if (exStyle.TitleStyle != null)
            {
                cells[index, i].SetStyle(exStyle.TitleStyle);
            }
            cells.SetRowHeight(index, 25);
        }

        index++;
        //生成数据行 
        for (int i = 0; i < Rownum; i++)
        {
            for (int k = 0; k < Colnum; k++)
            {
                cells[index + i, k].PutValue(dataTable.Rows[i][k].ToString());
                if (exStyle.ContentStyle != null)
                {
                    cells[index + i, k].SetStyle(exStyle.ContentStyle);
                }
            }
            cells.SetRowHeight(index + i, 24);
        }
        int columnCount = cells.MaxColumn;  //获取表页的最大列数
        int rowCount = cells.MaxRow;        //获取表页的最大行数

        for (int col = 0; col < columnCount; col++)
        {
            sheet.AutoFitColumn(col, 0, rowCount);
        }
        //for (int col = 0; col < columnCount; col++)
        //{
        //    cells.SetColumnWidthPixel(col, cells.GetColumnWidthPixel(col) + 30);
        //}

        System.IO.MemoryStream ms = workbook.SaveToStream();
        return ms;
    }


    /// <summary>
    /// DataTable转Excel
    /// </summary>
    /// <param name="workbook">工作薄</param>
    /// <param name="dataTable">datatable 数据源</param>
    /// <param name="tableName">表格名称</param>
    /// <param name="reportInfo">报表信息</param>
    /// <param name="exStyle">excel 整体样式</param>
    /// <returns>MemoryStream</returns>
    public static System.IO.MemoryStream OutStream(Workbook workbook, DataTable dataTable, string tableName, string reportInfo, ExcelStyle exStyle)
    {
        Worksheet sheet = workbook.Worksheets[0]; //工作表 
        Cells cells = sheet.Cells;//单元格 
        int Colnum = dataTable.Columns.Count;//表格列数 
        int Rownum = dataTable.Rows.Count;//表格行数 
        int index = 0;

        if (tableName != null)
        {
            //生成行1 标题行    
            cells.Merge(0, 0, 1, Colnum);//合并单元格 
            cells[index, 0].PutValue(tableName);//填写内容 
            if (exStyle.TableNameStyle != null)
            {
                cells[index, 0].SetStyle(exStyle.TableNameStyle);
            }
            index++;
            cells.SetRowHeight(0, 38);
        }


        if (reportInfo != null)
        {
            //生成行2 标题行    
            cells.Merge(1, 0, 1, Colnum);//合并单元格 
            cells[index, 0].PutValue(reportInfo);//填写内容 
            if (exStyle.TableNameStyle != null)
            {
                cells[index, 0].SetStyle(exStyle.ReprotInfoStyle);
            }
            index++;
            cells.SetRowHeight(0, 38);
        }

        //生成行1/2/3 列名行 
        for (int i = 0; i < Colnum; i++)
        {
            cells[index, i].PutValue(dataTable.Columns[i].ColumnName);
            if (exStyle.TitleStyle != null)
            {
                cells[index, i].SetStyle(exStyle.TitleStyle);
            }
            cells.SetRowHeight(index, 25);
        }

        index++;
        //生成数据行 
        for (int i = 0; i < Rownum; i++)
        {
            for (int k = 0; k < Colnum; k++)
            {
                cells[index + i, k].PutValue(dataTable.Rows[i][k].ToString());
                if (exStyle.ContentStyle != null)
                {
                    cells[index + i, k].SetStyle(exStyle.ContentStyle);
                }
            }
            cells.SetRowHeight(index + i, 24);
        }
        int columnCount = cells.MaxColumn;  //获取表页的最大列数
        int rowCount = cells.MaxRow;        //获取表页的最大行数

        for (int col = 0; col < columnCount; col++)
        {
            sheet.AutoFitColumn(col, 0, rowCount);
        }
        for (int col = 0; col < columnCount; col++)
        {
            cells.SetColumnWidthPixel(col, cells.GetColumnWidthPixel(col) + 30);
        }

        System.IO.MemoryStream ms = workbook.SaveToStream();
        return ms;
    }
}


/// <summary>
/// Excle样式定义类
/// </summary>
public class ExcelStyle
{
    private Style tableNameStyle;
    /// <summary>
    /// 表名称样式
    /// </summary>
    public Style TableNameStyle
    {
        get { return tableNameStyle; }
        set { tableNameStyle = value; }
    }

    private Style reprotInfoStyle;
    /// <summary>
    /// 统计报表信息样式
    /// </summary>
    public Style ReprotInfoStyle
    {
        get { return reprotInfoStyle; }
        set { reprotInfoStyle = value; }
    }


    private Style titleStyle;
    /// <summary>
    /// 表头样式
    /// </summary>
    public Style TitleStyle
    {
        get { return titleStyle; }
        set { titleStyle = value; }
    }
    private Style contentStyle;
    /// <summary>
    /// 表格类容样式
    /// </summary>
    public Style ContentStyle
    {
        get { return contentStyle; }
        set { contentStyle = value; }
    }
}

调用方法

public void Excel(){
    DataTable dataTable = dataTable ();//执行SQL语句返回DataTable
    
    Aspose.Cells.Workbook workbook = ExcelFile.GetWorkBook();
    //为标题设置样式
    Aspose.Cells.Style styleTitle = workbook.Styles[workbook.Styles.Add()];//新增样式
    styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中
    styleTitle.Font.Name = "宋体";//文字字体
    styleTitle.Font.Size = 18;//文字大小
    styleTitle.Font.IsBold = true;//粗体
    //样式2
    Aspose.Cells.Style style2 = workbook.Styles[workbook.Styles.Add()];//新增样式
    style2.HorizontalAlignment = TextAlignmentType.Center;//文字居中
    style2.Font.Name = "宋体";//文字字体
    style2.Font.Size = 14;//文字大小
    style2.Font.IsBold = true;//粗体
    style2.IsTextWrapped = false;//单元格内容自动换行
    style2.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
    style2.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
    style2.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
    style2.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
    //样式3
    Aspose.Cells.Style style3 = workbook.Styles[workbook.Styles.Add()];//新增样式
    style3.HorizontalAlignment = TextAlignmentType.Center;//文字居中
    style3.Font.Name = "宋体";//文字字体
    style3.Font.Size = 12;//文字大小
    style3.IsTextWrapped = false;
    style3.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
    style3.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
    style3.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
    style3.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
    ExcelStyle exStyle = new ExcelStyle();
    exStyle.ContentStyle = style3;
    exStyle.TitleStyle = style2;
    exStyle.TableNameStyle = styleTitle;
    System.IO.MemoryStream ms = ExcelFile.OutStream(workbook, dataTable, "Excel文件名", exStyle);
    HttpResponse response = HttpContext.Current.Response;
    response.Clear();
    response.Buffer = true;
    response.Charset = "utf-8";
    response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpContext.Current.Server.UrlEncode("Excel文件名.xls"));
    response.ContentEncoding = System.Text.Encoding.UTF8;
    response.ContentType = "application/ms-excel; charset=UTF-8 ";
    response.BinaryWrite(ms.ToArray());
    response.End();
}

例:

执行SQL语句如下:

 导出至Excel文件信息如下:

 

标签:index,C#,Excel,cells,导出,int,exStyle,workbook,col
From: https://www.cnblogs.com/lgx5/p/17590370.html

相关文章

  • [CF1849F] XOR Partition
    XORPartition题目描述Forasetofintegers$S$,let'sdefineitscostastheminimumvalueof$x\oplusy$amongallpairsofdifferentintegersfromtheset(here,$\oplus$denotesbitwiseXOR).Iftherearelessthantwoelementsintheset,......
  • CF1849C Binary String Copying
    Link我们想一下,什么时候两种变换是相同的或者说,这意味着什么。本题目有特殊性,特殊性就在于只有0和1对于每一个被改变的区间\([L_i,r_I]\),从\(l_i\)开始的那一堆0,和从\(r_i\)开始的那一堆1都没变。所以变化的部分就要从从左往右第一个1,和从右往左第一个0开始算。这个东西可以......
  • centos7 k8s 三节点 全二进制部署 1.23.15
    主机名IP地址Pod网段Service网段master192.168.1.60172.16.0.0/1210.96.0.0/16node01192.168.1.70172.16.0.0/1210.96.0.0/16node02192.168.1.80172.16.0.0/1210.96.0.0/16[root@master~]#cat/etc/redhat-releaseCentOSLinuxrelease7.9.2......
  • scratch3转换
    大家好,今天来详细讲解一下scratch3保存的文件(.sb3格式)怎么转换成html格式,以及在windows环境下运行的exe格式。一、准备转换工具1.htmlifier-offline.html,用于将sb3文件转换成html文件,这里使用离线版本2.nwjs-v0.52.0-win-x64.zip,用于将html文件打包为桌面应用3.makesfx.exe,......
  • 1.6 PC、手机图形API介绍
    电脑的工作原理:电脑是由各种不同的硬件组成,由驱动软件驱使硬件进行工作。所有的软件工程师都会直接或者间接的使用到驱动。定义:是一个图形库,用于渲染2D、3D矢量图形的跨语言、跨平台的应用程序编程接口(API)。针对GPU。基础概念 应用端:即我们自己的程序段,相对于opengles,我们属......
  • Centos7.9版本安装collectd并开启写入rrd文件功能
    文章目录一、背景介绍二、为什么用这个三、安装Collectd3.1尝试docker安装3.2尝试执行linux命令一步一步安装安装collectd设置将数据写入日志文件设置将数据写入rrd文件。一、背景介绍Collectd官网:https://collectd.org/Collectd是一款开源的系统统计守护进程,用于收集、处理和存......
  • 使用 OpenCV 进行图像模糊度检测(拉普拉斯方差方法)
    写在前面工作中遇到,简单整理人脸识别中,对于模糊程度较高的图像数据,识别率低,错误率高。虽然使用AdaFace模型,对低质量人脸表现尤为突出。但是还是需要对模糊程度高的图像进行丢弃处理当前通过阈值分类,符合要求的进行特性提取实际应用中,可以维护一个质量分数比如由模糊程度,图片字......
  • 手写Nacos基本原理——服务注册 配置管理
    手写Nacos基本原理一、背景介绍二、思路方案三、过程nacosService代码pom文件配置文件具体类nacosSDK代码pom文件配置类具体类serviceA代码pom文件配置文件具体类serviceB代码pom文件配置文件具体类实现效果四、总结五、升华一、背景介绍之前在项目开发的过程中,对于Nacos的理解......
  • 【C语言趣味教程】(4) 变量:代码注释 | 变量的声明 | 初始化与赋值 | 变量的命名 | 关
    Ⅰ.代码注释(Comment)0x00引入:注释的作用"程序员最讨厌两种人:一种是不写注释的人,一种是让我写注释的人。"相信大家对注释早已有所耳闻,对于注释,C语言有两种注释风格,我们下面会逐个讲解。 但在这之前,我们先来了解了解注释的作用,注释就是用于解释代码的文字的。注释通常用于版本、版......
  • 从 Component Tree 视角看 Dagger 到 Hilt 的演变
    1.从Dagger的本质说起一言以蔽之,Dagger的本质就是一棵ComponentTree(组件树)。1.1Component:依赖注入容器component是Dagger中的核心概念,我们通过@Component注解定义并生成代码。component作为依赖注入容器,身兼工厂、仓库、物流三种角色于一身。Dagger中的很多重要......