zoukankan      html  css  js  c++  java
  • 【C#-导出Excel】DataSet导出Excel

    1、添加引用

    2、封装方法

    using System;
    using System.Data;
    using System.IO;
    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    
    namespace Demo
    {
        /// <summary>
        /// Excel操作类
        /// </summary>
        public class Excel
        {
            private readonly HSSFWorkbook workbook = null;
            private readonly DataSet dataSet = null;
            private readonly string excelFilename = string.Empty;
    
            private readonly ICellStyle cellDateTimeStyle = null;
    
            /// <summary>
            /// Excel操作类构造函数
            /// </summary>
            /// <param name="dataSet"></param>
            /// <param name="excelFilename"></param>
            public Excel(DataSet dataSet, string excelFilename)
            {
                this.dataSet = dataSet;
                this.excelFilename = excelFilename;
                workbook = new HSSFWorkbook();
    
                IDataFormat iDataFormat = workbook.CreateDataFormat();
                //设置一个DateTime单元格的样式
                cellDateTimeStyle = workbook.CreateCellStyle();
                cellDateTimeStyle.DataFormat = iDataFormat.GetFormat("yyyy-m-d h:mm:ss");
            }
    
            /// <summary>
            /// 生成excel
            /// </summary>
            /// <returns></returns>
            public bool Write()
            {
                bool returns = false;
                using (FileStream saveFile = new FileStream(excelFilename, FileMode.Create, FileAccess.ReadWrite))
                {
                    WriteExcelFile(dataSet);
                    workbook.Write(saveFile);
                    returns = true;
                }
                return returns;
            }
    
            private void WriteExcelFile(DataSet ds)
            {
                foreach (DataTable dt in ds.Tables)
                {
                    ISheet sheet = workbook.CreateSheet(dt.TableName);
                    WriteDataTableToExcelWorksheet(dt, sheet);
                }
            }
    
            private void WriteDataTableToExcelWorksheet(DataTable dt, ISheet sheet)
            {
                //生成sheet第一行列名 
                IRow row = sheet.CreateRow(0);
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    ICell cell = row.CreateCell(i);
                    cell.SetCellValue(dt.Columns[i].Caption);
                }
                //写入数据
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    IRow rows = sheet.CreateRow(i + 1);
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        ICell cell = rows.CreateCell(j);
                        var cellValue = dt.Rows[i][j];
                        if (cellValue == DBNull.Value)
                        {
                            continue;
                        }
                        //类型判断处理
                        var type = cellValue.GetType();
                        var typeName = type.Name.ToLower();
                        switch (typeName)
                        {
                            case "int32":
                                cell.SetCellValue(double.Parse(cellValue.ToString()));
                                break;
                            case "string":
                                cell.SetCellValue(cellValue.ToString());
                                break;
                            case "datetime":
                                cell.CellStyle = cellDateTimeStyle;
                                cell.SetCellValue(DateTime.Parse(cellValue.ToString()));
                                break;
                            case "guid":
                                cell.SetCellValue(cellValue.ToString());
                                break;
                            case "boolean":
                                cell.SetCellValue(bool.Parse(cellValue.ToString()));
                                break;
                            default:
                                throw new Exception(string.Format("类型:{0}未做处理,请自行添加", typeName));
                        }
                    }
                }
            }
        }
    }

    3、实际应用

    using System;
    using System.Data;
    
    namespace Demo
    {
        class Program
        {
            static void Main(string[] args)
            {
                DataSet dataSet = new DataSet();
                DataTable dataTable = new DataTable();
                dataTable.TableName = "Demo";
                dataTable.Columns.Add("Id", typeof(int));
                dataTable.Columns.Add("名称", typeof(string));
                dataTable.Columns.Add("年龄", typeof(int));
                dataTable.Columns.Add("添加日期", typeof(DateTime));
    
                for (int i = 0; i < 1000; i++)
                {
                    dataTable.Rows.Add(i, "名称demo" + i, 18, DateTime.Now);
                }
                dataSet.Tables.Add(dataTable);
    
                Excel excel = new Excel(dataSet, "Demo.xls");
                excel.Write();
            }
        }
    }
  • 相关阅读:
    菜鸟nginx源码剖析数据结构篇(十一) 共享内存ngx_shm_t[转]
    菜鸟nginx源码剖析数据结构篇(十) 自旋锁ngx_spinlock[转]
    菜鸟nginx源码剖析数据结构篇(九) 内存池ngx_pool_t[转]
    菜鸟nginx源码剖析数据结构篇(八) 缓冲区链表ngx_chain_t[转]
    菜鸟nginx源码剖析数据结构篇(七) 哈希表 ngx_hash_t(下)[转]
    菜鸟nginx源码剖析数据结构篇(六) 哈希表 ngx_hash_t(上)[转]
    菜鸟nginx源码剖析数据结构篇(五) 基数树 ngx_radix_tree_t[转]
    菜鸟nginx源码剖析数据结构篇(四)红黑树ngx_rbtree_t[转]
    菜鸟nginx源码剖析数据结构篇(三) 单向链表 ngx_list_t[转]
    菜鸟nginx源码剖析数据结构篇(二) 双向链表ngx_queue_t[转]
  • 原文地址:https://www.cnblogs.com/Sukie-s-home/p/6547692.html
Copyright © 2011-2022 走看看