EPPlusToExcel.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using OfficeOpenXml;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Windows.Forms;
  9. namespace PTMedicalInsurance.Common
  10. {
  11. internal class EPPlusToExcel
  12. {
  13. public static string ExportDataGridViewToExcel(DataGridView dgv, string filePath)
  14. {
  15. using (var package = new ExcelPackage())
  16. {
  17. // 添加一个sheet
  18. var worksheet = package.Workbook.Worksheets.Add("Sheet1");
  19. // 将DataGridView列标题导出到Excel
  20. for (int i = 0; i < dgv.Columns.Count; i++)
  21. {
  22. worksheet.Cells[1, i + 1].Value = dgv.Columns[i].HeaderText;
  23. worksheet.Cells[1, i + 1].Style.Font.Bold = true;
  24. }
  25. // 将DataGridView数据导出到Excel
  26. for (int row = 0; row < dgv.RowCount; row++)
  27. {
  28. for (int col = 0; col < dgv.ColumnCount; col++)
  29. {
  30. worksheet.Cells[row + 2, col + 1].Value = dgv[col, row].Value;
  31. }
  32. //// 添加进度条更新(可选)
  33. //UpdateProgress(row, dgv.RowCount);
  34. }
  35. // 调整列宽以适应内容(可选)
  36. for (int col = 0; col < dgv.ColumnCount; col++)
  37. {
  38. worksheet.Column(col + 1).AutoFit();
  39. }
  40. FileInfo fileInfo = new FileInfo(filePath);
  41. package.SaveAs(fileInfo);
  42. MessageBox.Show("导出成功!!!路径为:" + filePath);
  43. }
  44. return filePath;
  45. }
  46. // 更新进度条的函数(可选)
  47. private void UpdateProgress(int current, int total)
  48. {
  49. int percentage = (int)(((double)current / (double)total) * 100);
  50. // 更新UI线程中的进度条
  51. }
  52. }
  53. }