标签:
在.net中导出数据到Excel其中使用的比较多的是NPOI类库,但是NPOI版本存在比较多,并且改变较大,官方提供的代码不太完备,所以在这里简单记录一下。
一、使用的类库包:
using NPOI.SS.UserModel; using NPOI.HSSF.UserModel;
HSSFWorkbook hssfworkbook = new HSSFWorkbook(); ISheet sheet = hssfworkbook.CreateSheet("Sheet1"); hssfworkbook.CreateSheet("Sheet2"); hssfworkbook.CreateSheet("Sheet3");三、使用CreateRow()创建行对象,CreateCell()创建单元格对象,再通过SetCellValue()设置单元格的内容。
下面的是一个简单的例子,设置工作表的标题字体,并且合并第一行,前5列
//Title IRow row = sheet.CreateRow(0); //创建行对象 ICell cell = row.CreateCell(0); //创建单元格对象 cell.SetCellValue(title); //设置单元格内容 // 设置单元格字体 ICellStyle style = hssfworkbook.CreateCellStyle(); style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; IFont font = hssfworkbook.CreateFont(); font.FontHeight = 20 * 20; style.SetFont(font); cell.CellStyle = style; // 合并第0列到第4列的内容 sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0,0,0,4));四、把WorkBook对象的内容写入到文件
FileStream</span> file = new FileStream(filePath, FileMode.Create); hssfworkbook.Write(file); file.Close();
/// <summary> /// 把DataGridView的内容导出到excel文件 /// </summary> /// <param name="dgv">DataGridView对象</param> /// <param name="title">设置的标题</param> /// <param name="filePath">保存的文件路径</param> /// <returns></returns> public static int SaveToExcel(DataGridView dgv, string title, string filePath) { if (dgv==null ||(dgv.Rows.Count == 0 && dgv.Columns.Count == 0)) return 1; HSSFWorkbook hssfworkbook = new HSSFWorkbook(); ISheet sheet = hssfworkbook.CreateSheet("Sheet1"); hssfworkbook.CreateSheet("Sheet2"); hssfworkbook.CreateSheet("Sheet3"); //Title IRow row = sheet.CreateRow(0); ICell cell = row.CreateCell(0); cell.SetCellValue(title); ICellStyle style = hssfworkbook.CreateCellStyle(); style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; IFont font = hssfworkbook.CreateFont(); font.FontHeight = 20 * 20; style.SetFont(font); cell.CellStyle = style; sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0,0,0,dgv.Columns.Count-1)); //Header int r, c; row = sheet.CreateRow(1); for (c = 0; c < dgv.Columns.Count; c++) { row.CreateCell(c).SetCellValue(dgv.Columns[c].HeaderText); } // content for (r = 0; r < dgv.Rows.Count; r++) { row = sheet.CreateRow(r+2); for (c = 0; c < dgv.Columns.Count; c++) { cell = row.CreateCell(c); if (dgv[c,r].Value !=null) cell.SetCellValue(dgv[c,r].Value.ToString()); } } r = 0; FileStream file=null; try { file = new FileStream(filePath, FileMode.Create); hssfworkbook.Write(file); } catch (Exception ex) { MessageBox.Show(ex.Message); r = 1; } finally { if (file !=null) file.Close(); } return r; }
标签:
原文地址:http://blog.csdn.net/yao_guet/article/details/45277687