Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8783333
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T20:48:21+00:00 2026-06-13T20:48:21+00:00

How can I copy a sheet between two different workbooks in Apache poi? The

  • 0

How can I copy a sheet between two different workbooks in Apache poi?

The method is missing referring this thread. There is not such a solution.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T20:48:23+00:00Added an answer on June 13, 2026 at 8:48 pm

    After a researching and trying, here my solution. I was tested with java 1.6 and apache-poi 3.8

    here i wan’t to provide the solution worked for me, special in this case, i pas a worksheet and a List of input streams (different workbooks i want to merge).

    My solution is a merged one, i’ve got merged the whole sourcecode from here i want to share this code with everyone, stuck on the same problem.

    /**
    * Original version available from:
    * http://www.coderanch.com/t/420958/open-source/Copying-sheet-excel-file-another
    **/
    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.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.CellStyle;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.WorkbookFactory;
    import org.apache.poi.ss.util.CellRangeAddress;
    
    public class CopySheets {
    
    public Workbook mergeExcelFiles(Workbook book, List<InputStream> inList) throws IOException {
    
        for (InputStream fin : inList) {
            Workbook b = WorkbookFactory.create(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(Sheet newSheet, Sheet 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(Sheet newSheet, Sheet sheet, boolean copyStyle){     
        int maxColumnNum = 0;     
        Map<Integer, CellStyle> styleMap = (copyStyle) ? new HashMap<Integer, CellStyle>() : null;     
        for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {     
            Row srcRow = sheet.getRow(i);     
            Row 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(Sheet srcSheet, Sheet destSheet, Row srcRow, Row destRow, Map<Integer, CellStyle> 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++) {     
            Cell oldCell = srcRow.getCell(j);   // ancienne cell  
            Cell 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(Cell oldCell, Cell newCell, Map<Integer, CellStyle> styleMap) {     
        if(styleMap != null) {     
            if(oldCell.getSheet().getWorkbook() == newCell.getSheet().getWorkbook()){     
                newCell.setCellStyle(oldCell.getCellStyle());     
            } else{     
                int stHashCode = oldCell.getCellStyle().hashCode();     
                CellStyle 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 Cell.CELL_TYPE_STRING:     
                newCell.setCellValue(oldCell.getStringCellValue());     
                break;     
          case Cell.CELL_TYPE_NUMERIC:     
                newCell.setCellValue(oldCell.getNumericCellValue());     
                break;     
          case Cell.CELL_TYPE_BLANK:     
                newCell.setCellType(HSSFCell.CELL_TYPE_BLANK);     
                break;     
          case Cell.CELL_TYPE_BOOLEAN:     
                newCell.setCellValue(oldCell.getBooleanCellValue());     
                break;     
          case Cell.CELL_TYPE_ERROR:     
                newCell.setCellErrorValue(oldCell.getErrorCellValue());     
                break;     
          case Cell.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(Sheet 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;  
                }  
    
    }  
    
    }  
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there a single query (subqueries in it are allowed) where I can copy
I have this code to copy a sheet from a Workbook in VBA/Access to
I am using this function to copy a sheet from a Workbook to another
I can copy remote image to my server with; @copy(http://www.example.com/image.jpg, $title.'.jpg'); But I want
with the shutil.copytree I can copy an entire directory with files and folders into
I have a chunk of javascript that users can copy and paste to put
I'd like a batch script in Windows with which I can copy one directory
I have an Access 2007 database and when I open it I can copy
I'm using e4x to generate a HTML-snippet for my users which they can copy
I have to say I don't understand Scala enumeration classes. I can copy-paste the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.