C# WinForm下Excel导入导出

编辑器加载中...

DataSet数据集内数据转化为Excel文件
/// <summary> 
/// ExportFiles 的摘要说明。 
/// 作用:把DataSet数据集内数据转化为Excel文件 
/// 描述:导出Excel文件    
/// 备注:请引用Office相应COM组件,导出Excel对象的一个方法要调用其中的一些方法和属性。 
/// </summary> 
public class ExportFiles 
{ 
    private string filePath = ""; 
    public ExportFiles(string excel_path) 
    { 
        // 
        // TODO: 在此处添加构造函数逻辑 
        // 
        filePath = excel_path; 
    } 
    /// <summary> 
    /// 将指定的Dataset导出到Excel文件 
    /// </summary> 
    /// <param name="dt"></param> 
    /// <returns></returns> 
    public bool ExportToExcel(System.Data.DataSet ds, string ReportName) 
    { 
        if (ds.Tables[0].Rows.Count == 0) 
        { 
            MessageBox.Show("数据集为空"); 
        } 
        Microsoft.Office.Interop.Excel._Application xlapp = new ApplicationClass(); 
        Workbook xlbook = xlapp.Workbooks.Add(true); 
        Worksheet xlsheet = (Worksheet)xlbook.Worksheets[1]; 
        Range range = xlsheet.get_Range(xlapp.Cells[1, 1], xlapp.Cells[1, ds.Tables[0].Columns.Count]); 
        range.MergeCells = true; 
        xlapp.ActiveCell.FormulaR1C1 = ReportName; 
        xlapp.ActiveCell.Font.Size = 20; 
        xlapp.ActiveCell.Font.Bold = true; 
        xlapp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter; 
        int colIndex = 0; 
        int RowIndex = 2; 
        //开始写入每列的标题 
        foreach (DataColumn dc in ds.Tables[0].Columns) 
        { 
            colIndex++; 
            xlsheet.Cells[RowIndex, colIndex] = dc.Caption; 
        } 
        //开始写入内容 
        int RowCount = ds.Tables[0].Rows.Count;//行数 
        for (int i = 0; i < RowCount; i++) 
        { 
            RowIndex++; 
            int ColCount = ds.Tables[0].Columns.Count;//列数 
            for (colIndex = 1; colIndex <= ColCount; colIndex++) 
            { 
                xlsheet.Cells[RowIndex, colIndex] = ds.Tables[0].Rows[i][colIndex - 1];//dg[i, colIndex - 1]; 
                xlsheet.Cells.ColumnWidth = ds.Tables[0].Rows[i][colIndex - 1].ToString().Length; 
            } 
        } 

        xlbook.Saved = true; 
        xlbook.SaveCopyAs(filePath); 
        xlapp.Quit(); 
        GC.Collect(); 
        return true; 
    } 

    public bool ExportToExcelOF(System.Data.DataSet ds, string ReportName) 
    { 
        if (ds.Tables[0].Rows.Count == 0) 
        { 
            MessageBox.Show("数据集为空"); 
        } 
        string FileName = filePath; 

        //System.Data.DataTable dt = new System.Data.DataTable(); 
        FileStream objFileStream; 
        StreamWriter objStreamWriter; 
        string strLine = ""; 
        objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write); 
        objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode); 

        strLine = ReportName; 
        objStreamWriter.WriteLine(strLine); 
        strLine = ""; 

        for (int i = 0; i < ds.Tables[0].Columns.Count; i++) 
        { 
            strLine = strLine + ds.Tables[0].Columns[i].ColumnName.ToString() + "          " + Convert.ToChar(9); 
        } 
        objStreamWriter.WriteLine(strLine); 
        strLine = ""; 

        for (int i = 0; i < ds.Tables[0].Rows.Count; i++) 
        { 
            strLine = strLine + (i + 1) + Convert.ToChar(9); 
            for (int j = 1; j < ds.Tables[0].Columns.Count; j++) 
            { 
                strLine = strLine + ds.Tables[0].Rows[i][j].ToString() + Convert.ToChar(9); 
            } 
            objStreamWriter.WriteLine(strLine); 
            strLine = ""; 
        } 
        objStreamWriter.Close(); 
        objFileStream.Close(); 

        //Microsoft.Office.Interop.Excel._Application xlapp = new ApplicationClass(); 
        //Workbook xlbook = xlapp.Workbooks.Add(true); 
        //Worksheet xlsheet = (Worksheet)xlbook.Worksheets[1]; 
        //Range range = xlsheet.get_Range(xlapp.Cells[1, 1], xlapp.Cells[1, ds.Tables[0].Columns.Count]); 
        //range.EntireColumn.AutoFit(); 
        //xlapp.Quit(); 
        return true; 
    }      
}
网上能搜到许多DataTable导出EXCEL的文章,但实施起来,可行者不多也!本人认真调试了一番,问题得以解决,现整理与大家分享:
一、实现目标:

    由一个内存表DataTable,导出字段名及其内容的完整EXCEL表格

二、实施步骤:

1、添加引用:

   这是非常生要的一步,很多人调试不成都是因为这步没做好:

   需要在你的解决方案中添加COM引用,选择 "Microsoft EXCEL ...."(根据版本有所不同),这是为下面的 EXCEL相关命名空间的引用做铺垫的;

   我用的EXCEL 2007,添加COM引用后如下图:

 

            


 

    增加了两个引用文件!

2、命名空间引用部分:

   增加下面的引用内容:

   using Microsoft.Office.Interop.Excel;

3、定义函数:

    public static void DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName)

    {

        if (tmpDataTable == null)

            return;

        int rowNum = tmpDataTable.Rows.Count;

        int columnNum = tmpDataTable.Columns.Count;

        int rowIndex = 1;

        int columnIndex = 0;

 

        Application xlApp = new ApplicationClass();

        xlApp.DefaultFilePath = "";

        xlApp.DisplayAlerts = true;

        xlApp.SheetsInNewWorkbook = 1;

        Workbook xlBook = xlApp.Workbooks.Add(true);

 

        //将DataTable的列名导入Excel表第一行

        foreach (DataColumn dc in tmpDataTable.Columns)

        {

            columnIndex++;

            xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;

        }

 

        //将DataTable中的数据导入Excel中

        for (int i = 0; i < rowNum; i++)

        {

            rowIndex++;

            columnIndex = 0;

            for (int j = 0; j < columnNum; j++)

            {

                columnIndex++;

                xlApp.Cells[rowIndex, columnIndex] = tmpDataTable.Rows[i][j].ToString();

            }

        }

        //xlBook.SaveCopyAs(HttpUtility.UrlDecode(strFileName, System.Text.Encoding.UTF8));

        xlBook.SaveCopyAs(strFileName);

    }

}

4、 使用实例:

       System.Data.DataTable dt = ……;   //准备好你的DataTable

       DataTabletoExcel(dt, "C:\\\\中国.XLS");   //调用自定义的函数,当然输出文件你可以随便写

三、测试环境:

    VS2008,EXCEL 2007