添加引用Microsoft Office Excel:
1
using
Excel
=
Microsoft.Office.Interop.Excel;
方法

1
将DataGridView控件中数据导出到Excel
#region 将DataGridView控件中数据导出到Excel
2
/**//// <summary>
3
/// 将DataGridView控件中数据导出到Excel
4
/// </summary>
5
/// <param name="gridView">DataGridView对象</param>
6
/// <param name="isShowExcle">是否显示Excel界面</param>
7
/// <returns></returns>
8
public bool ExportDataGridview(DataGridView gridView,bool isShowExcle)
9
{
10
if (gridView.Rows.Count == 0)
11
return false;
12
//建立Excel对象
13
Excel.Application excel = new Excel.Application();
14
excel.Application.Workbooks.Add(true);
15
excel.Visible = isShowExcle;
16
//生成字段名称
17
for (int i = 0; i < gridView.ColumnCount; i++)
18
{
19
excel.Cells[1, i + 1] = gridView.Columns[i].HeaderText;
20
}
21
//填充数据
22
for (int i = 0; i < gridView.RowCount-1; i++)
23
{
24
for (int j = 0; j < gridView.ColumnCount; j++)
25
{
26
if (gridView[j, i].ValueType == typeof(string))
27
{
28
excel.Cells[i + 2, j + 1] = "'" + gridView[j, i].Value.ToString();
29
}
30
else
31
{
32
excel.Cells[i + 2, j + 1] = gridView[j, i].Value.ToString();
33
}
34
}
35
}
36
return true;
37
}
38
#endregion
调用


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

1
if
(
!
oper.ExportDataGridview(dgvEquiment,
true
))
2
MessageBox.Show(
"
表格中没有数据,无法导出数据!
"
,
"
系统提示
"
, MessageBoxButtons.OK, MessageBoxIcon.Information);

2
