• C#利用NPOI导出Excel类(简单版)


    代码:

    using System.Data;
    using System.IO;
    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    
    namespace ahwildlife.Utils
    {
        /// <summary>
        /// Excel工具类
        /// 利用NPOI生成Excel
        /// </summary>
        public class ExcelUtil
        {
            #region 生成Excel
            /// <summary>
            /// 生成Excel
            /// </summary>
            public static void CreateExcel(DataTable dt, string path)
            {
                HSSFWorkbook workbook = new HSSFWorkbook();
                ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);//创建工作表
    
                #region 标题
                IRow row = sheet.CreateRow(0);//在工作表中添加一行
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    ICell cell = row.CreateCell(i);//在行中添加一列
                    cell.SetCellValue(dt.Columns[i].ColumnName);//设置列的内容     
                }
                #endregion
    
                #region 填充数据
                for (int i = 1; i <= dt.Rows.Count; i++)//遍历DataTable行
                {
                    DataRow dataRow = dt.Rows[i - 1];
                    row = sheet.CreateRow(i);//在工作表中添加一行
    
                    for (int j = 0; j < dt.Columns.Count; j++)//遍历DataTable列
                    {
                        ICell cell = row.CreateCell(j);//在行中添加一列
                        cell.SetCellValue(dataRow[j].ToString());//设置列的内容     
                    }
                }
                #endregion
    
                #region 输出到Excel
                MemoryStream ms = new MemoryStream();
                workbook.Write(ms);
    
                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    byte[] bArr = ms.ToArray();
                    fs.Write(bArr, 0, bArr.Length);
                    fs.Flush();
                }
                #endregion
    
            }
            #endregion
    
        }
    }
    View Code
  • 相关阅读:
    express开发实例
    node.js操作mongoDB数据库
    Mysql JDBC Url参数说明useUnicode=true&characterEncoding=UTF-8
    Hibernate 使用说明
    mysql 时间戳与日期格式的相互转换
    MOOC即Massive Open Online Course的缩写
    CentOS+Apache+php无法访问redis的解决方法
    CentOS 6.5下Redis安装详细步骤
    Linux进程基础
    CentOS如何查看端口是被哪个应用/进程占用
  • 原文地址:https://www.cnblogs.com/s0611163/p/4022165.html
Copyright © 2020-2023  润新知