C#将DataGridView中的数据导出为EXCEL
2011-05-02 09:55 jiangys 阅读(1171) 评论(0) 编辑 收藏 举报添加引用Microsoft Office Excel:
1using Excel = Microsoft.Office.Interop.Excel;
方法 1#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 /// <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
1 private void btnExcel_Click(object sender,EventArgs e)
{
if (!oper.ExportDataGridview(dgvEquiment, true))
2 MessageBox.Show("表格中没有数据,无法导出数据!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}