从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, FileMode.Create, FileAccess.Write))
            {
                byte[] data = ms.ToArray();

                fs.Write(data, 0, data.Length);
                fs.Flush();

                data = null;
            }
        }

使用NPOI来操作Excel:

        /// <summary>
        /// dataset To Excel
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        private static MemoryStream ToExcel(DataSet ds)
        {
            MemoryStream ms = new MemoryStream();
            IWorkbook workbook = new HSSFWorkbook();
            foreach (DataTable table in ds.Tables)
            {
                using (table)
                {
                    ISheet sheet = workbook.CreateSheet(table.TableName);
                    IRow headerRow = sheet.CreateRow(0);

                    //handling header.
                    foreach (DataColumn column in table.Columns)
                        headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value

                    //handling value.
                    int rowIndex = 1;

                    foreach (DataRow row in table.Rows)
                    {
                        IRow dataRow = sheet.CreateRow(rowIndex);

                        foreach (DataColumn column in table.Columns)
                        {
                            dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                        }

                        rowIndex++;
                    }
                }

                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
            }
            return ms;
        }

最后是调用的方法,也就是入口:

private void Button5_Click(object sender, EventArgs e)
        {
            SaveFileDialog opf = new SaveFileDialog();
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();
            dt.Columns.Add("编号");   //"编号"
            dt.Columns.Add("品名");   //"品名"
            dt.Columns.Add("规格");   //"规格"
            dt.Columns.Add("单位");   //"单位"
            dt.Columns.Add("申请数量");   //"申请数量
            dt.Columns.Add("描述");   //"描述"
            dt.TableName = "sheet1";
            ds.Tables.Add(dt.Copy());
            dt.TableName = "sheet2";
            ds.Tables.Add(dt.Copy());
            dt.TableName = "sheet3";
            ds.Tables.Add(dt.Copy());
            opf.Filter = "Excel93-07文件(*.xls)|*.xls";
            if (DialogResult.OK.Equals(opf.ShowDialog()))
            {
                string localfilepath = opf.FileName.ToString();
                string fileNameExt = localfilepath.Substring(localfilepath.LastIndexOf("\\") + 1); //获取文件名,不带路径
                string[] names = fileNameExt.Split(‘.‘);
                string FilePath = localfilepath.Substring(0, localfilepath.LastIndexOf("\\"));
                string newFileName = FilePath + "\\" + names[0] + "_" + string.Format("{0:yyyy-MM-dd}", DateTime.Now) + "." + names[1];     //fileNameExt   DateTime.Now.ToString("yyyyMMdd")
                RenderToExcel.DataTableToExcel(ds, newFileName);
                MessageBox.Show( "导出完成!", "提示");
            }
        }

意思就是这个意思,顺带把引用也贴上:

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using ICSharpCode.SharpZipLib.Core;

这个四个引用,缺一不可,关于NPOI大家自行百度

导入以上四个引用即可。

时间: 2024-10-29 00:19:35

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

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

1.当dataset中包含了html等特殊字符用这个处理 public void CreateExcel2(DataSet ds) { //创建一个excel application Excel.Application xls_exp=null; int rowindex=1; int colindex=0; //创建一个workbook,一个worksheet Excel._Workbook xls_book=null; Excel._Worksheet xls_sheet=null; try

ASP.NET用DataSet导出到Excel

//读取临时文件    GYYW.DA.Common.Base_SqlDataBase daBZDM = new GYYW.DA.Common.Base_SqlDataBase();    DataSet dsBZDM = daBZDM.GetDataSetBySql("select QCDM,MC,GG from WG_BZDM where QCDM like '02%'");    //同时将虚拟目录下的Data作为临时文件目录.    string urlPath = HttpC

dataset导出成excel

之前网上查找了很多关于这类的代码.要不是中文乱码,要不是就是太复杂.这个是我用过最好用的. //ds为数据源,filename为保存的文件名 publicvoidCreateExcel(DataSet ds,stringFileName) { //设置信息 HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType="application/vnd.ms-excel"; HttpConte

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;

DevExpress GridControl GridView 导出到 Excel 类

说明: 1>GridView 导出到 Excel (如果分页,只导出当前页数据) 2>GridView 导出到 Excel 3>方法2可以参考DataTable 导出到 Excel 自定义类如下: #region GridView 导出到 Excel Method First /// <summary> /// GridView 导出到 Excel (如果分页,只导出当前页数据) /// </summary> /// <param name="gv

数据导出至Excel文件--好库编程网http://code1.okbase.net/codefile/SerializeHelper.cs_2012122018724_118.htm

using System; using System.IO; using System.Data; using System.Collections; using System.Data.OleDb; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; /// <summary> /// Excel操作类 /// </summary> /// Microsoft Excel 11.0 Obj

C#dataset中数据导出到excel

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Data;using System.Reflection;using Microsoft.Office;//using Excel = Microsoft.Office.Interop.Excel;using

C# 将dataset数据导出到excel中

//添加引用 NPOI.dll //添加 using NPOI.HSSF.UserModel; /// <summary> /// 导出数据到Excel /// </summary> /// <param name="returnMsg"></param> /// <returns></returns> public bool ExportOrderToExcel(ref string returnMsg) { t

dataset 导出Excel

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