• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#DataGridview用NPOI导出Excel文件

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

导出excel我用的是nuget 的NPOI,直接在项目中添加的,引用到项目中,下面是截图:

 

下面我把ExcelHelper贴出来

    public static class ExcelHelper
    {
        public static void ExportToExcel(DataTable dt)
        {
            ExportToExcelData(dt);
        }
    
public static DataTable ToDataTable(this DataGridView myDGV) { DataTable dt = new DataTable(); for (int i = 0; i < myDGV.ColumnCount; i++) { dt.Columns.Add(myDGV.Columns[i].HeaderText); } //写入数值 for (int r = 0; r < myDGV.Rows.Count; r++) { List<object> values = new List<object>(); for (int i = 0; i < myDGV.ColumnCount; i++) { values.Add(myDGV.Rows[r].Cells[i].Value); } dt.Rows.Add(values .ToArray()); } return dt; } #region 导出 /// <summary> /// 数据导出 /// </summary> /// <param name="data"></param> /// <param name="sheetName"></param> public static void ExportToExcelData(this DataTable data) { ExportToExcel(data, "Sheet1"); } /// <summary> /// 数据导出 /// </summary> /// <param name="data"></param> /// <param name="sheetName"></param> public static void ExportToExcel(this DataTable data, string sheetName) { SaveFileDialog fileDialog = new SaveFileDialog(); //fileDialog.Filter = "Excel(97-2003)|*.xls|Excel(2007-2013)|*.xlsx"; fileDialog.Filter = "Excel|*.xls|Excel|*.xlsx"; if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) { return; } IWorkbook workbook = new XSSFWorkbook(); ISheet sheet = workbook.CreateSheet(sheetName); IRow rowHead = sheet.CreateRow(0); //填写表头 for (int i = 0; i < data.Columns.Count; i++) { rowHead.CreateCell(i, CellType.String).SetCellValue(data.Columns[i].ColumnName.ToString()); } //填写内容 for (int i = 0; i < data.Rows.Count; i++) { IRow row = sheet.CreateRow(i + 1); for (int j = 0; j < data.Columns.Count; j++) { row.CreateCell(j, CellType.String).SetCellValue(data.Rows[i][j].ToString()); } } for (int i = 0; i < data.Columns.Count; i++) { sheet.AutoSizeColumn(i); } using (FileStream stream = File.OpenWrite(fileDialog.FileName)) { workbook.Write(stream); stream.Close(); } MessageBox.Show("导出数据成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); GC.Collect(); } #endregion #region 导入 /// <summary> /// 导入的文件名 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public static DataSet ExcelToDataSet(string fileName) { return ExcelToDataSet(fileName, true); } /// <summary> /// 返回dataset /// </summary> /// <param name="fileName"></param> /// <param name="firstRowAsHeader"></param> /// <returns></returns> public static DataSet ExcelToDataSet(string fileName, bool firstRowAsHeader) { int sheetCount = 0; return ExcelToDataSet(fileName, firstRowAsHeader, out sheetCount); } /// <summary> /// 返回dataset /// </summary> /// <param name="fileName">文件名</param> /// <param name="firstRowAsHeader">文件头</param> /// <param name="sheetCount">内容</param> /// <returns></returns> public static DataSet ExcelToDataSet(string fileName, bool firstRowAsHeader, out int sheetCount) { using (DataSet ds = new DataSet()) { using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { IWorkbook workbook = WorkbookFactory.Create(fileStream); IFormulaEvaluator evaluator = WorkbookFactory.CreateFormulaEvaluator(workbook); sheetCount = workbook.NumberOfSheets; for (int i = 0; i < sheetCount; ++i) { ISheet sheet = workbook.GetSheetAt(i); DataTable dt = ExcelToDataTable(sheet, evaluator, firstRowAsHeader); ds.Tables.Add(dt); } return ds; } } } /// <summary> /// 返回DataTable /// </summary> /// <param name="sheet"></param> /// <param name="evaluator"></param> /// <param name="firstRowAsHeader"></param> /// <returns></returns> private static DataTable ExcelToDataTable(ISheet sheet, IFormulaEvaluator evaluator, bool firstRowAsHeader) { if (firstRowAsHeader) { return ExcelToDataTableFirstRowAsHeader(sheet, evaluator); } else { return ExcelToDataTable(sheet, evaluator); } } private static DataTable ExcelToDataTableFirstRowAsHeader(ISheet sheet, IFormulaEvaluator evaluator) { try { using (DataTable dt = new DataTable()) { IRow firstRow = sheet.GetRow(0); int cellCount = GetCellCount(sheet); for (int i = 0; i < cellCount; i++) { if (firstRow.GetCell(i) != null) { dt.Columns.Add(firstRow.GetCell(i).StringCellValue ?? string.Format("F{0}", i + 1), typeof(string)); } else { dt.Columns.Add(string.Format("F{0}", i + 1), typeof(string)); } } for (int i = 1; i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); DataRow dr = dt.NewRow(); FillDataRowByRow(row, evaluator, ref dr); dt.Rows.Add(dr); } dt.TableName = sheet.SheetName; return dt; } } catch (Exception ex) { MessageBox.Show(ex.Message); return null; } } private static DataTable ExcelToDataTable(ISheet sheet, IFormulaEvaluator evaluator) { using (DataTable dt = new DataTable()) { if (sheet.LastRowNum != 0) { int cellCount = GetCellCount(sheet); for (int i = 0; i < cellCount; i++) { dt.Columns.Add(string.Format("F{0}", i), typeof(string)); } for (int i = 0; i < sheet.FirstRowNum; ++i) { DataRow dr = dt.NewRow(); dt.Rows.Add(dr); } for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); DataRow dr = dt.NewRow(); FillDataRowByRow(row, evaluator, ref dr); dt.Rows.Add(dr); } } dt.TableName = sheet.SheetName; return dt; } } /// <summary> /// 填充数据 /// </summary> /// <param name="row"></param> /// <param name="evaluator"></param> /// <param name="dr"></param> private static void FillDataRowByRow(IRow row, IFormulaEvaluator evaluator, ref DataRow dr) { if (row != null) { for (int j = 0; j < dr.Table.Columns.Count; j++) { ICell cell = row.GetCell(j); if (cell != null) { switch (cell.CellType) { case CellType.Blank: { dr[j] = DBNull.Value; break; } case CellType.Boolean: { dr[j] = cell.BooleanCellValue; break; } case CellType.Numeric: { if (DateUtil.IsCellDateFormatted(cell)) { dr[j] = cell.DateCellValue; } else { dr[j] = cell.NumericCellValue; } break; } case CellType.String: { dr[j] = cell.StringCellValue; break; } case CellType.Error: { dr[j] = cell.ErrorCellValue; break; } case CellType.Formula: { cell = evaluator.EvaluateInCell(cell) as HSSFCell; dr[j] = cell.ToString(); break; } default: throw new NotSupportedException(string.Format("Unsupported format type:{0}", cell.CellType)); } } } } } /// <summary> /// 获取单元格 /// </summary> /// <param name="sheet"></param> /// <returns></returns> private static int GetCellCount(ISheet sheet) { int firstRowNum = sheet.FirstRowNum; int cellCount = 0; for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; ++i) { IRow row = sheet.GetRow(i); if (row != null && row.LastCellNum > cellCount) { cellCount = row.LastCellNum; } } return cellCount; } #endregion }

如果DataGridview的数据源有多余的列,我们可以用扩展方法,把dataGridView转成DataTable,ExcelHelper中有,但是我拿出来,需要自己注意下。

     
        /// <summary>
        /// DataGridView转DataTable的扩展方法
        /// </summary>
        /// <param name="myDGV"></param>
        /// <returns></returns>
        public static DataTable ToDataTable(this DataGridView myDGV)
        {
            DataTable dt = new DataTable();
            for (int i = 0; i < myDGV.ColumnCount; i++)
            {
                dt.Columns.Add(myDGV.Columns[i].HeaderText);
            }
            //写入数值
            for (int r = 0; r < myDGV.Rows.Count; r++)
            {
                List<object> values = new List<object>();
                for (int i = 0; i < myDGV.ColumnCount; i++)
                {
                    values.Add(myDGV.Rows[r].Cells[i].Value);
                }
                dt.Rows.Add(values .ToArray());
            }
            return dt;
        }
        #endregion

导出按钮事件,可以直接写:

   if (dgBoxInData.Rows.Count > 0)
                {
                    ExcelHelper.ExportToExcel(dgBoxInData.ToDataTable());//Run
                }

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
ASP.net(C#)批量上传图片(完整版)发布时间:2022-07-13
下一篇:
C#封装一个钩子类发布时间:2022-07-13
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap