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.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 ;
这段博客内容主要展示了在WinForm环境下,将数据导出到Excel的代码实现。通过创建Excel应用程序对象,添加工作簿,将数据逐行逐列写入Excel单元格,最后设置单元格的对齐方式并使Excel可见。
1万+





