| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- using OfficeOpenXml;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace PTMedicalInsurance.Common
- {
- internal class EPPlusToExcel
- {
-
- public static string ExportDataGridViewToExcel(DataGridView dgv, string filePath)
- {
- using (var package = new ExcelPackage())
- {
- // 添加一个sheet
- var worksheet = package.Workbook.Worksheets.Add("Sheet1");
- // 将DataGridView列标题导出到Excel
- for (int i = 0; i < dgv.Columns.Count; i++)
- {
- worksheet.Cells[1, i + 1].Value = dgv.Columns[i].HeaderText;
- worksheet.Cells[1, i + 1].Style.Font.Bold = true;
- }
- // 将DataGridView数据导出到Excel
- for (int row = 0; row < dgv.RowCount; row++)
- {
- for (int col = 0; col < dgv.ColumnCount; col++)
- {
- worksheet.Cells[row + 2, col + 1].Value = dgv[col, row].Value;
- }
- //// 添加进度条更新(可选)
- //UpdateProgress(row, dgv.RowCount);
- }
- // 调整列宽以适应内容(可选)
- for (int col = 0; col < dgv.ColumnCount; col++)
- {
- worksheet.Column(col + 1).AutoFit();
- }
- FileInfo fileInfo = new FileInfo(filePath);
- package.SaveAs(fileInfo);
- MessageBox.Show("导出成功!!!路径为:" + filePath);
- }
- return filePath;
- }
- // 更新进度条的函数(可选)
- private void UpdateProgress(int current, int total)
- {
- int percentage = (int)(((double)current / (double)total) * 100);
- // 更新UI线程中的进度条
- }
- }
- }
|