日期:2014-05-17  浏览次数:20985 次

C#将数据集DataSet中的数据导出到EXCEL文件的几种方法
[size=x-large]using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Windows.Forms;
using System.Reflection;

namespace DMS
{
/// <summary>
/// C#操作Excel类
/// </summary>
class ExcelOperate
{
//法一
//public bool DataSetToExcel(DataSet dataSet, bool isShowExcle)
//{
//    DataTable dataTable = dataSet.Tables[0];
//    int rowNumber = dataTable.Rows.Count;
//    int columnNumber = dataTable.Columns.Count;

//    if (rowNumber == 0)
//    {
//        MessageBox.Show("没有任何数据可以导入到Excel文件!");
//        return false;
//    }

//    //建立Excel对象
//    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
//    excel.Application.Workbooks.Add(true);
//    excel.Visible = isShowExcle;//是否打开该Excel文件

//    //填充数据
//    for (int c = 0; c < rowNumber; c++)
//    {
//        for (int j = 0; j < columnNumber; j++)
//        {
//            excel.Cells[c + 1, j + 1] = dataTable.Rows[c].ItemArray[j];
//        }
//    }

//    return true;
//}


//法二
//public bool DataSetToExcel(DataSet dataSet, bool isShowExcle)
//{
//    DataTable dataTable = dataSet.Tables[0];
//    int rowNumber = dataTable.Rows.Count;

//    int rowIndex = 1;
//    int colIndex = 0;


//    if (rowNumber == 0)
//    {
//        return false;
//    }

//    //建立Excel对象
//    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
//    excel.Application.Workbooks.Add(true);
//    excel.Visible = isShowExcle;

//    //生成字段名称
//    foreach (DataColumn col in dataTable.Columns)
//    {
//        colIndex++;
//        excel.Cells[1, colIndex] = col.ColumnName;
//    }

//    //填充数据
//    foreach (DataRow row in dataTable.Rows)
//    {
//        rowIndex++;
//        colIndex = 0;
//        foreach (DataColumn col in dataTable.Columns)
//        {
//            colIndex++;
//            excel.Cells[rowIndex, colIndex] = row[col.ColumnName];
//        }
//    }

//    return true;
//}

//法三(速度最快)
/// <summary>
/// 将数据集中的数据导出到EXCEL文件
/// </summary>
/// <param name="dataSet">输入数据集</param>
/// <param name="isShowExcle">是否显示该EXCEL文件</param>
/// <returns></returns>
public bool DataSetToExcel(DataSet dataSet, bool isShowExcle)