Tuesday, 17 November 2015

Apache POI - Pivot Table Creation Example

import java.io.FileOutputStream;
import java.io.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.xssf.usermodel.*;
import java.util.*;
public class createxlsx {  
        public static void main(String[] args) throws Exception{
                /* Apache POI Create Pivot Table Example Program */
                /* Step -1: Create a workbook object to start with */
                XSSFWorkbook new_workbook = new XSSFWorkbook(); //create a blank workbook object
                /* Create a worksheet in the workbook. We will name it "Pivot Table Example" */
                XSSFSheet sheet = new_workbook.createSheet("Pivot Table Example");  //create a worksheet with caption score_details
                /* Add some Rows and Columns to explain Pivot Table  */         
                /* Create the Header Row */
                Row row1 = sheet.createRow(0);                
                Cell cell11 = row1.createCell(0);
                cell11.setCellValue("Student");
                Cell cell12 = row1.createCell(1);
                cell12.setCellValue("Subject");
                Cell cell13 = row1.createCell(2);
                cell13.setCellValue("Score");
                /* Row #1 */
                Row row2 = sheet.createRow(1);
                Cell cell21 = row2.createCell(0);
                cell21.setCellValue("Matt");
                Cell cell22 = row2.createCell(1);
                cell22.setCellValue("English");
                Cell cell23 = row2.createCell(2);
                cell23.setCellValue(67);
                /* Row #2 */
                Row row3 = sheet.createRow(2);
                Cell cell31 = row3.createCell(0);
                cell31.setCellValue("Pitt");
                Cell cell32 = row3.createCell(1);
                cell32.setCellValue("English");
                Cell cell33 = row3.createCell(2);
                cell33.setCellValue(90);
                /* Row #3 */
                Row row4 = sheet.createRow(3);
                Cell cell41 = row4.createCell(0);
                cell41.setCellValue("Pitt");
                Cell cell42 = row4.createCell(1);
                cell42.setCellValue("Biology");
                Cell cell43 = row4.createCell(2);
                cell43.setCellValue(90);
                /* Row #4 */
                Row row5 = sheet.createRow(4);
                Cell cell51 = row5.createCell(0);
                cell51.setCellValue("Matt");
                Cell cell52 = row5.createCell(1);
                cell52.setCellValue("Physics");
                Cell cell53 = row5.createCell(2);
                cell53.setCellValue(99);
                /* Define an Area Reference for the Pivot Table */
                AreaReference a=new AreaReference("A1:C5");
                /* Define the starting Cell Reference for the Pivot Table */
                CellReference b=new CellReference("I5");
                /* Create the Pivot Table */
                XSSFPivotTable pivotTable = sheet.createPivotTable(a,b);
                /* First Create Report Filter - We want to filter Pivot Table by Student Name */
                pivotTable.addReportFilter(0);
                 /* Second - Row Labels - Once a student is filtered all subjects to be displayed in pivot table */
                pivotTable.addRowLabel(1);
                /* Define Column Label with Function, Sum of the marks obtained */
                pivotTable.addColumnLabel(DataConsolidateFunction.SUM, 2);                
                /* Write output to file */ 
                FileOutputStream output_file = new FileOutputStream(new File("POI_Pivot_Example.xlsx")); //create XLSX file
                new_workbook.write(output_file);//write excel document to output stream
                output_file.close(); //close the file
        }
}





Monday, 16 November 2015


import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Vector;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

/**
 *
 * @author Ranjeet Singh
 */
public class Operations {

    private static Operations op = new Operations();

    private Operations() {
    }

    public static Operations getInstance() {
        return op;
    }

    public Vector getFilesListData(String rawFolder, String splitString, int sheetNumber) {
        try {
       
       
       
            FileFilter filter = new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    if (pathname.toString().contains(".xls")) {
                        return pathname.isFile();
                    } else {
                        return false;
                    }
                }
            };
            File f = new File(rawFolder);
            File arr1[] = f.listFiles(filter);
            jxl.Workbook wb;
            int totalRows;
            jxl.Sheet sh;
            Vector list = new Vector();

