using Excel = Microsoft.Office.Interop.Excel;//添加 Microsoft.Office.Interop.Excel.dll 引用
class ExcelManager
{
public delegate void ProgressBarEventHandler(int max, int value);//导出进度条所需最大值与进度值
public event ProgressBarEventHandler ProgressBarEvent;
public delegate void ProgressBarOKEventHandler(int sum);//导出记录行数
public event ProgressBarOKEventHandler ProgressBarOKEvent;
public void ExportToExcel(System.Data.DataTable dt,string fileName)
{
if (dt == null || dt.Rows.Count == 0) return;
Excel.Application xlApp = new Excel.Application();
if (xlApp == null)
{
return;
}
Excel.Workbook book = xlApp.Workbooks.Add(true);
Excel.Worksheet sheet = (Excel.Worksheet)book.Worksheets[1];
Excel.Range range1 = null;
Excel.Range range2 = null;
Excel.Range range3 = null;
int rowsCount = dt.Rows.Count;
int columnsCount=dt.Columns.Count;
object[] arrHeader=new object[columnsCount];
for (int i = 0; i < columnsCount; i++)
{
arrHeader[i] = dt.Columns[i].ColumnName;
}
range1 = sheet.Range[sheet.Cells[1, 1], sheet.Cells[1, columnsCount]];
range1.Value2 = arrHeader;
range1.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
range1.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
range1.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
range1.Interior.ColorIndex = 15;
range1.Font.Bold = true;
object[,] arrBody = new object[rowsCount, columnsCount];
for (int i = 0; i < rowsCount; i++)
{
for (int j = 0; j < columnsCount; j++)
{
arrBody[i, j] = dt.Rows[i][j].ToString();
}
if (ProgressBarEvent != null) ProgressBarEvent(rowsCount,i+1);
}
range2 = sheet.Range[sheet.Cells[2, 1], sheet.Cells[rowsCount+1, columnsCount]];
range2.Value2 = arrBody;
range2.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
range2.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
range2.Borders.LineStyle = Excel.XlLineStyle.xlContinuous;
range3 = sheet.Range[sheet.Cells[1, 3], sheet.Cells[rowsCount + 1, 3]];
range3.NumberFormat = @"yyyy/MM/dd HH:mm:ss";
book.SaveAs(fileName);
//xlApp.Visible = true;
book.Close();
xlApp.Quit();
GC.Collect();
if (ProgressBarOKEvent != null) ProgressBarOKEvent(rowsCount);
}
}