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();
        }
    }
}
时间: 2025-01-04 05:56:18

DataSet导出Excel的相关文章

NPOI DataSet导出excel

/// <summary> /// DataSet导出到Excel的MemoryStream /// </summary> /// <param name="dtSource">源DataSet</param> public static MemoryStream DataSetToExcel(DataSet ds) { XSSFWorkbook workbook = new XSSFWorkbook(); for (int k = 0;

dataset 导出Excel

/// <summary> /// /// </summary> /// <param name="dataSet">要导出的数据来源</param> /// <param name="fileName">导出的Excel名称</param> /// <param name="saveDirectoryName">要保存到服务器上文件夹的名称</param&

xml方式将dataset导出excel

using System;using System.Collections;using System.Collections.Generic;using System.Data;using System.IO;using System.Linq;using System.Text;using System.Threading; namespace Cinway.Common{    public class xmlParam {        public string totalcount {

导出Excel方法(winform或web)

一.winform形式导出Excel 此方法适用于winform项目导出Excel,使用前需要引用Excel.dll,此处是直接用ds导出Excel,导出方法类GetExport如下: 1 using System; 2 using System.Collections.Generic; 3 using System.Data; 4 using System.IO; 5 using System.Text; 6 using System.Windows.Forms; 7 using Excel;

[转] Asp.Net 导出 Excel 数据的9种方案

湛刚 de BLOG 原文地址 Asp.Net 导出 Excel 数据的9种方案 简介 Excel 的强大之处在于它不仅仅只能打开Excel格式的文档,它还能打开CSV格式.Tab格式.website table 等多钟格式的文档.它具备自动识别行号,字符,格式化数字等功能,例如:如果你在Excel 单元格中输入数字 "123456789012" 会自动转化为"1.23457E+11". 背景介绍 正因为Excel的强大和易用,大家都喜欢将数据导出为 Excel 备

StreamWriter(dataset)导出EXCEL

public void WriteExcel(DataSet ds, string path) { try { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Execl files (*.xls)|*.xls"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDi

Asp.net中由DataSet数据类型导出Excel

今天要做一个功能 导出录取学生信息 费了半天劲结果被老师教育了一番 好了不抱怨了 DataSet数据类型导出Excel 好了不说了上源码 try { System.Web.HttpContext curContext = System.Web.HttpContext.Current; DataSet dsExcel = xqgl.Select_DCXSXXALL(); DataGrid dg = new DataGrid(); dg.DataSource = dsExcel; dg.DataBi

从DataSet 导出到Excel(是DataSet中的每个DataTable对应每个Sheet)

先来主要代码: public static void DataTableToExcel(DataSet dt, string Filename) { SaveToFile(ToExcel(dt), Filename); } 从上往下哈↓↓↓↓↓↓↓↓↓↓↓↓ private static void SaveToFile(MemoryStream ms, string fileName) { using (FileStream fs = new FileStream(fileName, FileM

【C#常用方法】2.DataTable(或DataSet)与Excel文件之间的导出与导入(使用NPOI)

DataTable与Excel之间的互导 1.项目添加NPOI的引用 NPOI项目简介: NPOI是一个开源的C#读写Excel.WORD等微软OLE2组件文档的项目,特点是可以在没有安装Office的情况下对Word或Excel文档进行读写操作.并且对老版本Office(2003-)与新版本Office(2007+)均有较好的支持.NPOI功能非常强大,可以操作Excel或Word文档的各个细节,如果你对NPOI想进行细致的学习,淘宝上有专门有书来讲NPOI,当然也可以访问NPOI的官方网站查