            String st;
            for (int i = 0; i < arr1.length; i++) {
                try {
                    wb = jxl.Workbook.getWorkbook(arr1[i]);
                    sh = wb.getSheet(sheetNumber);
                    totalRows = sh.getRows();
                    for (int row = 0; row < totalRows; row++) {

                        if (row == 0 && i >= 1) {
                            continue;
                        }
                        st = "";
                        for (int col = 0; col < sh.getColumns(); col++) {
                            st += splitString + sh.getCell(col, row).getContents();
                        }


                        list.add(st);
                    }

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return list;

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public void writaData(String fileName, String sheetName, Vector list, String splitString, int bufferRows) {
        try {
            String object, arr[];
            SXSSFWorkbook wwb = new SXSSFWorkbook(bufferRows);
            Sheet wsh = wwb.createSheet();
            int row = 0;
            Row excelRow;
            System.out.println("List Size" + list.size());
            list.trimToSize();
            for (int i = 0; i < list.size(); i++) {
                excelRow = wsh.createRow(row++);
                object = list.get(i).toString();
                arr = object.split(splitString);
                for (int ii = 1; ii < arr.length; ii++) {
                    try {
                        excelRow.createCell(ii - 1).setCellValue(Long.parseLong(arr[ii]));
                    } catch (NumberFormatException ee) {
                        excelRow.createCell(ii - 1).setCellValue(arr[ii]);
                    }
                }
            }
            wwb.write(new FileOutputStream(new File(fileName)));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String args[]) {
        Operations op = Operations.getInstance();
        Vector l = op.getFilesListData("Raw data/dump", "#", 0);
        op.writaData("aaa.xlsx", "Sheet1", l, "#", 1000);

    }


}

Thursday, 12 November 2015

This solution is for copy excels, It will merged the whole sourcecode from here.


import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

public class CopySheets {

public HSSFWorkbook mergeExcelFiles(HSSFWorkbook book, List<FileInputStream> inList) throws IOException {

    for (FileInputStream fin : inList) {
        HSSFWorkbook b = new HSSFWorkbook(fin);
        for (int i = 0; i < b.getNumberOfSheets(); i++) {
            // not entering sheet name, because of duplicated names
            copySheets(book.createSheet(),b.getSheetAt(i));
        }
    }
    return book;
}

/** 
 * @param newSheet the sheet to create from the copy. 
 * @param sheet the sheet to copy. 
 */  
public static void copySheets(HSSFSheet newSheet, HSSFSheet sheet){     
    copySheets(newSheet, sheet, true);     
}     

/** 
 * @param newSheet the sheet to create from the copy. 
 * @param sheet the sheet to copy. 
 * @param copyStyle true copy the style. 
 */  
public static void copySheets(HSSFSheet newSheet, HSSFSheet sheet, boolean copyStyle){     
    int maxColumnNum = 0;     
    Map<Integer, HSSFCellStyle> styleMap = (copyStyle) ? new HashMap<Integer, HSSFCellStyle>() : null;     
    for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {     
        HSSFRow srcRow = sheet.getRow(i);     
        HSSFRow destRow = newSheet.createRow(i);     
        if (srcRow != null) {     
            copyRow(sheet, newSheet, srcRow, destRow, styleMap);     
            if (srcRow.getLastCellNum() > maxColumnNum) {     
                maxColumnNum = srcRow.getLastCellNum();     
            }     
        }     
    }     
    for (int i = 0; i <= maxColumnNum; i++) {     
        newSheet.setColumnWidth(i, sheet.getColumnWidth(i));     
    }     
}     

/** 
 * @param srcSheet the sheet to copy. 
 * @param destSheet the sheet to create. 
 * @param srcRow the row to copy. 
 * @param destRow the row to create. 
 * @param styleMap - 
 */  
public static void copyRow(HSSFSheet srcSheet, HSSFSheet destSheet, HSSFRow srcRow, HSSFRow destRow, Map<Integer, HSSFCellStyle> styleMap) {     
    // manage a list of merged zone in order to not insert two times a merged zone  
  Set<CellRangeAddressWrapper> mergedRegions = new TreeSet<CellRangeAddressWrapper>();     
    destRow.setHeight(srcRow.getHeight());     
    // reckoning delta rows  
    int deltaRows = destRow.getRowNum()-srcRow.getRowNum();  
    // pour chaque row  
    for (int j = srcRow.getFirstCellNum(); j <= srcRow.getLastCellNum(); j++) {     
        HSSFCell oldCell = srcRow.getCell(j);   // ancienne cell  
        HSSFCell newCell = destRow.getCell(j);  // new cell   
        if (oldCell != null) {     
            if (newCell == null) {     
                newCell = destRow.createCell(j);     
            }     
            // copy chaque cell  
            copyCell(oldCell, newCell, styleMap);     
            // copy les informations de fusion entre les cellules  
            //System.out.println("row num: " + srcRow.getRowNum() + " , col: " + (short)oldCell.getColumnIndex());  
            CellRangeAddress mergedRegion = getMergedRegion(srcSheet, srcRow.getRowNum(), (short)oldCell.getColumnIndex());     

            if (mergedRegion != null) {   
              //System.out.println("Selected merged region: " + mergedRegion.toString());  
              CellRangeAddress newMergedRegion = new CellRangeAddress(mergedRegion.getFirstRow()+deltaRows, mergedRegion.getLastRow()+deltaRows, mergedRegion.getFirstColumn(),  mergedRegion.getLastColumn());  
                //System.out.println("New merged region: " + newMergedRegion.toString());  
                CellRangeAddressWrapper wrapper = new CellRangeAddressWrapper(newMergedRegion);  
                if (isNewMergedRegion(wrapper, mergedRegions)) {  
                    mergedRegions.add(wrapper);  
                    destSheet.addMergedRegion(wrapper.range);     
                }     
            }     
        }     
    }                
}    

/** 
 * @param oldCell 
 * @param newCell 
 * @param styleMap 
 */  
public static void copyCell(HSSFCell oldCell, HSSFCell newCell, Map<Integer, HSSFCellStyle> styleMap) {     
    if(styleMap != null) {     
        if(oldCell.getSheet().getWorkbook() == newCell.getSheet().getWorkbook()){     
            newCell.setCellStyle(oldCell.getCellStyle());     
        } else{     
            int stHashCode = oldCell.getCellStyle().hashCode();     
            HSSFCellStyle newCellStyle = styleMap.get(stHashCode);     
            if(newCellStyle == null){     
                newCellStyle = newCell.getSheet().getWorkbook().createCellStyle();     
                newCellStyle.cloneStyleFrom(oldCell.getCellStyle());     
                styleMap.put(stHashCode, newCellStyle);     
            }     
            newCell.setCellStyle(newCellStyle);     
        }     
    }     
    switch(oldCell.getCellType()) {     
        case HSSFCell.CELL_TYPE_STRING:     
            newCell.setCellValue(oldCell.getStringCellValue());     
            break;     
      case HSSFCell.CELL_TYPE_NUMERIC:     
            newCell.setCellValue(oldCell.getNumericCellValue());     
            break;     
        case HSSFCell.CELL_TYPE_BLANK:     
            newCell.setCellType(HSSFCell.CELL_TYPE_BLANK);     
            break;     
        case HSSFCell.CELL_TYPE_BOOLEAN:     
            newCell.setCellValue(oldCell.getBooleanCellValue());     
            break;     
        case HSSFCell.CELL_TYPE_ERROR:     
            newCell.setCellErrorValue(oldCell.getErrorCellValue());     
            break;     
        case HSSFCell.CELL_TYPE_FORMULA:     
            newCell.setCellFormula(oldCell.getCellFormula());     
            break;     
        default:     
            break;     
    }     

}     

/** 
 * Récupère les informations de fusion des cellules dans la sheet source pour les appliquer 
 * à la sheet destination... 
 * Récupère toutes les zones merged dans la sheet source et regarde pour chacune d'elle si 
 * elle se trouve dans la current row que nous traitons. 
 * Si oui, retourne l'objet CellRangeAddress. 
 *  
 * @param sheet the sheet containing the data. 
 * @param rowNum the num of the row to copy. 
 * @param cellNum the num of the cell to copy. 
 * @return the CellRangeAddress created. 
 */  
public static CellRangeAddress getMergedRegion(HSSFSheet sheet, int rowNum, short cellNum) {     
    for (int i = 0; i < sheet.getNumMergedRegions(); i++) {   
        CellRangeAddress merged = sheet.getMergedRegion(i);     
        if (merged.isInRange(rowNum, cellNum)) {     
            return merged;     
        }     
    }     
    return null;     
}     

/** 
 * Check that the merged region has been created in the destination sheet. 
 * @param newMergedRegion the merged region to copy or not in the destination sheet. 
 * @param mergedRegions the list containing all the merged region. 
 * @return true if the merged region is already in the list or not. 
 */  
private static boolean isNewMergedRegion(CellRangeAddressWrapper newMergedRegion, Set<CellRangeAddressWrapper> mergedRegions) {  
  return !mergedRegions.contains(newMergedRegion);     
}     

}
class CellRangeAddressWrapper implements Comparable<CellRangeAddressWrapper> {  

public CellRangeAddress range;  

/** 
 * @param theRange the CellRangeAddress object to wrap. 
 */  
public CellRangeAddressWrapper(CellRangeAddress theRange) {  
      this.range = theRange;  
}  

/** 
 * @param o the object to compare. 
 * @return -1 the current instance is prior to the object in parameter, 0: equal, 1: after... 
 */  
public int compareTo(CellRangeAddressWrapper o) {  

            if (range.getFirstColumn() < o.range.getFirstColumn()  
                        && range.getFirstRow() < o.range.getFirstRow()) {  
                  return -1;  
            } else if (range.getFirstColumn() == o.range.getFirstColumn()  
                        && range.getFirstRow() == o.range.getFirstRow()) {  
                  return 0;  
            } else {  
                  return 1;  
            }  

}  

}