添加引用Microsoft Office Excel: 1using Excel = Microsoft.Office.Interop.Excel;方法
1将DataGridView控件中数据导出到Excel#region 将DataGridView控件中数据导出到Excel
2 /**
3 /// 将DataGridView控件中数据导出到Excel
4 ///
5 /// DataGridView对象
6 /// 是否显示Excel界面
7 ///
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调用 1if (!oper.ExportDataGridview(dgvEquiment, true))
2 MessageBox.Show("表格中没有数据,无法导出数据!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);