C#从datatable或dategridview导出到excel
1.datatable
DataTable dtqzh= Service.getTableBySql("select * from table where"); if (dtqzh != null && dtqzh.Rows.Count > 0) { this.outLoadExcel(dtqzh); } private void outLoadExcel(DataTable dtqzh) { if (dtqzh.Rows.Count <= 0) { MessageBox.Show("没有可供导出的数据"); return; } //创建Excel对象 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); excel.Application.Workbooks.Add(true); excel.Visible = true; //生成字段,即添加表头 for (int i = 0; i < dtqzh.Columns.Count; i++) { excel.Cells[1, i + 1] = dtqzh.Columns[i].ColumnName; } //填充内容 for (int i = 0; i < dtqzh.Rows.Count; i++) { for (int j = 0; j < dtqzh.Columns.Count; j++) { if (dtqzh.Rows[i][j] == null) { excel.Cells[i + 2, j + 1] = ""; } else { excel.Cells[i + 2, j + 1] = dtqzh.Rows[i][j].ToString(); } } } }
2.datagridview
private void outLoadExcel(DataGridView dgv) { if (dgv.Rows.Count <= 0) { MessageBox.Show("没有可供导出的数据"); return; } //创建Excel对象 Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); excel.Application.Workbooks.Add(true); excel.Visible = true; //生成字段,即添加表头 for (int i = 0; i < dgv.Columns.Count; i++) { excel.Cells[1, i + 1] = dgv.Columns[i].HeaderText; } //填充内容 for (int i = 0; i < dgv.Rows.Count; i++) { for (int j = 0; j < dgv.Columns.Count; j++) { if (dgv[j, i].Value==null) { excel.Cells[i + 2, j + 1] = ""; } else if (dgv[j,i].ValueType==typeof(string)) { excel.Cells[i + 2, j + 1] = "'" + dgv[j, i].Value.ToString(); } else { excel.Cells[i + 2, j + 1] = dgv[j, i].Value.ToString(); } } } }