分享一個自己做的poi工具類,寫不是很完全,足夠我自己當前使用,有興趣的可以自行擴展
1 import org.apache.commons.lang3.exception.ExceptionUtils; 2 import org.apache.poi.hssf.usermodel.HSSFDataFormat; 3 import org.apache.poi.hssf.usermodel.HSSFSheet; 4 import org.apache.poi.hssf.usermodel.HSSFWorkbook; 5 import org.apache.poi.hssf.util.CellReference; 6 import org.apache.poi.ss.usermodel.*; 7 import org.apache.poi.ss.util.CellRangeAddress; 8 import org.apache.poi.ss.util.RegionUtil; 9 import org.apache.poi.xssf.usermodel.XSSFWorkbook; 10 import java.io.File; 11 import java.io.FileInputStream; 12 import java.io.FileOutputStream; 13 import java.io.IOException; 14 import java.util.List; 15 16 public class ExcelWriterUtil_Poi { 17 18 19 // 用于存放結果表內容的xlsx格式的作業簿 20 private XSSFWorkbook xssfWorkbook = null; 21 // 用于存放結果表內容的xls格式的作業簿 22 private HSSFWorkbook hssfWorkbook = null; 23 // 作業的sheet頁 24 private Sheet 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 public String getSheetName() { 42 43 return sheetName; 44 } 45 46 /** 47 * 根據名字切換sheet進行操作 // 指定作業sheet 48 * 49 * @param sheetName 50 */ 51 public void useSheet(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 * @param sheetName 81 */ 82 public void updateSheetName(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 void closeStream() { 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 public ExcelWriterUtil_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(new File(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(new File(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 = new File(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 = new FileOutputStream(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 = new FileInputStream(file); 177 // 判斷結果檔案的后綴是03版還是07版excel 178 if (resultType.equals(".xlsx")) { 179 try { 180 //通過檔案輸入流,在記憶體中創建結果表的作業簿 181 xssfWorkbook = new XSSFWorkbook(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 = new HSSFWorkbook(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 * 創建指定名稱的sheet 211 * @param sheetName 212 */ 213 public void createSheet(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, int column) { 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 * 當用例執行結果失敗時,使用該方法,以紅色字體寫入excel 240 * @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,boolean con,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 * @param rowNo 302 * @param column 303 * @param value 304 * @param size 305 * @param con 306 * @param fontStyle 307 * @param centerVa 垂直對齊方式 308 * @param centerHo 水平對齊方式 309 */ 310 public void writeFailCell(int rowNo, int column, String value,int size,boolean con,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 * @param rowNo 公式寫入的行數 365 * @param column 公式寫入的列數 366 * @param startLine 求和開始行數 367 */ 368 public void sumMation(int rowNo, int column,int startLine){ 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, List<String> list) { 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 * @param m 開始行 445 * @param n 結束行 446 * @param p 開始列 447 * @param q 結束列 448 */ 449 public void mergeCells(int m,int n,int p,int q){ 450 CellRangeAddress region = new CellRangeAddress(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); // 上邊框</strong></span> 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 void save() 491 { 492 System.out.println("保存檔案"); 493 // 如果結果表檔案未創建,則不保存 494 if (path != null) { 495 try { 496 //基于結果表路徑創建檔案輸出流 497 stream = new FileOutputStream(new File(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 * 復制指定下標的sheet 522 * @param sheetIndex 被復制sheet的下標 523 * @param sheetName 復制后sheet的名稱 524 */ 525 public void copySheet(int sheetIndex, 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 }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/263196.html
標籤:Java
