private static Boolean ExpordExcel(DataTable dt, string filePath, string ReportTitle, bool isTitle)
{
writelog("ExpordExcel 导出资料" );
if (dt == null || dt.Rows.Count <=0)
{
writelog("ExpordExcel 没有资料");
return false;
}
int eRowIndex = 1;
int eColIndex = 1;
int cols = dt.Columns.Count;
int rows = dt.Rows.Count;
Excel.Application xlApp = new Excel.ApplicationClass();
Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
Excel.Worksheet xlWorksheet;
//xlWorksheet = (Excel.Worksheet)xlBook.Worksheets.Add(Type.Missing, Type.Missing, 1, Type.Missing);//增加
xlWorksheet = (Excel.Worksheet)xlBook.Worksheets.get_Item(1);//取第一个Sheet
xlWorksheet.Name = ReportTitle;//表的名
try
{
//标题的处理
if (isTitle)
{
Excel.Range range = xlApp.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, cols]);
range.MergeCells = true;
xlApp.ActiveCell.FormulaR1C1 = ReportTitle;
xlApp.ActiveCell.Font.Size = 18;
xlApp.ActiveCell.Font.Bold = true;
xlApp.ActiveCell.VerticalAlignment = Excel.Constants.xlCenter;
xlApp.ActiveCell.HorizontalAlignment = Excel.Constants.xlCenter;
eRowIndex++;
}
//列名的处理
for (int i = 0; i < cols; i++)
{
xlApp.Cells[eRowIndex, eColIndex] = dt.Columns[i].ColumnName;
eColIndex++;
}
//列名加粗显示
xlApp.get_Range(xlApp.Cells[eRowIndex, 1], xlApp.Cells[eRowIndex, cols]).Font.Bold = true;
eRowIndex++;
for (int i = 0; i < rows; i++)
{
eColIndex = 1;
for (int j = 0; j < cols; j++)
{
xlApp.get_Range(xlApp.Cells[eRowIndex, eColIndex], xlApp.Cells[eRowIndex, eColIndex]).NumberFormatLocal = "@";//设置文本
xlApp.Cells[eRowIndex, eColIndex] = string.Format("{0}",dt.Rows[i][j].ToString());
eColIndex++;
}
eRowIndex++;
}
//控制单元格中的内容。
xlApp.Cells.EntireColumn.AutoFit();
xlApp.DisplayAlerts = false;
xlBook.SaveCopyAs(filePath);
xlApp.Workbooks.Close();
return true;
}
catch (Exception ex)
{
writelog(string.Format("ExpordExcel错误,{0}",ex.ToString()) ,true );
return false;
//throw;
}
finally
{
xlApp.Quit();
GC.Collect();
}
}