datatable 导出
/// <summary>
/// 将DataTable中的数据导出到Excel(支持Excel2003和Excel2007)
/// </summary>
/// <param name="dt"> DataTable</param>
/// <param name="url">Excel保存的路径DataTable</param>
/// <returns>导出成功返回True,否则返回false</ returns >
Public bool ExportExcel(DataTable dt,string url)
{
bool falge=false;
Microsoft.Office.Interop.Excel.Application objExcel=null;
Workbook objWorkbook=null;
Worksheet objsheet=null;
try
{
//申明对象
objExcel=new Microsoft.Office.Interop.Excel.Application();
objWorkbook= objExcel.Workbook.Add(Missing.Value);
objsheet= (Worksheet)objWorkbook.ActiveSheet;
//设置Excel不可见
objExcel.visible=false;
objExcel.DisplayAlerts=false;
//设置Excel字段类型全部为字符串
Objsheet.Cells.NumberFormat=”@”;
//向Excel中写入表格的标头
int displayColumnsCount=1;
for(int i=0;i<dt.Columns.Count;i++)
{
objExcel.Cells[1, displayColumnsCount]=dt.Colums[i].ColumnsName.Trim();
displayColumnsCount++;
}
//向Excel中逐行逐列写入表格中的数据
for(int row=0;row<dt.Rows.Count;row++)
{
displayColumnsCount=1;
for(int col=0;col< dt.Columns.Count;col++)
{
Try
{
objExcel.Cells[row+2,displayColumnsCount]=dt.Rows[row][col].ToString().Trim();
displayColumnsCount++;
}
Catch(Exception)
{}
}
}
//保存文件
objWorkbook.SaveAs(url, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSavaAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
flag=true;
}
Catch(Exceptioin ex)
{
flag=false;
MessageBox.Show(ex.Message,”温馨提示”,MessageBoxButtons.OK,MessageBoxIcon.Informaion);
}
Finally
{
//关闭Excel应用
If(objWorkbook!=null)objWorkbook.Close(Missing.Value, Missing.Value, Missing.Value);
If(objExcel.Workbooks!=null)objExcel.Workbooks.Close();
If(objExcel!=null)objExcel.Quit();
//杀死进程
KillProcess(“Excel”);
objsheet=null;
objWorkbook=null;
objExcel=null;
}
return flag;
}
/// <summary>
/// 根据进程名称杀死进程
/// </summary>
/// <param name=" ProcessName "> DataTable</param>
Public void KillProcess(string ProcessName)
{
System.Diagnostics.Process myproc=new System.Diagnostics.Process();
Try
{
Foreach(System.Diagnostics.Process thisproc in System.Diagnostics.Process.GetProcessByName(ProcessName))
{
If(!thisproc.CloseMainWindow())
{
thisproc.Kill();
}
}
}
catch(Exception ex)
{
Throw new Exception(“”,ex);
}