public class execl { /// <summary> /// 导出EXECLDataGridViewX /// </summary> /// <param name="dataGridView">DataGridViewX</param> /// <param name="IsVisible">是否导出隐藏列</param> public static void exp(DataGridView dataGridView,bool IsVisible=false) { try { if (dataGridView.RowCount<=0) { throw new Exception("未有导出数据!!!"); } SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "2007电子表格|*.xlsx"; if (saveFileDialog.ShowDialog()== DialogResult.Cancel) { return; } string file = saveFileDialog.FileName; XSSFWorkbook workbook2007 = new XSSFWorkbook(); //新建xlsx工作簿 workbook2007.CreateSheet("Sheet1"); XSSFSheet SheetOne = (XSSFSheet)workbook2007.GetSheet("Sheet1"); //首行标题 // SheetOne.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 18)); #region 样式1 ///样试 ICellStyle style = workbook2007.CreateCellStyle(); //设置单元格的样式:水平对齐居中 style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //设置垂直剧中 style.VerticalAlignment = VerticalAlignment.Center; //边框颜色 style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; //style.FillPattern = FillPattern.SolidForeground; //自动换行 // style.WrapText = true; #endregion #region 样式2 ///样试 ICellStyle style2 = workbook2007.CreateCellStyle(); //设置单元格的样式:水平对齐居中 style2.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //设置垂直剧中 style2.VerticalAlignment = VerticalAlignment.Center; //边框颜色 style2.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; style2.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; style2.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; style2.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; //style.FillPattern = FillPattern.SolidForeground; //自动换行 //style2.WrapText = true; style2.FillForegroundColor = HSSFColor.Red.Index; style2.FillPattern = FillPattern.SolidForeground; #endregion int i = 0; //行号 XSSFRow row = (XSSFRow)SheetOne.CreateRow(i); int c = 0; //列号 ICell cell; //写入列 foreach (DataGridViewColumn eo in dataGridView.Columns) { if (IsVisible) { if (!eo.Visible) { continue; } } cell = row.CreateCell(c); cell.SetCellValue(eo.HeaderText); cell.CellStyle = style; c++; } i++; foreach (DataGridViewRow ei in dataGridView.Rows) { row= (XSSFRow)SheetOne.CreateRow(i); c = 0; foreach (DataGridViewColumn eo in dataGridView.Columns) { if (IsVisible) { if (!eo.Visible) { continue; } } cell = row.CreateCell(c); cell.SetCellValue(ei.Cells[eo.Name].Value.ToString()); if (ei.DefaultCellStyle.BackColor.Name == "Red") { cell.CellStyle = style2; } else { cell.CellStyle = style; } c++; } i++; } FileStream file2007 = new FileStream(file, FileMode.Create); workbook2007.Write(file2007); file2007.Close(); workbook2007.Close(); MessageBox.Show ("导出成功"); } catch (Exception ex ) { throw ex ; } } } }
标签:execl,EXCEL,导出,dataGridView,DataGridView,public From: https://www.cnblogs.com/kangjin/p/17772374.html