eriezelagera

Create Excel - JXLSUtil

Jul 29th, 2014
597
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.05 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;  
  3. import org.apache.poi.ss.util.CellRangeAddress;  
  4. import org.apache.poi.xssf.usermodel.*;
  5.          
  6. /**  
  7.  *  
  8.  * @author jk  
  9.  * getted from http://jxls.cvs.sourceforge.net/jxls/jxls/src/java/org/jxls/util/Util.java?revision=1.8&view=markup  
  10.  * by Leonid Vysochyn    
  11.  * and modified (adding styles copying)  
  12.  * modified by Philipp Löpmeier (replacing deprecated classes and methods, using generic types)  
  13.  */    
  14. public final class JXLSUtil {    
  15.  
  16.     /**
  17.      * DEFAULT CONSTRUCTOR.
  18.      */  
  19.     private JXLSUtil() {
  20.     }
  21.  
  22.     public static XSSFWorkbook mergeExcelFiles(XSSFWorkbook new_workbook, XSSFWorkbook workbook, String sheet_name) throws IOException {
  23.         for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
  24.             // not entering sheet name, because of duplicated names
  25.             copySheets(new_workbook.createSheet(sheet_name), workbook.getSheetAt(i));
  26.         }
  27.         return new_workbook;
  28.     }
  29.    
  30.     /**
  31.      * @param newSheet the sheet to create from the copy.
  32.      * @param sheet the sheet to copy.
  33.      */  
  34.     public static void copySheets(XSSFSheet newSheet, XSSFSheet sheet){    
  35.         copySheets(newSheet, sheet, true);    
  36.     }    
  37.  
  38.     /**
  39.      * @param newSheet the sheet to create from the copy.
  40.      * @param sheet the sheet to copy.
  41.      * @param copyStyle true copy the style.
  42.      */  
  43.     public static void copySheets(XSSFSheet newSheet, XSSFSheet sheet, boolean copyStyle){    
  44.         int maxColumnNum = 0;    
  45.         Map<Integer, XSSFCellStyle> styleMap = (copyStyle) ? new HashMap<Integer, XSSFCellStyle>() : null;    
  46.         for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {    
  47.             XSSFRow srcRow = sheet.getRow(i);    
  48.             XSSFRow destRow = newSheet.createRow(i);    
  49.             if (srcRow != null) {    
  50.                 JXLSUtil.copyRow(sheet, newSheet, srcRow, destRow, styleMap);    
  51.                 if (srcRow.getLastCellNum() > maxColumnNum) {    
  52.                     maxColumnNum = srcRow.getLastCellNum();    
  53.                 }    
  54.             }    
  55.         }    
  56.         for (int i = 0; i <= maxColumnNum; i++) {    
  57.             newSheet.setColumnWidth(i, sheet.getColumnWidth(i));    
  58.         }    
  59.     }    
  60.  
  61.     /**
  62.      * @param srcSheet the sheet to copy.
  63.      * @param destSheet the sheet to create.
  64.      * @param srcRow the row to copy.
  65.      * @param destRow the row to create.
  66.      * @param styleMap -
  67.      */  
  68.     public static void copyRow(XSSFSheet srcSheet, XSSFSheet destSheet, XSSFRow srcRow, XSSFRow destRow, Map<Integer, XSSFCellStyle> styleMap) {    
  69.         // manage a list of merged zone in order to not insert two times a merged zone  
  70.       Set<CellRangeAddressWrapper> mergedRegions = new TreeSet<>();    
  71.         destRow.setHeight(srcRow.getHeight());    
  72.         // pour chaque row  
  73.         for (int j = srcRow.getFirstCellNum(); j <= srcRow.getLastCellNum(); j++) {    
  74.             XSSFCell oldCell = srcRow.getCell(j);   // ancienne cell  
  75.             XSSFCell newCell = destRow.getCell(j);  // new cell  
  76.             if (oldCell != null) {    
  77.                 if (newCell == null) {    
  78.                     newCell = destRow.createCell(j);    
  79.                 }    
  80.                 // copy chaque cell  
  81.                 copyCell(oldCell, newCell, styleMap);    
  82.                 // copy les informations de fusion entre les cellules  
  83.                 //System.out.println("row num: " + srcRow.getRowNum() + " , col: " + (short)oldCell.getColumnIndex());  
  84.                 CellRangeAddress mergedRegion = getMergedRegion(srcSheet, srcRow.getRowNum(), (short)oldCell.getColumnIndex());    
  85.  
  86.                 if (mergedRegion != null) {  
  87.                   //System.out.println("Selected merged region: " + mergedRegion.toString());  
  88.                   CellRangeAddress newMergedRegion = new CellRangeAddress(mergedRegion.getFirstRow(), mergedRegion.getLastRow(), mergedRegion.getFirstColumn(),  mergedRegion.getLastColumn());  
  89.                     //System.out.println("New merged region: " + newMergedRegion.toString());  
  90.                     CellRangeAddressWrapper wrapper = new CellRangeAddressWrapper(newMergedRegion);  
  91.                     if (isNewMergedRegion(wrapper, mergedRegions)) {  
  92.                         mergedRegions.add(wrapper);  
  93.                         destSheet.addMergedRegion(wrapper.range);    
  94.                     }    
  95.                 }    
  96.             }    
  97.         }    
  98.  
  99.     }    
  100.  
  101.     /**
  102.      * @param oldCell
  103.      * @param newCell
  104.      * @param styleMap
  105.      */  
  106.     public static void copyCell(XSSFCell oldCell, XSSFCell newCell, Map<Integer, XSSFCellStyle> styleMap) {    
  107.         if(styleMap != null) {    
  108.             if(oldCell.getSheet().getWorkbook() == newCell.getSheet().getWorkbook()){    
  109.                 newCell.setCellStyle(oldCell.getCellStyle());    
  110.             } else{    
  111.                 int stHashCode = oldCell.getCellStyle().hashCode();    
  112.                 XSSFCellStyle newCellStyle = styleMap.get(stHashCode);    
  113.                 if(newCellStyle == null){    
  114.                     newCellStyle = newCell.getSheet().getWorkbook().createCellStyle();    
  115.                     newCellStyle.cloneStyleFrom(oldCell.getCellStyle());    
  116.                     styleMap.put(stHashCode, newCellStyle);    
  117.                 }    
  118.                 newCell.setCellStyle(newCellStyle);    
  119.             }    
  120.         }    
  121.         switch(oldCell.getCellType()) {    
  122.             case XSSFCell.CELL_TYPE_STRING:    
  123.                 newCell.setCellValue(oldCell.getStringCellValue());    
  124.                 break;    
  125.           case XSSFCell.CELL_TYPE_NUMERIC:    
  126.                 newCell.setCellValue(oldCell.getNumericCellValue());    
  127.                 break;    
  128.             case XSSFCell.CELL_TYPE_BLANK:    
  129.                 newCell.setCellType(XSSFCell.CELL_TYPE_BLANK);    
  130.                 break;    
  131.             case XSSFCell.CELL_TYPE_BOOLEAN:    
  132.                 newCell.setCellValue(oldCell.getBooleanCellValue());    
  133.                 break;    
  134.             case XSSFCell.CELL_TYPE_ERROR:    
  135.                 newCell.setCellErrorValue(oldCell.getErrorCellValue());    
  136.                 break;    
  137.             case XSSFCell.CELL_TYPE_FORMULA:    
  138.                 newCell.setCellFormula(oldCell.getCellFormula());    
  139.                 break;    
  140.             default:    
  141.                 break;    
  142.         }    
  143.  
  144.     }    
  145.  
  146.     /**
  147.      * Récupère les informations de fusion des cellules dans la sheet source pour les appliquer
  148.      * à la sheet destination...
  149.      * Récupère toutes les zones merged dans la sheet source et regarde pour chacune d'elle si
  150.      * elle se trouve dans la current row que nous traitons.
  151.      * Si oui, retourne l'objet CellRangeAddress.
  152.      *  
  153.      * @param sheet the sheet containing the data.
  154.      * @param rowNum the num of the row to copy.
  155.      * @param cellNum the num of the cell to copy.
  156.      * @return the CellRangeAddress created.
  157.      */  
  158.     public static CellRangeAddress getMergedRegion(XSSFSheet sheet, int rowNum, short cellNum) {    
  159.         for (int i = 0; i < sheet.getNumMergedRegions(); i++) {  
  160.             CellRangeAddress merged = sheet.getMergedRegion(i);    
  161.             if (merged.isInRange(rowNum, cellNum)) {    
  162.                 return merged;    
  163.             }    
  164.         }    
  165.         return null;    
  166.     }    
  167.  
  168.     /**
  169.      * Check that the merged region has been created in the destination sheet.
  170.      * @param newMergedRegion the merged region to copy or not in the destination sheet.
  171.      * @param mergedRegions the list containing all the merged region.
  172.      * @return true if the merged region is already in the list or not.
  173.      */  
  174.     private static boolean isNewMergedRegion(CellRangeAddressWrapper newMergedRegion, Set<CellRangeAddressWrapper> mergedRegions) {  
  175.       return !mergedRegions.contains(newMergedRegion);    
  176.     }    
  177.  
  178. }
Advertisement
Add Comment
Please, Sign In to add comment