軟件開發(fā)過程中,經(jīng)常會將大批量數(shù)據(jù)導(dǎo)出到excel,但常用的datatable循環(huán)方式導(dǎo)出excel已經(jīng)很大的影響了性能。創(chuàng)軟軟件開發(fā)團隊經(jīng)過多次調(diào)試分析,總結(jié)了快速將大批量DataTable中的數(shù)據(jù)導(dǎo)出到excel表格,同時解決了徹底關(guān)閉Excel進程的問題。
話不多說,直接上代碼
using Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; //dt:從數(shù)據(jù)庫讀取的數(shù)據(jù);file_name:保存路徑;sheet_name:表單名稱 private void DataTableToExcel(DataTable dt, string file_name, string sheet_name) { Microsoft.Office.Interop.Excel.Application Myxls = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook Mywkb = Myxls.Workbooks.Add(); Microsoft.Office.Interop.Excel.Worksheet MySht = Mywkb.ActiveSheet; MySht.Name = sheet_name; Myxls.Visible = false; Myxls.DisplayAlerts = false; try { //寫入表頭 object[] arrHeader = new object[dt.Columns.Count]; for(int i = 0; i < dt.Columns.Count; i++) { arrHeader[i] = dt.Columns[i].ColumnName; } MySht.Range[Mysht.Cells[1,1], MySht.Cells[1,dt.Columns.Count]].Value2 = arrHeader; //寫入表體數(shù)據(jù) object[,] arrBody = new object[dt.Rows.Count, dt.Columns.Count]; for(int i = 0; i < dt.Rows.Count; i++) { for(int j = 0; j < dt.Columns.Count; j++) { arrBody[i,j] = dt.Rows[i][j].ToString(); } } MySht.Range[MySht.Cells[2,1], MySht.Cells[dt.Rows.Count + 1, dt.Columns.Count]].Value2 = arrBody; if(Mywkb != null) { Mywkb.SaveAs(file_name); Mywkb.Close(Type.Missing, Type.Missing, Type.Missing); Mywkb = null; } } catch(Exception ex) { MessageBox.Show(ex.Message, "系統(tǒng)提示"); } finally { //徹底關(guān)閉Excel進程 if(Myxls != null) { Myxls.Quit(); try { if(Myxls != null) { int pid; GetWindowThreadProcessId(new IntPtr(Myxls.Hwnd), out pid); System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(pid); p.Kill(); } } catch(Exception ex) { MessageBox.Show("結(jié)束當前EXCEL進程失?。?quot; + ex.Message); } Myxls = null; } GC.Collect(); } }
需要C#從大量數(shù)據(jù)的DataTable高效率快速導(dǎo)出到Excel的方法及源代碼的同學(xué)可以試一下,上面代碼已經(jīng)應(yīng)用到了創(chuàng)軟開發(fā)框架平臺。