Sunday, 7 May 2017

Java program to Merge two Excel sheets

This program has been taken from the below link and enhanced for easy use and easy understanding. This program is working 100% and the result is accurate.
Jars used: poi.jar

https://coderanch.com/t/614715/java/merge-excel-files - Thanks for the program

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
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.hssf.util.CellRangeAddress;


@SuppressWarnings("deprecation")
public class MSExcel {
 public static void main(String args[]) throws FileNotFoundException{
  MSExcel mslobj = new MSExcel();
  mslobj.readExcel();
 }

 private void readExcel() {
  // TODO Auto-generated method stub
  try {
   String FilePath = "C:\\Users\\test.xls";
   String FilePath1 = "C:\\Users\\test1.xls";
   FileInputStream fis = new FileInputStream(FilePath);
   FileInputStream fis1 = new FileInputStream(FilePath1);
   HSSFWorkbook workbook = new HSSFWorkbook(fis);
   HSSFSheet sheet = workbook.getSheet(“sheet”);
 
   HSSFWorkbook wb = new HSSFWorkbook(fis1);
   //Workbook wb = new XSSFWorkbook();
   HSSFSheet sheet1 = wb.getSheet(“sheet1”);
   copySheets(sheet1, sheet);
 
   FileOutputStream outfile = new FileOutputStream("C:\\Users\\test1.xls");
   wb.write(outfile);
   outfile.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
 
  public static void copySheets(HSSFSheet newSheet, HSSFSheet sheet){
    copySheets(newSheet, sheet, true);
  }
     
       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) {
                   MSExcel.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));
           }
       }
 
       public static void copyRow(HSSFSheet srcSheet, HSSFSheet destSheet, HSSFRow srcRow, HSSFRow destRow, Map<Integer, HSSFCellStyle> styleMap) {
           @SuppressWarnings("deprecation")
     Set<CellRangeAddress> mergedRegions = new TreeSet<CellRangeAddress>();
           destRow.setHeight(srcRow.getHeight());
           for (int j = srcRow.getFirstCellNum(); j <= srcRow.getLastCellNum(); j++) {
               HSSFCell oldCell = srcRow.getCell(j);
               HSSFCell newCell = destRow.getCell(j);
               if (oldCell != null) {
                   if (newCell == null) {
                       newCell = destRow.createCell(j);
                   }
                   copyCell(oldCell, newCell, styleMap);
                   CellRangeAddress mergedRegion = getMergedRegion(srcSheet, srcRow.getRowNum(), (short)oldCell.getColumnIndex());
                   if (mergedRegion != null) {
                       CellRangeAddress newMergedRegion = new CellRangeAddress(mergedRegion.getFirstRow(), mergedRegion.getFirstColumn(), mergedRegion.getLastRow(), mergedRegion.getLastColumn());
                       if (isNewMergedRegion(newMergedRegion, mergedRegions)) {
                           mergedRegions.add(newMergedRegion);
                           destSheet.addMergedRegion(newMergedRegion);
                       }
                   }
               }
           }
         
       }
     
       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;
           }
         
       }
     
       public static CellRangeAddress getMergedRegion(HSSFSheet sheet, int rowNum, short cellNum) {
           for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
               CellRangeAddress merged = (CellRangeAddress) sheet.getMergedRegion(i);
               if (merged.isInRange(rowNum, cellNum)) {
                   return merged;
               }
           }
           return null;
       }
 
       private static boolean isNewMergedRegion(CellRangeAddress newMergedRegion, Collection<CellRangeAddress> mergedRegions) {
           return !mergedRegions.contains(newMergedRegion);
       }
     
 }

9 comments:

  1. How to merge if there are more than 2 excel files?

    ReplyDelete
  2. Hi Akhila, hope you are well. Can you please let me know whether you are trying to merge more than two excel files or sheets ?

    ReplyDelete
  3. Let us begin with Information Technology. Gone are the days when people melted for fear of where to get information or data for their usage. Whatever information you think you need has been well written out for you on the Internet. caledon houses for sale

    ReplyDelete
  4. Technology has enabled people in different geographical locations all over the world to virtually meet, communicate and also seal deals using conference calling, video conferencing and Skype all with the help of the Internet. combination weigher

    ReplyDelete
  5. . Not all nations on the planet utilize the standard 900/1,800 MHz GSM. The exemptions being, Canada, Mexico, Japan, Korea, and some Central/South American nations, with some restricted inclusion of the standard GSM organizations. dumps plus pin

    ReplyDelete
  6. However, with bank check card fraud, the cash has been eliminated straightforwardly from your record - and you won't get that cash back until the fraud guarantee is settled. Dumps cvv

    ReplyDelete
  7. This potential boundless risk implies that it is essential to report fraud rapidly. In the event that you think you've lost your card, or suspect a fraudulent utilization of your card, report it right away. credit card skimmer for sale

    ReplyDelete
  8. Technology alludes to the assortment of devices that make it simpler to utilize, make, oversee and trade data. mobile tracker free

    ReplyDelete
  9. There are numerous aspects to being mindful. Most importantly a decent stable tech will take care of the requirements of the architect. Being mindful methods focusing.why you should use a vpn on a streaming website

    ReplyDelete

Expense Handler Application with advance technologies

Budget Planner  One of the application developed with Ionic 4 and Python-Flask.  Ionic 4 code:  https://github.com/logeshbuiltin/Expense...