参考:https://blog.csdn.net/lanshengsheng2012/article/details/11479183 (提供的源码中类NPOIExcelHelper稍加修改即可使用)
HSSFWorkbook workbook = new HSSFWorkbook(); //创建工作簿
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(); //创建表单
HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0); //创建row
headerRow.HeightInPoints = 53; //设置行高
headerRow.CreateCell(0).SetCellValue("demo"); //设置指定单元格-cell 的内容
设置格式:
HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle(); //定义一个style
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //水平居中
headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; //垂直居中
headStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; //边框
headStyle.WrapText = true; //自动换行
sheet.AddMergedRegion(new Region(0, 0, 0, 21)); //合并单元格 起始行,起始列,目的行,目的列
headerRow.GetCell(0).CellStyle = headStyle; //设置某个cell应用style
对角线:
style0.BorderDiagonalLineStyle = NPOI.SS.UserModel.BorderStyle.Dashed;
style0.BorderDiagonal = NPOI.SS.UserModel.BorderDiagonal.Backward;
字体设置:
HSSFFont font = (HSSFFont)workbook.CreateFont(); //创建字体样式
font.Boldweight = 700;
font.FontName = "宋体";
font.FontHeightInPoints = 20; //字体大小
headStyle.SetFont(font); //应用样式
追加数据到现有excel:
FileStream fs = new FileStream("e:/zaocao.xls", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);//读取流
POIFSFileSystem ps = new POIFSFileSystem(fs);//需using NPOI.POIFS.FileSystem;
IWorkbook workbook = new HSSFWorkbook(ps);
ISheet sheet = workbook.GetSheetAt(0);//获取工作表
IRow row = sheet.GetRow(0); //得到表头
FileStream fout = new FileStream("e:/zaocao.xls", FileMode.Open, FileAccess.Write, FileShare.ReadWrite);//写入流
row = sheet.CreateRow((sheet.LastRowNum + 1));//在工作表中添加一行
ICell cell1 = row.CreateCell(0);
cell1.SetCellValue("测试数据");//赋值
fout.Flush();
workbook.Write(fout);//写入文件
workbook = null;
fout.Close();