datatable 倒入excel

来源:互联网 发布:js设计模式有哪些东西 编辑:程序博客网 时间:2024/06/06 22:53

大家好,我有个datatable dt,列20,行2000,用如下方法倒入excel,用时20分钟,可有更好点的方法
Excel.Application excel = new Excel.Application ( ) ;
excel.Application.Workbooks.Add ( true ) ;
for(int n =0;n<dt.Columns.Count;n++)
{
   excel.Cells[1,n+1] = dt.Columns[n].ColumnName;
}
for(int i=0;i<dt.Rows.Count;i++)
{
for(int j=0;j<dt.Columns.Count;j++)
{
excel.Cells[i+2,j+1] = dt.Rows[i][j].ToString();
}
}
Excel.Range r1 = excel.get_Range(excel.Cells[1,1],excel.Cells[dt.Rows.Count+1,dt.Columns.Count]);
r1.EntireColumn.AutoFit();
r1.EntireRow.AutoFit();
r1.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
r1.VerticalAlignment   = Excel.XlVAlign.xlVAlignCenter;
excel.Visible = true ;

////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////

楼主打开
Excel.Application excel = new Excel.Application ( ) ;
excel.Application.Workbooks.Add ( true ) ;
//打开excel后让其不可见,特别是设置ScreenUpdating为false避免每次写单元格刷屏

excel.Visible = false;
excel.ScreenUpdating = false;

//...楼主中间写数据等

//最后可见,并刷新屏幕
excel.Visible = true;
excel.ScreenUpdating = true

//////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////

用ado.net应该比com快
http://support.microsoft.com/default.aspx?scid=kb;zh-cn;306023#

原创粉丝点击