经过对Excel深入了解,采用数据写入到range的方法,效率更高,更明显;与常用的逐单元格写有所不同,可查看[C#]WinForm中DataGrid扩展 - 导出Excel文件 (1)
本例的实现方式以[C#]WinForm中DataGrid扩展 - 导出Excel文件 (1)相似。
1
public
bool
ExportExcel(
string
p_ReportName)
2
{
3
if ( this.TableStyles.Count == 0 ) return false;
4
DataGridTableStyle ts = this.TableStyles[0];
5
6
// 创建Excel对象 --LeeWenjie 2006-11-29
7
Excel.Application xlApp = new Excel.ApplicationClass();
8
if ( xlApp == null )
9
{
10
MessageBox.Show("Excel无法启动");
11
return false;
12
}
13
// 创建Excel工作薄
14
Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
15
Excel.Worksheet xlSheet = (Excel.Worksheet)xlBook.Worksheets[1];
16
17
// 设置标题
18
Excel.Range range = xlSheet.get_Range(xlApp.Cells[1,1],xlApp.Cells[1,ts.GridColumnStyles.Count]);
19
range.MergeCells = true;
20
xlApp.ActiveCell.FormulaR1C1 = p_ReportName;
21
xlApp.ActiveCell.Font.Size = 20;
22
xlApp.ActiveCell.Font.Bold = true;
23
xlApp.ActiveCell.HorizontalAlignment = Excel.Constants.xlCenter;
24
25
// 列索引,行索引,总列数,总行数
26
int colIndex = 0;
27
int RowIndex = 0;
28
int colCount = ts.GridColumnStyles.Count;
29
int RowCount = this.BindingContext[this.DataSource,this.DataMember].Count;
30
31
// 创建缓存数据
32
object[,] objData = new object[RowCount + 1, colCount ];
33
// 获取列标题
34
foreach(DataGridColumnStyle cs in ts.GridColumnStyles)
35
{
36
objData[RowIndex,colIndex++] = cs.HeaderText;
37
}
38
// 获取数据
39
for(RowIndex =1;RowIndex< RowCount;RowIndex++)
40
{
41
for(colIndex=0;colIndex < colCount;colIndex++)
42
{
43
objData[RowIndex,colIndex] = this[RowIndex-1,colIndex];
44
}
45
Application.DoEvents();
46
}
47
// 写入Excel
48
range = xlSheet.get_Range(xlApp.Cells[2,1],xlApp.Cells[RowCount,colCount]);
49
range.Value2 = objData;
50
51
// 保存
52
try
53
{
54
xlBook.Saved = true;
55
xlBook.SaveCopyAs("D://Fly" + DateTime.Now.ToString("yyyyMMdd") + ".xls");
56
}
57
catch
58
{
59
MessageBox.Show("保存出错,请检查!");
60
return false;
61
}
62
finally
63
{
64
xlApp.Quit();
65
GC.Collect();
66
}
67
return true;
68
}

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

开发环境:
VS.Net 2003
改进后,效率提高N倍,8000条数据大约需要2秒。
**************************************