java poi 类_Java操作Excel工具类(poi)

1 importorg.apache.commons.lang3.exception.ExceptionUtils;2 importorg.apache.poi.hssf.usermodel.HSSFDataFormat;3 importorg.apache.poi.hssf.usermodel.HSSFSheet;4 importorg.apache.poi.hssf.usermodel.HSSFWorkbook;5 importorg.apache.poi.hssf.util.CellReference;6 import org.apache.poi.ss.usermodel.*;7 importorg.apache.poi.ss.util.CellRangeAddress;8 importorg.apache.poi.ss.util.RegionUtil;9 importorg.apache.poi.xssf.usermodel.XSSFWorkbook;10 importjava.io.File;11 importjava.io.FileInputStream;12 importjava.io.FileOutputStream;13 importjava.io.IOException;14 importjava.util.List;15

16 public classExcelWriterUtil_Poi {17

18

19 //用于存放结果表内容的xlsx格式的工作簿

20 private XSSFWorkbook xssfWorkbook = null;21 //用于存放结果表内容的xls格式的工作簿

22 private HSSFWorkbook hssfWorkbook = null;23 //工作的sheet页

24 privateSheet sheet;25 //用于读取用例表内容复制到结果标的文件输出流

26 private FileOutputStream stream = null;27 //用于存储结果表的路径的成员变量,便于在保存结果时进行判断

28 private String path = null;29 //单元格格式

30 private CellStyle style = null;31 //表的总行数

32 public int rows = 0;33 private String sheetName="Sheet1";//初始化默认给一个sheet名字

34 private FileInputStream in =null;35 private String resultType=null;36

37 /**

38 * 获取当前操作sheet的名称39 *@return

40 */

41 publicString getSheetName() {42

43 returnsheetName;44 }45

46 /**

47 * 根据名字切换sheet进行操作 // 指定工作sheet48 *49 *@paramsheetName50 */

51 public voiduseSheet(String sheetName) {52

53 this.sheetName =sheetName;54 try{55 if (resultType.equals(".xlsx")) {56 sheet =xssfWorkbook.getSheet(getSheetName());57 if (sheet == null) {58 return;59 }60

61 } else if (resultType.equals(".xls")) {62 sheet =hssfWorkbook.getSheet(getSheetName());63 if (sheet == null) {64 return;65 }66 }67 rows =sheet.getPhysicalNumberOfRows();68

69 sheet.setForceFormulaRecalculation(true); //刷新公式

70

71 } catch(Exception e) {72 System.out.println(ExceptionUtils.getStackTrace(e));73 }74

75

76 }77

78 /**

79 * 修改当前sheet的名称80 *@paramsheetName81 */

82 public voidupdateSheetName(String sheetName){83 try{84 if (resultType.equals(".xlsx")) {85 sheet =xssfWorkbook.getSheet(getSheetName());86 if(sheet == null) {87 return;88 }89 int indexSheet =xssfWorkbook.getSheetIndex(sheet);90 xssfWorkbook.setSheetName(indexSheet,sheetName);91

92 }else if(resultType.equals(".xls")){93 sheet =hssfWorkbook.getSheet(getSheetName());94 if(sheet == null) {95 return;96 }97 int indexSheet =hssfWorkbook.getSheetIndex(sheet);98 hssfWorkbook.setSheetName(indexSheet,sheetName);99 }100 }catch(Exception e){101 System.out.println(ExceptionUtils.getStackTrace(e));102 }103 }104

105 /**

106 * 关闭文件输入流107 */

108 public voidcloseStream() {109 try{110 in.close();111 } catch(IOException e) {112 //TODO Auto-generated catch block

113 e.printStackTrace();114 }115 }116 /*

117 * 根据模板 path1,创建path2,将path1中的内容复制到path2中118 * @param path1模板表路径119 * path2新生表路径120 */

121 publicExcelWriterUtil_Poi(String path1, String path2) {122 //截取模板表后缀名

123 String Origintype = path1.substring(path1.lastIndexOf("."));124 //判断是xls还是xlsx格式,完成在内存中创建模板表的工作簿

125 XSSFWorkbook xssfWorkbookRead = null;126 HSSFWorkbook hssfWorkbookRead = null;127 if (Origintype.equals(".xlsx")) {128 try{129 xssfWorkbookRead = new XSSFWorkbook(newFile(path1));130 } catch(Exception e) {131 System.out.println(ExceptionUtils.getStackTrace(e));132 }133 }134 if (Origintype.equals(".xls")) {135 try{136 hssfWorkbookRead = new HSSFWorkbook(new FileInputStream(newFile(path1)));137 } catch(Exception e) {138 System.out.println(ExceptionUtils.getStackTrace(e));139 }140 }141 //如果两种格式均不符合,则文件打开失败

142 if (xssfWorkbookRead == null && hssfWorkbookRead == null) {143 System.out.println("Excel文件打开失败!");144 return;145 }146

147 //截取结果表后缀名

148 resultType = path2.substring(path2.lastIndexOf("."));149 //确定结果表格式为excel格式

150 if (resultType.equals(".xlsx") || resultType.equals(".xls")) {151 try{152 //根据新生表的文件名,为该文件在内存中开辟空间

153 File file = newFile(path2);154 try{155 //在磁盘上面创建该文件

156 file.createNewFile();157 } catch(Exception e1) {158 //创建失败,提示路径非法,并停止创建

159 System.out.println(ExceptionUtils.getStackTrace(e1));160 return;161 }162 //基于新生表,创建文件输出流stream

163 stream = newFileOutputStream(file);164 //将用例表中的内容写入文件输出流stream

165 if (hssfWorkbookRead != null) {166 hssfWorkbookRead.write(stream);167 //关闭用例表在内存中的副本

168 hssfWorkbookRead.close();169 } else{170 xssfWorkbookRead.write(stream);171 xssfWorkbookRead.close();172 }173 //关闭已经写入了用例表内容的文件流

174 stream.close();175 //基于新生表,创建文件输入流

176 in = newFileInputStream(file);177 //判断结果文件的后缀是03版还是07版excel

178 if (resultType.equals(".xlsx")) {179 try{180 //通过文件输入流,在内存中创建结果表的工作簿

181 xssfWorkbook = newXSSFWorkbook(in);182 System.out.println(getSheetName());183 sheet =xssfWorkbook.getSheet(getSheetName());184

185 } catch(Exception e) {186 System.out.println(ExceptionUtils.getStackTrace(e));187 }188 }189 if (resultType.equals(".xls")) {190 try{191 hssfWorkbook = newHSSFWorkbook(in);192 sheet =hssfWorkbook.getSheet(getSheetName());193 } catch(Exception e) {194 System.out.println(ExceptionUtils.getStackTrace(e));195 }196 }197 rows =sheet.getPhysicalNumberOfRows();198 //将成员变量结果文件路径赋值为path2,表示结果表已经成功创建。

199 path =path2;200

201 } catch(Exception e) {202 System.out.println( ExceptionUtils.getStackTrace(e));203 }204 } else{205 System.out.println("写入的文件格式错误!");206 }207 }208

209 /**

210 * 创建指定名称的sheet211 *@paramsheetName212 */

213 public voidcreateSheet(String sheetName){214 if(xssfWorkbook != null){215 sheet=xssfWorkbook.createSheet(sheetName);216 }else if(hssfWorkbook!=null){217 sheet=hssfWorkbook.createSheet(sheetName);218 }219 rows =sheet.getPhysicalNumberOfRows();220 }221

222

223

224 //设置样式为Excel中指定单元格的样式

225 public void setStyle(int rowNo, intcolumn) {226 Row row = null;227 Cell cell = null;228 try{229 style=xssfWorkbook.createCellStyle();230 style.setVerticalAlignment( VerticalAlignment.CENTER);231 style.setAlignment(HorizontalAlignment.CENTER);232

233 } catch(Exception e) {234 e.printStackTrace();235 }236 }237

238 /*

239 * 当用例执行结果失败时,使用该方法,以红色字体写入excel240 * @param r单元格行数241 * l单元格列数242 * value输入值243 * size字体大小244 * con是否加粗245 * fontStyle字体类型246 */

247 public void writeFailCell(int rowNo, int column, String value,int size,booleancon,String fontStyle) {248 if(fontStyle==null||"".equals(fontStyle)){249 fontStyle="宋体";250 }251 Row row = null;252 try{253 //获取指定行

254 row =sheet.getRow(rowNo);255 } catch(Exception e) {256 e.printStackTrace();257 }258 //行不存在,则创建

259 if (row == null) {260 row =sheet.createRow(rowNo);261 }262 //在该行,新建指定列的单元格

263 Cell cell =row.createCell(column);264 //设置单元格值

265 cell.setCellValue(value);266 //设置单元格样式

267 CellStyle failStyle = null;268 //新建字体样式

269 Font font = null;270 //根据不同的excel版本进行实例化

271 if (hssfWorkbook != null) {272 font =hssfWorkbook.createFont();273 failStyle =hssfWorkbook.createCellStyle();274 } else{275 font =xssfWorkbook.createFont();276 failStyle =xssfWorkbook.createCellStyle();277 }278 failStyle.setVerticalAlignment( VerticalAlignment.CENTER);279 failStyle.setAlignment(HorizontalAlignment.CENTER);280 failStyle.setBorderBottom(BorderStyle.THIN); //下边框

281 failStyle.setBorderLeft(BorderStyle.THIN);//左边框

282 failStyle.setBorderTop(BorderStyle.THIN);//上边框

283 failStyle.setBorderRight(BorderStyle.THIN);//右边框

284 font.setColor(IndexedColors.BLACK.index);//字体颜色

285 font.setBold(con);286 font.setFontName(fontStyle);287 font.setFontHeightInPoints((short) size);288 //将字体颜色作为单元格样式

289 failStyle.setFont(font);290 //设置对应单元格样式

291 cell.setCellStyle(failStyle);292 //单元格文字自适应长度

293 for (int i = 0; i < value.length(); i++) {294 sheet.autoSizeColumn(i);295 sheet.setColumnWidth(i,sheet.getColumnWidth(i)*18/10);296 }297 }298

299 /**

300 *301 *@paramrowNo302 *@paramcolumn303 *@paramvalue304 *@paramsize305 *@paramcon306 *@paramfontStyle307 *@paramcenterVa 垂直对齐方式308 *@paramcenterHo 水平对齐方式309 */

310 public void writeFailCell(int rowNo, int column, String value,int size,booleancon,String fontStyle,VerticalAlignment centerVa ,HorizontalAlignment centerHo) {311 if(fontStyle==null||"".equals(fontStyle)){312 fontStyle="宋体";313 }314 Row row = null;315 try{316 //获取指定行

317 row =sheet.getRow(rowNo);318 } catch(Exception e) {319 e.printStackTrace();320 }321 //行不存在,则创建

322 if (row == null) {323 row =sheet.createRow(rowNo);324 }325 //在该行,新建指定列的单元格

326 Cell cell =row.createCell(column);327 //设置单元格值

328 cell.setCellValue(value);329 //设置单元格样式

330 CellStyle failStyle = null;331 //新建字体样式

332 Font font = null;333 //根据不同的excel版本进行实例化

334 if (hssfWorkbook != null) {335 font =hssfWorkbook.createFont();336 failStyle =hssfWorkbook.createCellStyle();337 } else{338 font =xssfWorkbook.createFont();339 failStyle =xssfWorkbook.createCellStyle();340 }341 failStyle.setVerticalAlignment(centerVa);342 failStyle.setAlignment(centerHo);343 failStyle.setBorderBottom(BorderStyle.THIN); //下边框

344 failStyle.setBorderLeft(BorderStyle.THIN);//左边框

345 failStyle.setBorderTop(BorderStyle.THIN);//上边框

346 failStyle.setBorderRight(BorderStyle.THIN);//右边框

347 font.setColor(IndexedColors.BLACK.index);//字体颜色

348 font.setBold(con);349 font.setFontName(fontStyle);350 font.setFontHeightInPoints((short) size);351 //将字体颜色作为单元格样式

352 failStyle.setFont(font);353 //设置对应单元格样式

354 cell.setCellStyle(failStyle);355 //单元格文字自适应长度

356 for (int i = 0; i < value.length(); i++) {357 sheet.autoSizeColumn(i);358 sheet.setColumnWidth(i,sheet.getColumnWidth(i)*18/10);359 }360 }361

362 /**

363 * 将求和公式写入单元格中364 *@paramrowNo 公式写入的行数365 *@paramcolumn 公式写入的列数366 *@paramstartLine 求和开始行数367 */

368 public void sumMation(int rowNo, int column,intstartLine){369 Row row = null;370 try{371 //获取指定行

372 row =sheet.getRow(rowNo);373 } catch(Exception e) {374 e.printStackTrace();375 }376 //行不存在,则创建

377 if (row == null) {378 row =sheet.createRow(rowNo);379 }380 //在该行,新建指定列的单元格

381 Cell cell =row.createCell(column);382 String ch1 = CellReference.convertNumToColString(column); //将当前行长度转成ABC列

383 String ch1Start=ch1+startLine;384 String chiEnd=ch1+rowNo+"";385 //不需要给该指定的单元格赋值,写入上面行,导出时自动会合计

386 String format="SUM("+ch1Start+":"+chiEnd+")";387 cell.setCellFormula(format);388 CellStyle failStyle = null;389 //新建字体样式

390 Font font = null;391 //根据不同的excel版本进行实例化

392 if (hssfWorkbook != null) {393 font =hssfWorkbook.createFont();394 failStyle =hssfWorkbook.createCellStyle();395 } else{396 font =xssfWorkbook.createFont();397 failStyle =xssfWorkbook.createCellStyle();398 }399 failStyle.setVerticalAlignment( VerticalAlignment.CENTER);400 failStyle.setAlignment(HorizontalAlignment.CENTER);401 //设置字体颜色为红色

402 font.setColor(IndexedColors.BLACK.index);403 font.setBold(true);404 failStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,#0"));405 failStyle.setVerticalAlignment( VerticalAlignment.CENTER);406 failStyle.setAlignment(HorizontalAlignment.CENTER);407 failStyle.setBorderBottom(BorderStyle.THIN); //下边框

408 failStyle.setBorderLeft(BorderStyle.THIN);//左边框

409 failStyle.setBorderTop(BorderStyle.THIN);//上边框

410 failStyle.setBorderRight(BorderStyle.THIN);//右边框411 //将字体颜色作为单元格样式

412 failStyle.setFont(font);413 //设置对应单元格样式

414 cell.setCellStyle(failStyle);415 }416

417

418 //写入一整行的内容

419 public void writeLine(int rowNo, Listlist) {420 Row row = null;421 try{422 //获取指定行

423 row =sheet.getRow(rowNo);424 } catch(Exception e) {425 e.printStackTrace();426 }427 //行不存在,则创建

428 if (row == null) {429 row =sheet.createRow(rowNo);430 }431 Cell cell = null;432 for (int i = 0; i < list.size(); i++) {433 //在该行,新建指定列的单元格

434 cell =row.createCell(i);435 //设置单元格值

436 cell.setCellValue(list.get(i));437 //设置单元格样式

438 cell.setCellStyle(style);439 }440 }441

442 /**

443 * 单元格合并444 *@paramm 开始行445 *@paramn 结束行446 *@paramp 开始列447 *@paramq 结束列448 */

449 public void mergeCells(int m,int n,int p,intq){450 CellRangeAddress region = newCellRangeAddress(m, n, p, q);451 sheet.addMergedRegion(region);452

453 RegionUtil.setBorderBottom(1, region, sheet); //下边框

454 RegionUtil.setBorderLeft(1, region, sheet); //左边框

455 RegionUtil.setBorderRight(1, region, sheet); //有边框

456 RegionUtil.setBorderTop(1, region, sheet); //上边框

457 Row row = null;458 try{459 //获取指定行

460 row =sheet.getRow(m);461 } catch(Exception e) {462 e.printStackTrace();463 }464 //行不存在,则创建

465 if (row == null) {466 row =sheet.createRow(m);467 }468 //在该行,新建指定列的单元格

469 Cell cell =row.createCell(p);470 CellStyle failStyle = null;471 //新建字体样式

472 Font font = null;473 //根据不同的excel版本进行实例化

474 if (hssfWorkbook != null) {475 font =hssfWorkbook.createFont();476 failStyle =hssfWorkbook.createCellStyle();477 } else{478 font =xssfWorkbook.createFont();479 failStyle =xssfWorkbook.createCellStyle();480 }481 font.setBold(true);482 failStyle.setFont(font);483 cell.setCellStyle(failStyle);484 }485

486

487 /**

488 * //将结果表在内存中的工作簿内容保存到磁盘文件中489 */

490 public voidsave()491 {492 System.out.println("保存文件");493 //如果结果表文件未创建,则不保存

494 if (path != null) {495 try{496 //基于结果表路径创建文件输出流

497 stream = new FileOutputStream(newFile(path));498 //将结果表的workbook工作簿的内容写入输出流中,即写入文件

499 if (xssfWorkbook != null) {500 xssfWorkbook.write(stream);501 xssfWorkbook.close();502 } else{503 if (hssfWorkbook != null) {504 hssfWorkbook.write(stream);505 hssfWorkbook.close();506 } else{507 System.out.println("未打开Excel文件!");508 }509 }510 //公式刷新

511 sheet.setForceFormulaRecalculation(true);512 //关闭输出流,完成将内存中workbook写入文件的过程,保存文件。

513 stream.close();514 } catch(Exception e) {515 e.printStackTrace();516 }517 }518 }519

520 /**

521 * 复制指定下标的sheet522 *@paramsheetIndex 被复制sheet的下标523 *@paramsheetName 复制后sheet的名称524 */

525 public void copySheet(intsheetIndex, String sheetName){526 try{527 //基于结果表路径创建文件输出流528

529 //将结果表的workbook工作簿的内容写入输出流中,即写入文件

530 if (xssfWorkbook != null) {531 sheet=xssfWorkbook.cloneSheet(sheetIndex, sheetName);532

533 } else{534 if (hssfWorkbook != null) {535 HSSFSheet rows =hssfWorkbook.cloneSheet(sheetIndex);536 useSheet(rows.getSheetName());537 updateSheetName(sheetName);538 } else{539 System.out.println("未打开Excel文件!");540 }541 }542 //公式刷新

543 sheet.setForceFormulaRecalculation(true);544 } catch(Exception e) {545 e.printStackTrace();546 }547 }548

549 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值