POI 常用方法

  1. package com.testritegroup.datahub.print.util;  
  2.   
  3.   
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStream;  
  9. import java.util.ArrayList;  
  10. import java.util.HashMap;  
  11. import java.util.Iterator;  
  12. import java.util.List;  
  13. import java.util.Map;  
  14. import java.util.TreeMap;  
  15. import java.util.Map.Entry;  
  16. import java.util.regex.Pattern;  
  17.   
  18. import org.apache.commons.logging.Log;  
  19. import org.apache.commons.logging.LogFactory;  
  20. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  21. import org.apache.poi.ss.usermodel.Cell;  
  22. import org.apache.poi.ss.usermodel.CellStyle;  
  23. import org.apache.poi.ss.usermodel.ClientAnchor;  
  24. import org.apache.poi.ss.usermodel.CreationHelper;  
  25. import org.apache.poi.ss.usermodel.DateUtil;  
  26. import org.apache.poi.ss.usermodel.Drawing;  
  27. import org.apache.poi.ss.usermodel.Font;  
  28. import org.apache.poi.ss.usermodel.Picture;  
  29. import org.apache.poi.ss.usermodel.Row;  
  30. import org.apache.poi.ss.usermodel.Sheet;  
  31. import org.apache.poi.ss.usermodel.Workbook;  
  32. import org.apache.poi.ss.usermodel.WorkbookFactory;  
  33. import org.apache.poi.ss.util.CellRangeAddress;  
  34. import org.apache.poi.ss.util.CellReference;  
  35. import org.apache.poi.util.IOUtils;  
  36. import org.apache.poi.xssf.usermodel.XSSFCellStyle;  
  37. import org.apache.poi.xssf.usermodel.XSSFColor;  
  38. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  39.   
  40. /** 
  41.  * @className:POIExcelUtil.java 
  42.  * @classDescription:POI操作类 
  43.  */  
  44.   
  45. public class POIExcelUtil {  
  46.     private static Log log = LogFactory.getLog(POIExcelUtil.class);  
  47.   
  48.     // ------------------------写Excel-----------------------------------  
  49.     /** 
  50.      * 创建workBook对象 xlsx(2007以上版本) 
  51.      *  
  52.      * @return 
  53.      */  
  54.     public static Workbook createWorkbook() {  
  55.         return createWorkbook(false);  
  56.     }  
  57.   
  58.     /** 
  59.      * 创建WorkBook对象 
  60.      *  
  61.      * @param flag 
  62.      *            true:xlsx(1997-2007) false:xls(2007以下) 
  63.      * @return 
  64.      */  
  65.     public static Workbook createWorkbook(boolean flag) {  
  66.         Workbook wb;  
  67.         if (flag) {  
  68.             wb = new XSSFWorkbook();  
  69.         } else {  
  70.             wb = new HSSFWorkbook();  
  71.         }  
  72.         return wb;  
  73.     }  
  74.   
  75.     /** 
  76.      * 添加图片 
  77.      *  
  78.      * @param wb 
  79.      *            workBook对象 
  80.      * @param sheet 
  81.      *            sheet对象 
  82.      * @param picFileName 
  83.      *            图片文件名称(全路径) 
  84.      * @param picType 
  85.      *            图片类型 
  86.      * @param row 
  87.      *            图片所在的行 
  88.      * @param col 
  89.      *            图片所在的列 
  90.      */  
  91.     public static void addPicture(Workbook wb, Sheet sheet, String picFileName,  
  92.             int picType, int row, int col) {  
  93.         InputStream is = null;  
  94.         try {  
  95.             // 读取图片  
  96.             is = new FileInputStream(picFileName);  
  97.             byte[] bytes = IOUtils.toByteArray(is);  
  98.             int pictureIdx = wb.addPicture(bytes, picType);  
  99.             is.close();  
  100.             // 写图片  
  101.             CreationHelper helper = wb.getCreationHelper();  
  102.             Drawing drawing = sheet.createDrawingPatriarch();  
  103.             ClientAnchor anchor = helper.createClientAnchor();  
  104.             // 设置图片的位置  
  105.             anchor.setCol1(col);  
  106.             anchor.setRow1(row);  
  107.             Picture pict = drawing.createPicture(anchor, pictureIdx);  
  108.   
  109.             pict.resize();  
  110.         } catch (Exception e) {  
  111.             try {  
  112.                 if (is != null) {  
  113.                     is.close();  
  114.                 }  
  115.             } catch (IOException e1) {  
  116.                 e1.printStackTrace();  
  117.             }  
  118.             e.printStackTrace();  
  119.         }  
  120.     }  
  121.   
  122.     /** 
  123.      * 创建Cell 默认为水平和垂直方式都是居中 
  124.      *  
  125.      * @param style 
  126.      *            CellStyle对象 
  127.      * @param row 
  128.      *            Row对象 
  129.      * @param column 
  130.      *            单元格所在的列 
  131.      * @return 
  132.      */  
  133.     public static Cell createCell(CellStyle style, Row row, short column) {  
  134.         return createCell(style, row, column, XSSFCellStyle.ALIGN_CENTER,  
  135.                 XSSFCellStyle.ALIGN_CENTER);  
  136.     }  
  137.   
  138.     /** 
  139.      * 创建Cell并设置水平和垂直方式 
  140.      *  
  141.      * @param style 
  142.      *            CellStyle对象 
  143.      * @param row 
  144.      *            Row对象 
  145.      * @param column 
  146.      *            单元格所在的列 
  147.      * @param halign 
  148.      *            水平对齐方式:XSSFCellStyle.VERTICAL_CENTER. 
  149.      * @param valign 
  150.      *            垂直对齐方式:XSSFCellStyle.ALIGN_LEFT 
  151.      */  
  152.     public static Cell createCell(CellStyle style, Row row, short column,  
  153.             short halign, short valign) {  
  154.         Cell cell = row.createCell(column);  
  155.         setAlign(style, halign, valign);  
  156.         cell.setCellStyle(style);  
  157.         return cell;  
  158.     }  
  159.   
  160.     /** 
  161.      * 合并单元格 
  162.      *  
  163.      * @param sheet 
  164.      * @param firstRow 
  165.      *            开始行 
  166.      * @param lastRow 
  167.      *            最后行 
  168.      * @param firstCol 
  169.      *            开始列 
  170.      * @param lastCol 
  171.      *            最后列 
  172.      */  
  173.     public static void mergeCell(Sheet sheet, int firstRow, int lastRow,  
  174.             int firstCol, int lastCol) {  
  175.         sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol,  
  176.                 lastCol));  
  177.     }  
  178.   
  179.     // ---------------------------------设置样式-----------------------  
  180.   
  181.     /** 
  182.      * 设置单元格对齐方式 
  183.      *  
  184.      * @param style 
  185.      * @param halign 
  186.      * @param valign 
  187.      * @return 
  188.      */  
  189.     public static CellStyle setAlign(CellStyle style, short halign, short valign) {  
  190.         style.setAlignment(halign);  
  191.         style.setVerticalAlignment(valign);  
  192.         return style;  
  193.     }  
  194.   
  195.     /** 
  196.      * 设置单元格边框(四个方向的颜色一样) 
  197.      *  
  198.      * @param style 
  199.      *            style对象 
  200.      * @param borderStyle 
  201.      *            边框类型 :dished-虚线 thick-加粗 double-双重 dotted-有点的 
  202.      *            CellStyle.BORDER_THICK 
  203.      * @param borderColor 
  204.      *            颜色 IndexedColors.GREEN.getIndex() 
  205.      * @return 
  206.      */  
  207.     public static CellStyle setBorder(CellStyle style, short borderStyle,  
  208.             short borderColor) {  
  209.   
  210.         // 设置底部格式(样式+颜色)  
  211.         style.setBorderBottom(borderStyle);  
  212.         style.setBottomBorderColor(borderColor);  
  213.         // 设置左边格式  
  214.         style.setBorderLeft(borderStyle);  
  215.         style.setLeftBorderColor(borderColor);  
  216.         // 设置右边格式  
  217.         style.setBorderRight(borderStyle);  
  218.         style.setRightBorderColor(borderColor);  
  219.         // 设置顶部格式  
  220.         style.setBorderTop(borderStyle);  
  221.         style.setTopBorderColor(borderColor);  
  222.   
  223.         return style;  
  224.     }  
  225.   
  226.     /** 
  227.      * 自定义颜色(xssf) 
  228.      *  
  229.      * @param style 
  230.      *            xssfStyle 
  231.      * @param red 
  232.      *            RGB red (0-255) 
  233.      * @param green 
  234.      *            RGB green (0-255) 
  235.      * @param blue 
  236.      *            RGB blue (0-255) 
  237.      */  
  238.     public static CellStyle setBackColorByCustom(XSSFCellStyle style, int red,  
  239.             int green, int blue) {  
  240.         // 设置前端颜色  
  241.         style.setFillForegroundColor(new XSSFColor(new java.awt.Color(red,  
  242.                 green, blue)));  
  243.         // 设置填充模式  
  244.         style.setFillPattern(CellStyle.SOLID_FOREGROUND);  
  245.   
  246.         return style;  
  247.     }  
  248.   
  249.     /** 
  250.      * 设置前景颜色 
  251.      *  
  252.      * @param style 
  253.      *            style对象 
  254.      * @param color 
  255.      *            :IndexedColors.YELLOW.getIndex() 
  256.      * @return 
  257.      */  
  258.     public static CellStyle setBackColor(CellStyle style, short color) {  
  259.   
  260.         // 设置前端颜色  
  261.         style.setFillForegroundColor(color);  
  262.         // 设置填充模式  
  263.         style.setFillPattern(CellStyle.SOLID_FOREGROUND);  
  264.   
  265.         return style;  
  266.     }  
  267.   
  268.     /** 
  269.      * 设置背景颜色 
  270.      *  
  271.      * @param style 
  272.      *            style对象 
  273.      * @param color 
  274.      *            :IndexedColors.YELLOW.getIndex() 
  275.      * @param fillPattern 
  276.      *            :CellStyle.SPARSE_DOTS 
  277.      * @return 
  278.      */  
  279.     public static CellStyle setBackColor(CellStyle style, short backColor,  
  280.             short fillPattern) {  
  281.   
  282.         // 设置背景颜色  
  283.         style.setFillBackgroundColor(backColor);  
  284.   
  285.         // 设置填充模式  
  286.         style.setFillPattern(fillPattern);  
  287.   
  288.         return style;  
  289.     }  
  290.   
  291.     /** 
  292.      *  
  293.      * 设置字体(简单的需求实现,如果复杂的字体,需要自己去实现)尽量重用 
  294.      *  
  295.      * @param style 
  296.      *            style对象 
  297.      * @param fontSize 
  298.      *            字体大小 shot(24) 
  299.      * @param color 
  300.      *            字体颜色 IndexedColors.YELLOW.getIndex() 
  301.      * @param fontName 
  302.      *            字体名称 "Courier New" 
  303.      * @param 
  304.      */  
  305.     public static CellStyle setFont(Font font, CellStyle style, short fontSize,  
  306.             short color, String fontName) {  
  307.         font.setFontHeightInPoints(color);  
  308.         font.setFontName(fontName);  
  309.   
  310.         // font.setItalic(true);// 斜体  
  311.         // font.setStrikeout(true);//加干扰线  
  312.   
  313.         font.setColor(color);// 设置颜色  
  314.         // Fonts are set into a style so create a new one to use.  
  315.         style.setFont(font);  
  316.   
  317.         return style;  
  318.   
  319.     }  
  320.   
  321.     /** 
  322.      *  
  323.      * @param createHelper 
  324.      *            createHelper对象 
  325.      * @param style 
  326.      *            CellStyle对象 
  327.      * @param formartData 
  328.      *            date:"m/d/yy h:mm"; int:"#,###.0000" ,"0.0" 
  329.      */  
  330.     public static CellStyle setDataFormat(CreationHelper createHelper,  
  331.             CellStyle style, String formartData) {  
  332.   
  333.         style.setDataFormat(createHelper.createDataFormat().getFormat(  
  334.                 formartData));  
  335.   
  336.         return style;  
  337.     }  
  338.   
  339.     /** 
  340.      * 将Workbook写入文件 
  341.      *  
  342.      * @param wb 
  343.      *            workbook对象 
  344.      * @param fileName 
  345.      *            文件的全路径 
  346.      * @return 
  347.      */  
  348.     public static boolean createExcel(Workbook wb, String fileName) {  
  349.         boolean flag = true;  
  350.         FileOutputStream fileOut = null;  
  351.         try {  
  352.             File file = new File(fileName);  
  353.             File parent = file.getParentFile();  
  354.             if (parent != null && !parent.exists()) {  
  355.                 parent.mkdirs();  
  356.             }  
  357.             fileOut = new FileOutputStream(fileName);  
  358.             wb.write(fileOut);  
  359.             fileOut.close();  
  360.   
  361.         } catch (Exception e) {  
  362.             flag = false;  
  363.             if (fileOut != null) {  
  364.                 try {  
  365.                     fileOut.close();  
  366.                 } catch (IOException e1) {  
  367.                     // TODO Auto-generated catch block  
  368.                     e1.printStackTrace();  
  369.                 }  
  370.             }  
  371.             e.printStackTrace();  
  372.         }  
  373.         return flag;  
  374.     }  
  375.   
  376.     // --------------------读取Excel-----------------------  
  377.     /** 
  378.      * 读取Excel 
  379.      *  
  380.      * @param filePathName 
  381.      * @return 
  382.      */  
  383.     public static Workbook readExcel(String filePathName) {  
  384.         InputStream inp = null;  
  385.         Workbook wb = null;  
  386.         try {  
  387.             inp = new FileInputStream(filePathName);  
  388.             wb = WorkbookFactory.create(inp);  
  389.             inp.close();  
  390.   
  391.         } catch (Exception e) {  
  392.             try {  
  393.                 if (null != inp) {  
  394.                     inp.close();  
  395.                 }  
  396.             } catch (IOException e1) {  
  397.                 // TODO Auto-generated catch block  
  398.                 e1.printStackTrace();  
  399.             }  
  400.             e.printStackTrace();  
  401.         }  
  402.         return wb;  
  403.     }  
  404.   
  405.     /** 
  406.      * 读取Cell的值 
  407.      *  
  408.      * @param sheet 
  409.      * @return 
  410.      */  
  411.     public static Map readCell(Sheet sheet) {  
  412.         Map map = new HashMap();  
  413.         // 遍历所有行  
  414.         for (Row row : sheet) {  
  415.             // 便利所有列  
  416.             for (Cell cell : row) {  
  417.                 // 获取单元格的类型  
  418.                 CellReference cellRef = new CellReference(row.getRowNum(),  
  419.                         cell.getColumnIndex());  
  420.                 // System.out.print(cellRef.formatAsString());  
  421.                 String key = cellRef.formatAsString();  
  422.                 // System.out.print(" - ");  
  423.   
  424.                 switch (cell.getCellType()) {  
  425.                 // 字符串  
  426.                 case Cell.CELL_TYPE_STRING:  
  427.                     map.put(key, cell.getRichStringCellValue().getString());  
  428.                     // System.out.println(cell.getRichStringCellValue()  
  429.                     // .getString());  
  430.                     break;  
  431.                 // 数字  
  432.                 case Cell.CELL_TYPE_NUMERIC:  
  433.                     if (DateUtil.isCellDateFormatted(cell)) {  
  434.                         // System.out.println(cell.getDateCellValue());  
  435.                         map.put(key, cell.getDateCellValue());  
  436.                     } else {  
  437.                         // System.out.println(cell.getNumericCellValue());  
  438.                         map.put(key, cell.getNumericCellValue());  
  439.                     }  
  440.                     break;  
  441.                 // boolean  
  442.                 case Cell.CELL_TYPE_BOOLEAN:  
  443.                     // System.out.println(cell.getBooleanCellValue());  
  444.                     map.put(key, cell.getBooleanCellValue());  
  445.                     break;  
  446.                 // 方程式  
  447.                 case Cell.CELL_TYPE_FORMULA:  
  448.                     // System.out.println(cell.getCellFormula());  
  449.                     map.put(key, cell.getCellFormula());  
  450.                     break;  
  451.                 // 空值  
  452.                 default:  
  453.                     System.out.println();  
  454.                     map.put(key, "");  
  455.                 }  
  456.   
  457.             }  
  458.         }  
  459.         return map;  
  460.   
  461.     }  
  462.   
  463.   
  464.     /** 
  465.      * 替换明细内容 
  466.      * @param sheet  
  467.      * @param detailList 明细列表 
  468.      */  
  469.     private static void replaceDetail(Workbook workbook, Sheet sheet, String detailKey, List<Map<String, String>> detailList) {  
  470.         // 找到 #detail 的位置,复制该行到到下一行  
  471.         if(detailList == null || detailList.size() == 0return;  
  472.           
  473.         int detailSize = detailList.size();  
  474.           
  475.         Cell detailCell = findCell(sheet, detailKey);  
  476.         if(detailCell == nullreturn;  
  477.           
  478.           
  479.         // #detail 所在行号  
  480.         int detailRow = detailCell.getRowIndex();  
  481.         // #detail 所在列号  
  482.         int detailColunm = detailCell.getColumnIndex();  
  483.           
  484.         for(int i = 1; i < detailSize; i++){  
  485.             copyRow(workbook, sheet, detailRow, detailRow + i);  
  486.         }  
  487.           
  488.           
  489.         int[] rownum = getDetailColunmNum(sheet, detailRow,detailColunm, detailList.get(0).size());  
  490.         for(Map<String, String> detailMap : detailList){  
  491.             int colunm = 0;  
  492.             Row thisRow = sheet.getRow(detailRow);  
  493.             float defaultRowHeight = thisRow.getHeightInPoints();  
  494.             float maxHeight = defaultRowHeight;  
  495.               
  496.             for(Entry<String, String> entry: detailMap.entrySet()){  
  497.                   
  498.                 Cell thisCell = thisRow.getCell(rownum[colunm]);  
  499.                   
  500.                 float thisHeight = getExcelCellAutoHeight(entry.getValue(),defaultRowHeight, getMergedCellNum(thisCell) * sheet.getColumnWidth(rownum[colunm])/256);   
  501.                 if(thisHeight > maxHeight) maxHeight = thisHeight;  
  502.                   
  503.                   
  504.                 if(thisCell == null) {  
  505.                     thisCell = thisRow.createCell(rownum[colunm]);  
  506.                     thisCell.setCellValue(entry.getValue());  
  507.                 }else {  
  508.                     thisCell.setCellValue(entry.getValue());  
  509.                     thisCell.getCellStyle().setWrapText(true);  
  510.                 }  
  511.                   
  512.                 colunm++;  
  513.             }  
  514.             thisRow.setHeightInPoints(maxHeight);  
  515.             detailRow++;  
  516.         }  
  517.     }  
  518.       
  519.     private static int[] getDetailColunmNum(Sheet sheet, int detailRow, int detalColunm, int detailMapSize){  
  520.         int[] rowNum = new int[detailMapSize];  
  521.         int mergedRow = 0;  
  522.         int j = 0;  
  523.         for(int i = 0; i < detailMapSize + mergedRow;i++){  
  524.             Cell cell = sheet.getRow(detailRow).getCell(i+detalColunm);  
  525.             if(isMergedRegionNotFirstCell(cell)){  
  526.                 mergedRow++;  
  527.             } else {  
  528.                 rowNum[j++] = i+detalColunm;  
  529.             }  
  530.               
  531.         }  
  532.         return rowNum;  
  533.           
  534.     }  
  535.       
  536.       
  537.       
  538.     /** 
  539.      * 判断当前单元格是合并单元格的非第一行 
  540.      * @param cell 
  541.      * @return 
  542.      */  
  543.     private static int getMergedCellNum(Cell cell) {  
  544.         if(cell == nullreturn 1;  
  545.         Sheet sheet = cell.getSheet();  
  546.           
  547.         CellRangeAddress range = null;  
  548.         int mergedNum = sheet.getNumMergedRegions();  
  549.         for (int i = 0; i < mergedNum; i++) {  
  550.                 range = sheet.getMergedRegion(i);  
  551.                 if(cell.getColumnIndex() == range.getFirstColumn() && cell.getRowIndex() == range.getFirstRow()){  
  552.                     return range.getLastColumn() - range.getFirstColumn() + 1;  
  553.                 }   
  554.         }  
  555.         return 1;  
  556.     }  
  557.       
  558.     /** 
  559.      * 判断当前单元格是合并单元格的非第一行 
  560.      * @param cell 
  561.      * @return 
  562.      */  
  563.     private static boolean isMergedRegionNotFirstCell(Cell cell) {  
  564.         if(cell == nullreturn false;  
  565.         Sheet sheet = cell.getSheet();  
  566.           
  567.         CellRangeAddress range = null;  
  568.         int mergedNum = sheet.getNumMergedRegions();  
  569.         for (int i = 0; i < mergedNum; i++) {  
  570.                 range = sheet.getMergedRegion(i);  
  571.                 if(cell.getColumnIndex() > range.getFirstColumn()  
  572.                         && cell.getColumnIndex() <= range.getLastColumn()   
  573.                         && cell.getRowIndex() == range.getFirstRow()){  
  574.                     return true;  
  575.                 }   
  576.         }  
  577.         return false;  
  578.     }  
  579.     
  580.   
  581.   
  582.   
  583.     /** 
  584.      * 替换文本 
  585.      *  
  586.      * @param sheet 
  587.      *            工作表 
  588.      * @param replaceTextMap 
  589.      *            替换文本MAP key=原字符串 value=替换字符串 
  590.      */  
  591.     private static void replaceHeader(Sheet sheet, Map<String, String> replaceTextMap) {  
  592.         // 遍历所有行  
  593.         for (Row thisRow : sheet) {  
  594.             boolean isFound = false;  
  595.             // 便利所有列  
  596.             float defaultRowHeight = thisRow.getHeightInPoints();  
  597.             float maxHeight = defaultRowHeight;  
  598.             for (Cell thisCell : thisRow) {  
  599.           
  600.                   
  601.                 // 获取单元格的类型  
  602.                 CellReference cellRef = new CellReference(thisRow.getRowNum(),  
  603.                         thisCell.getColumnIndex());  
  604.                 switch (thisCell.getCellType()) {  
  605.                 // 字符串  
  606.                 case Cell.CELL_TYPE_STRING:  
  607.                     String targetText = thisCell.getRichStringCellValue()  
  608.                             .getString();  
  609.                       
  610.   
  611.                       
  612.                     if (targetText != null && !targetText.trim().equals("")) {  
  613.                         if(replaceTextMap.containsKey(targetText)){  
  614.                               
  615.                         float thisHeight = getExcelCellAutoHeight((String)replaceTextMap.get(targetText),defaultRowHeight, getMergedCellNum(thisCell) * sheet.getColumnWidth(thisCell.getColumnIndex())/256);   
  616.                         if(thisHeight > maxHeight) maxHeight = thisHeight;  
  617.                             isFound = true;  
  618.                             thisCell.setCellValue((String)replaceTextMap.get(targetText));  
  619.                             thisCell.getCellStyle().setWrapText(true);  
  620.                             log.info(" Sheet[" + sheet.getSheetName() + "]"  
  621.                                     + "行:" + (thisCell.getRowIndex() + 1) + "列:"  
  622.                                     + getColLetter(thisCell.getColumnIndex()) + " "  
  623.                                     + targetText + " replace " + targetText + " -> "  
  624.                                     + (String)replaceTextMap.get(targetText));  
  625.                         }  
  626.                     }  
  627.   
  628.                     break;  
  629.                 // 数字  
  630.                 case Cell.CELL_TYPE_NUMERIC:  
  631.                     break;  
  632.                 // boolean  
  633.                 case Cell.CELL_TYPE_BOOLEAN:  
  634.                     break;  
  635.                 // 方程式  
  636.                 case Cell.CELL_TYPE_FORMULA:  
  637.                     break;  
  638.                 // 空值  
  639.                 default:  
  640.                 }  
  641.   
  642.             }  
  643.               
  644.             if(isFound) thisRow.setHeightInPoints(maxHeight);  
  645.         }  
  646.   
  647.     }  
  648.   
  649.       
  650.     /** 
  651.      * 替换文本 
  652.      *  
  653.      * @param sheet 
  654.      *            工作表 
  655.      * @param key 
  656.      *            原字符串 
  657.      * @param value 
  658.      *            替换字符串 
  659.      */  
  660.     private static Cell findCell(Sheet sheet, String findStr) {  
  661.         // 遍历所有行  
  662.         for (Row row : sheet) {  
  663.             // 便利所有列  
  664.             for (Cell cell : row) {  
  665.                 // 获取单元格的类型  
  666.                 CellReference cellRef = new CellReference(row.getRowNum(),  
  667.                         cell.getColumnIndex());  
  668.                 switch (cell.getCellType()) {  
  669.                 // 字符串  
  670.                 case Cell.CELL_TYPE_STRING:  
  671.                     String targetText = cell.getRichStringCellValue()  
  672.                             .getString();  
  673.   
  674.                     if (targetText != null && !targetText.trim().equals("")) {  
  675.                         if (targetText.contains(findStr))  
  676.                             return cell;  
  677.                     }  
  678.   
  679.                     break;  
  680.                 // 数字  
  681.                 case Cell.CELL_TYPE_NUMERIC:  
  682.                     break;  
  683.                 // boolean  
  684.                 case Cell.CELL_TYPE_BOOLEAN:  
  685.                     break;  
  686.                 // 方程式  
  687.                 case Cell.CELL_TYPE_FORMULA:  
  688.                     break;  
  689.                 // 空值  
  690.                 default:  
  691.                 }  
  692.   
  693.             }  
  694.         }  
  695.           
  696.         return null;  
  697.   
  698.     }  
  699.       
  700.     /** 
  701.      * 将列的索引换算成ABCD字母,这个方法要在插入公式时用到。 
  702.      *  
  703.      * @param colIndex 
  704.      *            列索引。 
  705.      * @return ABCD字母。 
  706.      */  
  707.     private static String getColLetter(int colIndex) {  
  708.         String ch = "";  
  709.         if (colIndex < 26)  
  710.             ch = "" + (char) ((colIndex) + 65);  
  711.         else  
  712.             ch = "" + (char) ((colIndex) / 26 + 65 - 1)  
  713.                     + (char) ((colIndex) % 26 + 65);  
  714.         return ch;  
  715.     }  
  716.   
  717.     /** 
  718.      * 遍历文件夹下的文件,并打印文件夹下文件的路径 
  719.      * @param directoryPath 文件夹目录 
  720.      */  
  721.     public static void traversal(List<String> filesPathList, String directoryPath) {  
  722.         File dir = new File(directoryPath);  
  723.         File[] files = dir.listFiles();  
  724.         if (files == null) {  
  725.             return;  
  726.         } else {  
  727.             for (int i = 0; i < files.length; i++) {  
  728.                 if (files[i].isDirectory()) {  
  729.                     traversal(filesPathList, files[i].getAbsolutePath());  
  730.                 } else {  
  731.                     filesPathList.add(files[i].getAbsolutePath());  
  732.                 }  
  733.             }  
  734.         }  
  735.     }  
  736.       
  737.     private static void copyRow(Workbook workbook, Sheet worksheet, int sourceRowNum, int destinationRowNum) {  
  738.         // Get the source / new row  
  739.         Row newRow = worksheet.getRow(destinationRowNum);  
  740.         Row sourceRow = worksheet.getRow(sourceRowNum);  
  741.   
  742.         // If the row exist in destination, push down all rows by 1 else create a new row  
  743.         if (newRow != null) {  
  744.             worksheet.shiftRows(destinationRowNum, worksheet.getLastRowNum(), 1);  
  745.         } else {  
  746.             newRow = worksheet.createRow(destinationRowNum);  
  747.         }  
  748.   
  749.         // Loop through source columns to add to new row  
  750.         for (int i = 0; i < sourceRow.getLastCellNum(); i++) {  
  751.             // Grab a copy of the old/new cell  
  752.             Cell oldCell = sourceRow.getCell(i);  
  753.             Cell newCell = newRow.createCell(i);  
  754.   
  755.             // If the old cell is null jump to next cell  
  756.             if (oldCell == null) {  
  757.                 newCell = null;  
  758.                 continue;  
  759.             }  
  760.   
  761.             // Copy style from old cell and apply to new cell  
  762.             CellStyle newCellStyle = workbook.createCellStyle();  
  763.             newCellStyle.cloneStyleFrom(oldCell.getCellStyle());  
  764.             newCell.setCellStyle(newCellStyle);  
  765.   
  766.             // If there is a cell comment, copy  
  767.             if (newCell.getCellComment() != null) {  
  768.                 newCell.setCellComment(oldCell.getCellComment());  
  769.             }  
  770.   
  771.             // If there is a cell hyperlink, copy  
  772.             if (oldCell.getHyperlink() != null) {  
  773.                 newCell.setHyperlink(oldCell.getHyperlink());  
  774.             }  
  775.   
  776.             // Set the cell data type  
  777.             newCell.setCellType(oldCell.getCellType());  
  778.   
  779.             // Set the cell data value  
  780.             switch (oldCell.getCellType()) {  
  781.                 case Cell.CELL_TYPE_BLANK:  
  782.                     newCell.setCellValue(oldCell.getStringCellValue());  
  783.                     break;  
  784.                 case Cell.CELL_TYPE_BOOLEAN:  
  785.                     newCell.setCellValue(oldCell.getBooleanCellValue());  
  786.                     break;  
  787.                 case Cell.CELL_TYPE_ERROR:  
  788.                     newCell.setCellErrorValue(oldCell.getErrorCellValue());  
  789.                     break;  
  790.                 case Cell.CELL_TYPE_FORMULA:  
  791.                     newCell.setCellFormula(oldCell.getCellFormula());  
  792.                     break;  
  793.                 case Cell.CELL_TYPE_NUMERIC:  
  794.                     newCell.setCellValue(oldCell.getNumericCellValue());  
  795.                     break;  
  796.                 case Cell.CELL_TYPE_STRING:  
  797.                     newCell.setCellValue(oldCell.getRichStringCellValue());  
  798.                     break;  
  799.             }  
  800.         }  
  801.   
  802.         // If there are are any merged regions in the source row, copy to new row  
  803.         for (int i = 0; i < worksheet.getNumMergedRegions(); i++) {  
  804.             CellRangeAddress cellRangeAddress = worksheet.getMergedRegion(i);  
  805.             if (cellRangeAddress.getFirstRow() == sourceRow.getRowNum()) {  
  806.                 CellRangeAddress newCellRangeAddress = new CellRangeAddress(newRow.getRowNum(),  
  807.                         (newRow.getRowNum() +  
  808.                                 (cellRangeAddress.getFirstRow() -  
  809.                                         cellRangeAddress.getLastRow())),  
  810.                         cellRangeAddress.getFirstColumn(),  
  811.                         cellRangeAddress.getLastColumn());  
  812.                 worksheet.addMergedRegion(newCellRangeAddress);  
  813.             }  
  814.         }  
  815.     }  
  816.   
  817.       
  818.     public static float getExcelCellAutoHeight(String str,float defaultRowHeight, int fontCountInline) {  
  819.         int defaultCount = 0;  
  820.           
  821.         for (int i = 0; i < str.length(); i++) {  
  822.             int ff = getregex(str.substring(i, i + 1));  
  823.             defaultCount = defaultCount + ff;  
  824.         }  
  825.         if (defaultCount > fontCountInline){  
  826.             return ((int) (defaultCount / fontCountInline) + 1) * defaultRowHeight;//计算  
  827.         } else {  
  828.             return defaultRowHeight;  
  829.         }  
  830.     }  
  831.   
  832.     public static int getregex(String charStr) {  
  833.           
  834.         if(charStr==" ")  
  835.         {  
  836.             return 1;  
  837.         }  
  838.         // 判断是否为字母或字符  
  839.         if (Pattern.compile("^[A-Za-z0-9]+$").matcher(charStr).matches()) {  
  840.             return 1;  
  841.         }  
  842.         // 判断是否为全角  
  843.   
  844.         if (Pattern.compile("[\u4e00-\u9fa5]+$").matcher(charStr).matches()) {  
  845.             return 2;  
  846.         }  
  847.         //全角符号 及中文  
  848.         if (Pattern.compile("[^x00-xff]").matcher(charStr).matches()) {  
  849.             return 2;  
  850.         }  
  851.         return 1;  
  852.   
  853.     }  
  854.   
  855.       
  856.     /** 
  857.      * @param args 
  858.      * @throws Exception 
  859.      */  
  860.     public static void main(String[] args) throws Exception {  
  861.   
  862.         Map<String, String> replaceTextMap = new HashMap<String, String>();  
  863.         replaceTextMap.put("#寄单地址""[寄单地址厂商编号厂商编号厂商编号厂商编号厂商编号厂商编号厂商编号]");  
  864.         replaceTextMap.put("#厂商编号""[厂商编号厂商编号厂商编号厂商编号厂商编号厂商编号厂商编号厂商编号]");  
  865.         replaceTextMap.put("#厂商名称""[厂商名称厂商编号厂商编号厂商编号厂商编号厂商编号厂商编号厂商编号]");  
  866.   
  867.         Workbook wb = readExcel("F:\\PO差异报表.xls");  
  868.         Sheet sheet = wb.getSheetAt(0);  
  869.         replaceHeader(sheet, replaceTextMap);  
  870.           
  871.         List<Map<String, String>> detailList = new ArrayList<Map<String,String>>();  
  872.         Map<String,String> detailMap = new TreeMap<String, String>();  
  873.         detailMap.put("ID11""厂商编号");  
  874.         detailMap.put("ID12""厂商编号");  
  875.         detailMap.put("ID13""厂商编号厂商编号厂商编号厂商编号厂商编号厂商编号厂商编号");  
  876.         detailMap.put("ID14""ID14");  
  877.         detailMap.put("ID15""ID15");  
  878.         detailMap.put("ID16""ID16");  
  879.         detailList.add(detailMap);  
  880.         detailMap = new TreeMap<String, String>();  
  881.         detailMap.put("ID21""ID21");  
  882.         detailMap.put("ID22""ID22");  
  883.         detailMap.put("ID23""ID23");  
  884.         detailMap.put("ID24""ID24");  
  885.         detailMap.put("ID25""ID25");  
  886.         detailMap.put("ID26""ID26");  
  887.         detailList.add(detailMap);  
  888.         replaceDetail(wb, sheet, "#detail", detailList);  
  889.         replaceDetail(wb, sheet, "#detail1", detailList);  
  890.         createExcel(wb, "F:\\PO差异报表_replace.xls");  
  891.   
  892.     }  
  893.       
  894. }  
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值