datatable 導出到Execl

public static bool ExportToExcel(DataTable table, string excelName, int[] columnIndexs, string[] columnHeads)
    {
        #region 將方法中用到的所有Excel變量聲明在方法最開始,以便最後統一回收。
         Excel.ApplicationClass oExcel = new Excel.ApplicationClass();
        Excel.Workbook obook = null;
        Excel.Worksheet oSheet = null;
        Excel.Range range = null;
        #endregion
        try
        {
            obook = oExcel.Workbooks.Add("");
            oSheet = (Excel.Worksheet)obook.Worksheets[1];
            int rCount, cCount;
            rCount = table.Rows.Count;
            cCount = table.Columns.Count;
            object obj = System.Reflection.Missing.Value;

            if (cCount < columnIndexs.Length || cCount < columnHeads.Length)
            {
                throw new ArgumentOutOfRangeException("columnIndexs 與 columnHeads 長度必須一致。");
            }
            for (int i = 1; i <= columnIndexs.Length; i++)
            {
                //Excel.Range = (Excel.Range)oSheet.Columns.get_Item(i, obj); 
                range = (Excel.Range)oSheet.Columns.get_Item(i, obj);
                range.NumberFormatLocal = "@";
            }
            for (int c = 0; c < columnIndexs.Length; c++)
            {
                oSheet.Cells[1, c + 1] = columnHeads[c];
                for (int r = 1; r <= rCount; r++)
                {
                    oSheet.Cells[r + 1, c + 1] = table.Rows[r - 1][columnIndexs[c]].ToString();
                }
            }
            obook.SaveCopyAs(excelName);
            //必須調用 obook.Close(), 否則無法釋放進程。
            obook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
            return true;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
           // 調用System.Runtime.InteropServices.Marshal.ReleaseComObject(object) 方法釋放方法中
            //用到的所有的Excel 變量, 記住是所有的。 比如說此方法中的range 對象, 就容易被遺忘。
           
             ystem.Runtime.InteropServices.Marshal.ReleaseComObject(range);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oSheet);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obook);
           
            // 很多文章上都說必須調用此方法, 但是我試過沒有調用oExcel.Quit() 的情況, 進程也能安全退出,
             //還是保留着吧。
            oExcel.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);
            // 垃圾回收是必須的。 測試如果不執行垃圾回收, 無法關閉Excel 進程。
            GC.Collect();
        }
    }

  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章