DataSet导出Excel

Posted 没有爪子的猫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
        }
    }
}

 

以上是关于DataSet导出Excel的主要内容,如果未能解决你的问题,请参考以下文章

DataSet导出Excel

xml方式将dataset导出excel

由DataSet导出生成excel的几种方法

请问如何把dataset里面的表导出到excel中?

unigui导出EXCEL使用NATIVEEXCEL

求将dataset数据集导出到excel文件的方法(vs2005 c#)