public void ExportDataGridViewToExcel(string fileName, DataGridView dgv) { try { if (dgv.Rows.Count > 0) { string saveFileName = ""; //bool fileSaved = false; SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.DefaultExt = "xls"; saveDialog.Filter = "Excel文件|*.xls"; saveDialog.FileName = fileName; if (saveDialog.ShowDialog() == DialogResult.OK) //点击确定 { saveFileName = saveDialog.FileName; Workbook wb = new Workbook(Aspose.Cells.FileFormatType.Xlsx); try { Worksheet sheet = wb.Worksheets[0]; //写入标题 int headindex = 0; for (int i = 0; i < dgv.ColumnCount; i++) { if (dgv.Columns[i].Visible) { sheet.Cells[0, headindex].PutValue(dgv.Columns[i].HeaderText); headindex++; } } //写入数据 for (int r = 0; r < dgv.Rows.Count; r++) { int rowindex = 0; for (int i = 0; i < dgv.ColumnCount; i++) { if (dgv.Columns[i].Visible) { sheet.Cells[r + 1, rowindex].PutValue(dgv.Rows[r].Cells[i].Value == null ? "" : dgv.Rows[r].Cells[i].Value.ToString(), true); if (dgv.Columns[i].HeaderText.Contains("数量")) { sheet.Cells[r + 1, rowindex].PutValue(dgv.Rows[r].Cells[i].Value == null ? "" : dgv.Rows[r].Cells[i].Value.ToString(), true); //Style style = sheet.Cells[r + 1, rowindex].GetStyle(); //style.Number = 1; //sheet.Cells[r + 1, rowindex].SetStyle(style); } else { sheet.Cells[r + 1, rowindex].PutValue(dgv.Rows[r].Cells[i].FormattedValue); } rowindex++; } } System.Windows.Forms.Application.DoEvents(); } sheet.AutoFitColumns();//列宽自适应 wb.Save(saveFileName); GC.Collect();//强行销毁 //给个提示框 } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { GC.Collect();//强行销毁 return; } } else { MessageBox.Show("报表为空,无表格需要导出", "提示", MessageBoxButtons.OK); } } catch (Exception) { MessageBox.Show("导出错误!", "提示", MessageBoxButtons.OK); } }
winform 导出Excel