winForm将DataGridView导出到Excel用EPPLUS4.5.3.3(高版本要声明非商业用途)

 public static bool DataGridViewToExcel(DataGridView dgv, string fileName)
        {
            bool b = false;
            try
            {
                if (dgv == null || dgv.RowCount == 0)
                {
                    return b;
                }
                var excel = new ExcelPackage();
                var workSheet = excel.Workbook.Worksheets.Add("Sheet1");
                //添加标题
                for (int i = 0; i < dgv.ColumnCount; i++)
                {
                    workSheet.Cells[1, i + 1].Value = dgv.Columns[i].HeaderText;
                    workSheet.Cells[1, i + 1].Style.Font.Bold = true;
                }
                //添加数据
                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;
                    }
                }
                //调整列宽自适应
                workSheet.Cells[1, 1, dgv.RowCount + 1, dgv.ColumnCount].AutoFitColumns();
                excel.SaveAs(new System.IO.FileInfo(fileName));
                b = true;
            }
            catch (Exception ex)
            {
                string resStr = ex.Message;
            }
            return b;
        }

 

posted @ 2026-06-11 19:04  techNote  阅读(6)  评论(0)    收藏  举报