DataTable匯出成Excel

來源:互聯網
上載者:User

DataTable匯出成Excel

網上能搜到許多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

其實Excel的版本是2003與2007都無所謂,主要是看你添加進來的庫檔案版本適合不適合

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.