1
using System;
2
using System.IO;
3
using System.Data;
4
using System.Web;
5
using System.Text;
6
using System.Globalization;
7
using System.Collections;
8
using System.Windows.Forms;
9
using Microsoft.CSharp;
10
11
namespace Com.Elong.BusinessService.Domain.CommissionAccount
12
{
13
public class ExcelHelper
14
{
15
public static void ExportToExcel(string filePath, DataSet ds)
16
{
17
object oMissing = System.Reflection.Missing.Value;
18
Excel.ApplicationClass xlApp = new Excel.ApplicationClass();
19
try
20
{
21
// 打开Excel文件。以下为Office 2000.
22
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filePath, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
23
Excel.Worksheet xlWorksheet;
24
// 循环所有DataTable
25
for( int i=0; i<ds.Tables.Count; i++ )
26
{
27
// 添加入一个新的Sheet页。
28
xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.Add(oMissing,oMissing,1,oMissing);
29
// 以TableName作为新加的Sheet页名。
30
xlWorksheet.Name = ds.Tables[i].TableName;
31
// 取出这个DataTable中的所有值,暂存于stringBuffer中。
32
string stringBuffer = "";
33
for( int j=0; j<ds.Tables[i].Rows.Count; j++ )
34
{
35
for( int k=0; k<ds.Tables[i].Columns.Count; k++ )
36
{
37
38
stringBuffer += ds.Tables[i].Rows[j][k].ToString();
39
if( k < ds.Tables[i].Columns.Count - 1 )
40
stringBuffer += "\t";
41
}
42
stringBuffer += "\n";
43
}
44
// 利用系统剪切板
45
System.Windows.Forms.Clipboard.SetDataObject("");
46
// 将stringBuffer放入剪切板。
47
System.Windows.Forms.Clipboard.SetDataObject(stringBuffer);
48
// 选中这个sheet页中的第一个单元格
49
((Excel.Range)xlWorksheet.Cells[1,1]).Select();
50
// 粘贴!
51
xlWorksheet.Paste(oMissing,oMissing);
52
// 清空系统剪切板。
53
System.Windows.Forms.Clipboard.SetDataObject("");
54
}
55
// 保存并关闭这个工作簿。
56
xlWorkbook.Close( Excel.XlSaveAction.xlSaveChanges, oMissing, oMissing );
57
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkbook);
58
xlWorkbook = null;
59
}
60
catch(Exception ex)
61
{
62
MessageBox.Show(ex.Message);
63
}
64
finally
65
{
66
// 释放
67
xlApp.Quit();
68
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
69
xlApp = null;
70
GC.Collect();
71
}
72
}
73
}
74
}
75
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75