将DataTable中的数据导出到Excel(支持Excel2003和Excel2007)
/// <summary> |
02 |
/// 将DataTable中的数据导出到Excel(支持Excel2003和Excel2007) |
03 |
/// </summary> |
04 |
/// <param name="dt"> DataTable</param> |
05 |
/// <param name="url">Excel保存的路径DataTable</param> |
06 |
/// <returns>导出成功返回True,否则返回false</ returns > |
07 |
Public bool ExportExcel(DataTable dt,string url) |
08 |
{ |
09 |
bool falge=false; |
10 |
Microsoft.Office.Interop.Excel.Application objExcel=null; |
11 |
Workbook objWorkbook=null; |
12 |
Worksheet objsheet=null; |
13 |
try |
14 |
{ |
15 |
//申明对象 |
16 |
objExcel=new Microsoft.Office.Interop.Excel.Application(); |
17 |
objWorkbook= objExcel.Workbook.Add(Missing.Value); |
18 |
objsheet= (Worksheet)objWorkbook.ActiveSheet; |
19 |
20 |
//设置Excel不可见 |
21 |
objExcel.visible=false; |
22 |
objExcel.DisplayAlerts=false; |
23 |
24 |
//设置Excel字段类型全部为字符串 |
25 |
Objsheet.Cells.NumberFormat=”@”; |
26 |
27 |
//向Excel中写入表格的标头 |
28 |
int displayColumnsCount=1; |
29 |
for(int i=0;i<dt.Columns.Count;i++) |
30 |
{ |
31 |
objExcel.Cells[1, displayColumnsCount]=dt.Colums[i].ColumnsName.Trim(); |
32 |
displayColumnsCount++; |
33 |
} |
34 |
//向Excel中逐行逐列写入表格中的数据 |
35 |
for(int row=0;row<dt.Rows.Count;row++) |
36 |
{ |
37 |
displayColumnsCount=1; |
38 |
for(int col=0;col< dt.Columns.Count;col++) |
39 |
{ |
40 |
Try |
41 |
{ |
42 |
objExcel.Cells[row+2,displayColumnsCount]=dt.Rows[row][col].ToString().Trim(); |
43 |
displayColumnsCount++; |
44 |
} |
45 |
Catch(Exception) |
46 |
{} |
47 |
} |
48 |
} |
49 |
//保存文件 |
50 |
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); |
51 |
flag=true; |
52 |
} |
53 |
Catch(Exceptioin ex) |
54 |
{ |
55 |
flag=false; |
56 |
MessageBox.Show(ex.Message,”温馨提示”,MessageBoxButtons.OK,MessageBoxIcon.Informaion); |
57 |
} |
58 |
Finally |
59 |
{ |
60 |
//关闭Excel应用 |
61 |
If(objWorkbook!=null)objWorkbook.Close(Missing.Value, Missing.Value, Missing.Value); |
62 |
If(objExcel.Workbooks!=null)objExcel.Workbooks.Close(); |
63 |
If(objExcel!=null)objExcel.Quit(); |
64 |
65 |
//杀死进程 |
66 |
KillProcess(“Excel”); |
67 |
objsheet=null; |
68 |
objWorkbook=null; |
69 |
objExcel=null; |
70 |
} |
71 |
return flag; |
72 |
} |
73 |
74 |
75 |
/// <summary> |
76 |
/// 根据进程名称杀死进程 |
77 |
/// </summary> |
78 |
/// <param name=" ProcessName "> DataTable</param> |
79 |
Public void KillProcess(string ProcessName) |
80 |
{ |
81 |
System.Diagnostics.Process myproc=new System.Diagnostics.Process(); |
82 |
Try |
83 |
{ |
84 |
Foreach(System.Diagnostics.Process thisproc in System.Diagnostics.Process.GetProcessByName(ProcessName)) |
85 |
{ |
86 |
If(!thisproc.CloseMainWindow()) |
87 |
{ |
88 |
thisproc.Kill(); |
89 |
} |
90 |
} |
91 |
} |
92 |
catch(Exception ex) |
93 |
{ |
94 |
Throw new Exception(“”,ex); |
95 |
} |
浙公网安备 33010602011771号