分享一个自己做的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 block113 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 // 基于新生表,创建文件输出流stream163 stream = new FileOutputStream(file);164 // 将用例表中的内容写入文件输出流stream165 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版excel178 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 * 创建指定名称的sheet211 * @param sheetName212 */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 * 当用例执行结果失败时,使用该方法,以红色字体写入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,boolean con,String fontStyle) {248 if(fontStyle==null||"".equals(fontStyle)){249 font;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 rowNo302 * @param column303 * @param value304 * @param size305 * @param con306 * @param fontStyle307 * @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 font;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 * 复制指定下标的sheet522 * @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 }
原文转载:http://www.shaoqun.com/a/584576.html
zen cart:https://www.ikjzd.com/w/1282
深兰科技:https://www.ikjzd.com/w/1517
分享一个自己做的poi工具类,写不是很完全,足够我自己当前使用,有兴趣的可以自行扩展1importorg.apache.commons.lang3.exception.ExceptionUtils;2importorg.apache.poi.hssf.usermodel.HSSFDataFormat;3importorg.apache.poi.hssf.usermodel.HSSFSheet;4i
ifttt:https://www.ikjzd.com/w/956
邮乐网购:https://www.ikjzd.com/w/1776
赛兔:https://www.ikjzd.com/w/2375
销售宝典!如何借助大卖的listing来销售产品?:https://www.ikjzd.com/home/112852
PayPal和eBay变更互联网销售税征收细则!:https://www.ikjzd.com/home/110084
iphone 11新机发布了,我们如何进行相关配件选品?:https://www.ikjzd.com/home/107519
No comments:
Post a Comment