DataTable导出到Excel高效率代码分享
1)下述方法中,将DataTable单元格内容写入数组后一次性赋值给Excel的Range,效率非常高,比之循环DataTable单元格逐个赋值给Excel的Cell的方法,速度快多了;2)下述方法中用到的彻底关闭Excel进程的方式,也值得注意。
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int pid);
//函数原型;DWORD GetWindowThreadProcessld(HWND hwnd,LPDWORD lpdwProcessld);
//参数:hWnd:窗口句柄
//参数:lpdwProcessld:接收进程标识的32位值的地址。如果这个参数不为NULL,GetWindwThreadProcessld将进程标识拷贝到这个32位值中,否则不拷贝
//返回值:返回值为创建窗口的线程标识。
//dt:从数据库读取的数据;file_name:保存路径;sheet_name:表单名称
private void DataTableToExcel(DataTable dt, string file_name, string sheet_name)
{
Microsoft.Office.Interop.Excel.Application Myxls = newMicrosoft.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;
for(int i = 0; i < dt.Columns.Count; i++)
{
arrHeader = dt.Columns.ColumnName;
}
MySht.Range, MySht.Cells].Value2 = arrHeader;
//写入表体数据
object[,] arrBody = new object;
for(int i = 0; i < dt.Rows.Count; i++)
{
for(int j = 0; j < dt.Columns.Count; j++)
{
arrBody = dt.Rows.ToString();
}
}
MySht.Range, MySht.Cells].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, "系统提示");
}
finally
{
//彻底关闭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("结束当前EXCEL进程失败:" + ex.Message);
}
Myxls = null;
}
GC.Collect();
}
}
888555 20170527
页:
[1]