In this article, I am going to explain how to merge two excel files. Some time we may need to do excel merging programmitically. If you want to do any modification by logic in merging, you can do using this program easily. To implement this program you need to download Apache POI library and have it in your build path (copy POI jars to lib folder).
There is no direct method to merge excel files using java. You have need to follow the below flow.
Click Here To Download Eclipse Project

Flow of the program

  1. Get Excel files
  2. Get Work Books of those excel files
  3. Get sheets to be merged in those excel files
  4. Read every row and add it to other sheet
  5. Read every cell and add it to the row
  6. Write merged workbook to output file

Java Code

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class MergeExcel {

    public static void main(String[] args) {
        try {
            // excel files
            FileInputStream excellFile1 = new FileInputStream(new File(
            FileInputStream excellFile2 = new FileInputStream(new File(

            // Create Workbook instance holding reference to .xlsx file
            XSSFWorkbook workbook1 = new XSSFWorkbook(excellFile1);
            XSSFWorkbook workbook2 = new XSSFWorkbook(excellFile2);

            // Get first/desired sheet from the workbook
            XSSFSheet sheet1 = workbook1.getSheetAt(0);
            XSSFSheet sheet2 = workbook2.getSheetAt(0);

            // add sheet2 to sheet1
            addSheet(sheet1, sheet2);

            // save merged file
            File mergedFile = new File(
            if (!mergedFile.exists()) {
            FileOutputStream out = new FileOutputStream(mergedFile);
                    .println("Files were merged succussfully");
        } catch (Exception e) {


    public static void addSheet(XSSFSheet mergedSheet, XSSFSheet sheet) {
        // map for cell styles
        Map<Integer, XSSFCellStyle> styleMap = new HashMap<Integer, XSSFCellStyle>();
        // This parameter is for appending sheet rows to mergedSheet in the end
        int len = mergedSheet.getLastRowNum();
        for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {

            XSSFRow row = sheet.getRow(j);
            XSSFRow mrow = mergedSheet.createRow(len + j + 1);

            for (int k = row.getFirstCellNum(); k < row.getLastCellNum(); k++) {
                XSSFCell cell = row.getCell(k);
                XSSFCell mcell = mrow.createCell(k);

                if (cell.getSheet().getWorkbook() == mcell.getSheet()
                        .getWorkbook()) {
                } else {
                    int stHashCode = cell.getCellStyle().hashCode();
                    XSSFCellStyle newCellStyle = styleMap.get(stHashCode);
                    if (newCellStyle == null) {
                        newCellStyle = mcell.getSheet().getWorkbook()
                        styleMap.put(stHashCode, newCellStyle);

                switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_FORMULA:
                case HSSFCell.CELL_TYPE_NUMERIC:
                case HSSFCell.CELL_TYPE_STRING:
                case HSSFCell.CELL_TYPE_BLANK:
                case HSSFCell.CELL_TYPE_BOOLEAN:
                case HSSFCell.CELL_TYPE_ERROR:


  1. Hi,
    Can we merge .xlsx and .xls file into one file??

  2. Does this merge tabels based on common key?
    e.g. Suppose this:
    FirstTable.xls which contains columns as: UserID, FirstName, LastName
    SecondTable.xls which contains columns as: UserID, Description
    Now my question is that does your program merge these 2 tables based on UserID or not?

  3. Hi,
    Nice Post for merge Excel Sheet. I think everyone can not write JAVA Code for Merging Excel Sheet. You Can use synkronizer Excel Tool for Update, Merge and compare excel sheet files.


  4. It merges the files but not all headers in row 1. It reads first sheet and put it in output file and then it read another sheet and put the content from second below the first sheet content in the output file. Cn you please help me so that I can have all the content from left to right

  5. Thanks for sharing This Blog on How to Merge Excel files using java. it's really useful and information blog post. I Think you can also use Synkronizer Excel tool for merge multiple excel file. using this tool, No need to write any JAVA or VBA script. Keep Sharing Good Content on your blog.

  6. Thanks for sharing.
    I was stuck but finally got solution from your blog

  7. Can you please give solution to merge multiple excel sheets
    Thanks in advance

  8. Its giving null pointer exception. plz help

  9. Are you the one who studies this subject?? I have a headache with this subject.카지노사이트Looking at your writing was very helpful.

  10. I need you to thank for your season of this awesome 먹튀검증!!! I definately appreciate each and every piece of it and I have you bookmarked to look at new stuff of your blog an absolute necessity read blog!!!!

  11. I am overwhelmed by your post with such a nice topic. Usually I visit your 메이저토토사이트 and get updated through the information you include but today’s blog would be the most appreciable. Well done!

  12. Good blog.Are you also searching for Help With My Nursing Paper? we are the best solution for you. We are best known for delivering nursing writing services to students without having to break the bank.

  13. I want to always read your blogs. I love them Are you also searching for Nursing Pico Writing Help? we are the best solution for you. We are best known for delivering Nursing Pico writing services to students without having to break the bank

  14. I would like to thank you for the efforts you have put in penning this site. I’m hoping to view the same high-grade content by you later on as well. In truth, your creative writing abilities has motivated me to get my own, personal website now. 사설놀이터

  15. Hi there, I simply hopped over in your website by way of StumbleUpon. Now not one thing I’d typically learn, but I favored your emotions none the less. Thank you for making something worth reading. 먹튀검증업체

  16. I am constantly surprised by the amount of information accessible on this subject. What you presented was well researched and well written to get your stand on this over to all your readers. Thanks a lot my dear. 토토사이트

  17. I'm so happy to finally find a post with what I want. 안전놀이터순위 You have inspired me a lot. If you are satisfied, please visit my website and leave your feedback.

  18. Of course, your article is good enough, but I thought it would be much better to see professional photos and videos together. There are articles and photos on these topics on my homepage, so please visit and share your opinions. keonhacai

  19. Good day! This post could not be written any better! Reading this post reminds me of my previous room mate! He always kept chatting about this. I will forward this page to him. Pretty sure he will have a good read. Thanks for sharing. 안전사이트

  20. I am sure this article has touched all the internet people, its really really nice post on building up new webpage. Also, visit my site 토토사이트

  21. Howdy terrific blog! Does running a blog like this take a massive amount work? I have virtually no understanding of coding however I had been hoping to start my
    own blog soon. 경마

  22. Wow, fantastic weblog structure! How long have you evver been running a blog for?
    you made blogging look easy. The total glance of our web site is magnificent, as well as the content!

  23. I actually can´t help activities here. Thank you for time properly spent looking over this article. I can´t bear in mind the last moment I´ve bookmarked
    anything. 사설토토

  24. Thank you for any other informative blog. Where else may just I am getting that kind of information written in such a perfect method? I have a mission that I’m simply now working on, and I have been on the glance out for such info. 안전놀이터추천

  25. The vacation trades offered are evaluated a variety of in the chosen and simply good value all around the world. Those hostels are normally based towards households which you’ll find accented via charming shores promoting crystal-clear fishing holes, concurrent of one’s Ocean. Hotels Discounts 메이저사이트

  26. Hey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you. 먹튀검증 and I am very happy to see your post just in time and it was a great help. Thank you ! Leave your blog address below. Please visit me anytime!

  27. Succeed! It could be one of the most useful blogs we have ever come across on the subject. Excellent info! I’m also an expert in this topic so I can understand your effort very well. Thanks for the huge help. 먹튀검증사이트

  28. Your internet site really feels a great deal of expert touch. I'm still an amateur, so I wish to speak to a professional. My writing is still unsatisfactory, however I desire you to evaluate me by my writing. Please do that for us. 바카라사이트

  29. I always think about what is. It seems to be a perfect article that seems to blow away such worries. 먹튀검증사이트 seems to be the best way to show something. When you have time, please write an article about what means!!

  30. Good morning!! I am also blogging with you. In my blog, articles related to are mainly written, and they are usually called 메이저사이트. If you are curious about , please visit!!

  31. In my opinion, the item you posted is perfect for being selected as the best item of the year. You seem to be a genius to combine 먹튀사이트 and . Please think of more new items in the future!



Popular Posts