web-dev-qa-db-ja.com

Apache POIを使用してHSSFWorkbookをXSSFWorkbookに変換する方法は?

変換する方法

org.Apache.poi.hssf.usermodel.HSSFWorkbook

org.Apache.poi.xssf.usermodel.XSSFWorkbook

apache POIで?

環境:

  • JSE1.6
  • JBossAS4.3.2
  • POI 3.7
9

このコードは、私がここで見つけたものから適応されています coderanch forum

public final class ExcelDocumentConverter {
public static XSSFWorkbook convertWorkbookHSSFToXSSF(HSSFWorkbook source) {
    XSSFWorkbook retVal = new XSSFWorkbook();
    for (int i = 0; i < source.getNumberOfSheets(); i++) {
        XSSFSheet xssfSheet = retVal.createSheet();
        HSSFSheet hssfsheet = source.getSheetAt(i);
        copySheets(hssfsheet, xssfSheet);
    }
    return retVal;
}

public static void copySheets(HSSFSheet source, XSSFSheet destination) {
    copySheets(source, destination, true);
}

/**
 * @param destination
 *            the sheet to create from the copy.
 * @param the
 *            sheet to copy.
 * @param copyStyle
 *            true copy the style.
 */
public static void copySheets(HSSFSheet source, XSSFSheet destination, boolean copyStyle) {
    int maxColumnNum = 0;
    Map<Integer, HSSFCellStyle> styleMap = (copyStyle) ? new HashMap<Integer, HSSFCellStyle>() : null;
    for (int i = source.getFirstRowNum(); i <= source.getLastRowNum(); i++) {
        HSSFRow srcRow = source.getRow(i);
        XSSFRow destRow = destination.createRow(i);
        if (srcRow != null) {
            copyRow(source, destination, srcRow, destRow, styleMap);
            if (srcRow.getLastCellNum() > maxColumnNum) {
                maxColumnNum = srcRow.getLastCellNum();
            }
        }
    }
    for (int i = 0; i <= maxColumnNum; i++) {
        destination.setColumnWidth(i, source.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, XSSFSheet destSheet, HSSFRow srcRow, XSSFRow 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());
    // pour chaque row
    for (int j = srcRow.getFirstCellNum(); j <= srcRow.getLastCellNum(); j++) {
        HSSFCell oldCell = srcRow.getCell(j); // ancienne cell
        XSSFCell 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(),
                        mergedRegion.getLastRow(), 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, XSSFCell newCell, Map<Integer, HSSFCellStyle> styleMap) {
    if (styleMap != null) {
        int stHashCode = oldCell.getCellStyle().hashCode();
        HSSFCellStyle sourceCellStyle = styleMap.get(stHashCode);
        XSSFCellStyle destnCellStyle = newCell.getCellStyle();
        if (sourceCellStyle == null) {
            sourceCellStyle = oldCell.getSheet().getWorkbook().createCellStyle();
        }
        destnCellStyle.cloneStyleFrom(oldCell.getCellStyle());
        styleMap.put(stHashCode, sourceCellStyle);
        newCell.setCellStyle(destnCellStyle);
    }
    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);
}
}
9

上記の答えはすべて役に立たないので、ここに動作するコードがあります:

必要なフィールドに入力し、transform()を使用するmainメソッドを作成するだけです。

package myStuff;

import Java.io.*;
import Java.util.*;

import org.Apache.poi.hssf.usermodel.*;
import org.Apache.poi.poifs.filesystem.POIFSFileSystem;
import org.Apache.poi.ss.usermodel.*;
import org.Apache.poi.ss.util.CellRangeAddress;
import org.Apache.poi.xssf.usermodel.*;

public class ExcelConverter {

private File path = null;
private ArrayList<File> inputFiles = new ArrayList<File>();
private HSSFWorkbook workbookOld = null;
private XSSFWorkbook workbookNew = null;
private int lastColumn = 0;
private HashMap<Integer, XSSFCellStyle> styleMap = null;

private void getInputFiles() {
    String call = "getInputFiles ";
    if (this.path.isFile()) {
        if (this.path.getAbsolutePath().endsWith(".xls")
                && !new File(this.path.getAbsolutePath() + "x").exists())
            this.inputFiles.add(this.path);
        else {
            System.out
                    .println("Datei endet nicht mit .xls oder XLSX-Datei existiert bereits");
        }
    } else
        for (File f : this.path.listFiles(new FilenameFilter() {
            // anonyme innere Klasse

            @Override
            public boolean accept(File dir, String name) {
                if (name.endsWith(".xls"))
                    return true;
                return false;
            }

        })) {
            if (!new File(f.getAbsoluteFile() + "x").exists()) {
                this.inputFiles.add(f);
            }
        }
    System.out
            .println(call + "Dateien gefunden: " + this.inputFiles.size());
    System.out.println(call + "abgeschlossen");
}

private HSSFWorkbook getWorkBook(File f) throws FileNotFoundException,
        IOException {
    System.out.println("getWorkBook lese " + f.getAbsolutePath());
    POIFSFileSystem fs = new POIFSFileSystem(new BufferedInputStream(
            new FileInputStream(f)));
    HSSFWorkbook workbook = new HSSFWorkbook(fs);
    System.out.println("getWorkBook abgeschlossen");
    return workbook;
}

private void transform() {
    String call = "transform ";
    System.out.println(call + "Workbook");
    XSSFSheet sheetNew;
    HSSFSheet sheetOld;
    this.workbookNew.setForceFormulaRecalculation(this.workbookOld
            .getForceFormulaRecalculation());
    // workbookNew.setHidden(workbookOld.isHidden()); //[email protected] -
    // von Apache noch nicht implementiert
    this.workbookNew.setMissingCellPolicy(this.workbookOld
            .getMissingCellPolicy());

    for (int i = 0; i < this.workbookOld.getNumberOfSheets(); i++) {
        sheetOld = this.workbookOld.getSheetAt(i);
        sheetNew = this.workbookNew.getSheet(sheetOld.getSheetName());
        System.out.println(call + "Sheet erstellt: "
                + sheetOld.getSheetName());
        sheetNew = this.workbookNew.createSheet(sheetOld.getSheetName());
        this.transform(sheetOld, sheetNew);
    }
    System.out.println(call + "Anzahl verwendeter Styles: "
            + this.styleMap.size());
    System.out.println(call + "abgeschlossen");
}

private void transform(HSSFSheet sheetOld, XSSFSheet sheetNew) {
    System.out.println("transform Sheet");

    sheetNew.setDisplayFormulas(sheetOld.isDisplayFormulas());
    sheetNew.setDisplayGridlines(sheetOld.isDisplayGridlines());
    sheetNew.setDisplayGuts(sheetOld.getDisplayGuts());
    sheetNew.setDisplayRowColHeadings(sheetOld.isDisplayRowColHeadings());
    sheetNew.setDisplayZeros(sheetOld.isDisplayZeros());
    sheetNew.setFitToPage(sheetOld.getFitToPage());
    sheetNew.setForceFormulaRecalculation(sheetOld
            .getForceFormulaRecalculation());
    sheetNew.setHorizontallyCenter(sheetOld.getHorizontallyCenter());
    sheetNew.setMargin(Sheet.BottomMargin,
            sheetOld.getMargin(Sheet.BottomMargin));
    sheetNew.setMargin(Sheet.FooterMargin,
            sheetOld.getMargin(Sheet.FooterMargin));
    sheetNew.setMargin(Sheet.HeaderMargin,
            sheetOld.getMargin(Sheet.HeaderMargin));
    sheetNew.setMargin(Sheet.LeftMargin,
            sheetOld.getMargin(Sheet.LeftMargin));
    sheetNew.setMargin(Sheet.RightMargin,
            sheetOld.getMargin(Sheet.RightMargin));
    sheetNew.setMargin(Sheet.TopMargin, sheetOld.getMargin(Sheet.TopMargin));
    sheetNew.setPrintGridlines(sheetNew.isPrintGridlines());
    sheetNew.setRightToLeft(sheetNew.isRightToLeft());
    sheetNew.setRowSumsBelow(sheetNew.getRowSumsBelow());
    sheetNew.setRowSumsRight(sheetNew.getRowSumsRight());
    sheetNew.setVerticallyCenter(sheetOld.getVerticallyCenter());

    XSSFRow rowNew;
    for (Row row : sheetOld) {
        rowNew = sheetNew.createRow(row.getRowNum());
        if (rowNew != null)
            this.transform((HSSFRow) row, rowNew);
    }

    for (int i = 0; i < this.lastColumn; i++) {
        sheetNew.setColumnWidth(i, sheetOld.getColumnWidth(i));
        sheetNew.setColumnHidden(i, sheetOld.isColumnHidden(i));
    }

    for (int i = 0; i < sheetOld.getNumMergedRegions(); i++) {
        CellRangeAddress merged = sheetOld.getMergedRegion(i);
        sheetNew.addMergedRegion(merged);
    }
}

private void transform(HSSFRow rowOld, XSSFRow rowNew) {
    XSSFCell cellNew;
    rowNew.setHeight(rowOld.getHeight());
    if (rowOld.getRowStyle() != null) {
        Integer hash = rowOld.getRowStyle().hashCode();
        if (!this.styleMap.containsKey(hash))
            this.transform(hash, rowOld.getRowStyle(),
                    this.workbookNew.createCellStyle());
        rowNew.setRowStyle(this.styleMap.get(hash));
    }
    for (Cell cell : rowOld) {
        cellNew = rowNew.createCell(cell.getColumnIndex(),
                cell.getCellType());
        if (cellNew != null)
            this.transform((HSSFCell) cell, cellNew);
    }
    this.lastColumn = Math.max(this.lastColumn, rowOld.getLastCellNum());
}

private void transform(HSSFCell cellOld, XSSFCell cellNew) {
    cellNew.setCellComment(cellOld.getCellComment());

    Integer hash = cellOld.getCellStyle().hashCode();
    if (!this.styleMap.containsKey(hash)) {
        this.transform(hash, cellOld.getCellStyle(),
                this.workbookNew.createCellStyle());
    }
    cellNew.setCellStyle(this.styleMap.get(hash));

    switch (cellOld.getCellType()) {
    case Cell.CELL_TYPE_BLANK:
        break;
    case Cell.CELL_TYPE_BOOLEAN:
        cellNew.setCellValue(cellOld.getBooleanCellValue());
        break;
    case Cell.CELL_TYPE_ERROR:
        cellNew.setCellValue(cellOld.getErrorCellValue());
        break;
    case Cell.CELL_TYPE_FORMULA:
        cellNew.setCellValue(cellOld.getCellFormula());
        break;
    case Cell.CELL_TYPE_NUMERIC:
        cellNew.setCellValue(cellOld.getNumericCellValue());
        break;
    case Cell.CELL_TYPE_STRING:
        cellNew.setCellValue(cellOld.getStringCellValue());
        break;
    default:
        System.out.println("transform: Unbekannter Zellentyp "
                + cellOld.getCellType());
    }
}

private void transform(Integer hash, HSSFCellStyle styleOld,
        XSSFCellStyle styleNew) {
    styleNew.setAlignment(styleOld.getAlignment());
    styleNew.setBorderBottom(styleOld.getBorderBottom());
    styleNew.setBorderLeft(styleOld.getBorderLeft());
    styleNew.setBorderRight(styleOld.getBorderRight());
    styleNew.setBorderTop(styleOld.getBorderTop());
    styleNew.setDataFormat(this.transform(styleOld.getDataFormat()));
    styleNew.setFillBackgroundColor(styleOld.getFillBackgroundColor());
    styleNew.setFillForegroundColor(styleOld.getFillForegroundColor());
    styleNew.setFillPattern(styleOld.getFillPattern());
    styleNew.setFont(this.transform(styleOld.getFont(this.workbookOld)));
    styleNew.setHidden(styleOld.getHidden());
    styleNew.setIndention(styleOld.getIndention());
    styleNew.setLocked(styleOld.getLocked());
    styleNew.setVerticalAlignment(styleOld.getVerticalAlignment());
    styleNew.setWrapText(styleOld.getWrapText());
    this.styleMap.put(hash, styleNew);
}

private short transform(short index) {
    DataFormat formatOld = this.workbookOld.createDataFormat();
    DataFormat formatNew = this.workbookNew.createDataFormat();
    return formatNew.getFormat(formatOld.getFormat(index));
}

private XSSFFont transform(HSSFFont fontOld) {
    XSSFFont fontNew = this.workbookNew.createFont();
    fontNew.setBoldweight(fontOld.getBoldweight());
    fontNew.setCharSet(fontOld.getCharSet());
    fontNew.setColor(fontOld.getColor());
    fontNew.setFontName(fontOld.getFontName());
    fontNew.setFontHeight(fontOld.getFontHeight());
    fontNew.setItalic(fontOld.getItalic());
    fontNew.setStrikeout(fontOld.getStrikeout());
    fontNew.setTypeOffset(fontOld.getTypeOffset());
    fontNew.setUnderline(fontOld.getUnderline());
    return fontNew;
}
}
3
Thomas
//Added xbean-2.3.0.jar/xmlbeans-2.3.0.jar,poi-ooxml-3.7-20101029.jarpoi-ooxml-schemas-3.7-beta1.jar,
import Java.io.*;
import Java.util.*;

import org.Apache.poi.hssf.usermodel.*;
import org.Apache.poi.poifs.filesystem.POIFSFileSystem;
import org.Apache.poi.ss.usermodel.*;
import org.Apache.poi.ss.util.CellRangeAddress;
import org.Apache.poi.xssf.usermodel.*;

public class Xls2Xlsx {

private File path = new File("c:/Integration-TestCases.xls");
private ArrayList<File> inputFiles = new ArrayList<File>();

private int lastColumn = 0;
private HashMap<Integer, XSSFCellStyle> styleMap = new HashMap();

private void getInputFiles() {
    String call = "getInputFiles ";
    if (this.path.isFile()) {
        if (this.path.getAbsolutePath().endsWith(".xls")
                && !new File(this.path.getAbsolutePath() + "x").exists())
            this.inputFiles.add(this.path);
        else {
            System.out
                    .println("Datei endet nicht mit .xls oder XLSX-Datei existiert bereits");
        }
    } else
        for (File f : this.path.listFiles(new FilenameFilter() {
            // anonyme innere Klasse

            @Override
            public boolean accept(File dir, String name) {
                if (name.endsWith(".xls"))
                    return true;
                return false;
            }

        })) {
            if (!new File(f.getAbsoluteFile() + "x").exists()) {
                this.inputFiles.add(f);
            }
        }
    System.out
            .println(call + "Dateien gefunden: " + this.inputFiles.size());
    System.out.println(call + "abgeschlossen");
}

private HSSFWorkbook getWorkBook(File f) throws FileNotFoundException,
        IOException {
    System.out.println("getWorkBook lese " + f.getAbsolutePath());
    POIFSFileSystem fs = new POIFSFileSystem(new BufferedInputStream(
            new FileInputStream(f)));
    HSSFWorkbook workbook = new HSSFWorkbook(fs);
    System.out.println("getWorkBook abgeschlossen");
    return workbook;
}

private void transformHSSF(HSSFWorkbook workbookOld ,XSSFWorkbook workbookNew) {
    String call = "transform ";
    System.out.println(call + "Workbook");
    XSSFSheet sheetNew;
    HSSFSheet sheetOld;
    //TODO::workbookNew.setForceFormulaRecalculation(workbookOld.getForceFormulaRecalculation());
    // workbookNew.setHidden(workbookOld.isHidden()); //[email protected] -
    // von Apache noch nicht implementiert
    workbookNew.setMissingCellPolicy(workbookOld.getMissingCellPolicy());

    for (int i = 0; i < workbookOld.getNumberOfSheets(); i++) {
        sheetOld =  workbookOld.getSheetAt(i);
        sheetNew = workbookNew.getSheet(sheetOld.getSheetName());
        System.out.println(call + "Sheet Name: " + sheetOld.getSheetName());
        sheetNew = workbookNew.createSheet(sheetOld.getSheetName());
        this.transform(workbookOld,workbookNew,sheetOld, sheetNew);
    }
    System.out.println(call + "Styles size: "        + this.styleMap.size());
    System.out.println(call + "abgeschlossen");
}



    private void transform(HSSFWorkbook workbookOld ,XSSFWorkbook workbookNew,HSSFSheet sheetOld, XSSFSheet sheetNew) {
        System.out.println("transform Sheet");

        sheetNew.setDisplayFormulas(sheetOld.isDisplayFormulas());
        sheetNew.setDisplayGridlines(sheetOld.isDisplayGridlines());
        sheetNew.setDisplayGuts(sheetOld.getDisplayGuts());
        sheetNew.setDisplayRowColHeadings(sheetOld.isDisplayRowColHeadings());
        sheetNew.setDisplayZeros(sheetOld.isDisplayZeros());
        sheetNew.setFitToPage(sheetOld.getFitToPage());
        //
        //TODO::sheetNew.setForceFormulaRecalculation(sheetOld.getForceFormulaRecalculation());
        sheetNew.setHorizontallyCenter(sheetOld.getHorizontallyCenter());
        sheetNew.setMargin(Sheet.BottomMargin,
                sheetOld.getMargin(Sheet.BottomMargin));
        sheetNew.setMargin(Sheet.FooterMargin,
                sheetOld.getMargin(Sheet.FooterMargin));
        sheetNew.setMargin(Sheet.HeaderMargin,
                sheetOld.getMargin(Sheet.HeaderMargin));
        sheetNew.setMargin(Sheet.LeftMargin,
                sheetOld.getMargin(Sheet.LeftMargin));
        sheetNew.setMargin(Sheet.RightMargin,
                sheetOld.getMargin(Sheet.RightMargin));
        sheetNew.setMargin(Sheet.TopMargin, sheetOld.getMargin(Sheet.TopMargin));
        sheetNew.setPrintGridlines(sheetNew.isPrintGridlines());
        //TODO::sheetNew.setRightToLeft(sheetNew.isRightToLeft());
        sheetNew.setRowSumsBelow(sheetNew.getRowSumsBelow());
        sheetNew.setRowSumsRight(sheetNew.getRowSumsRight());
        sheetNew.setVerticallyCenter(sheetOld.getVerticallyCenter());

        XSSFRow rowNew;
        for (Row row : sheetOld) {
            rowNew = sheetNew.createRow(row.getRowNum());
            if (rowNew != null)
                this.transform(workbookOld,workbookNew,(HSSFRow) row, rowNew);
        }

        for (int i = 0; i < this.lastColumn; i++) {
            sheetNew.setColumnWidth(i, sheetOld.getColumnWidth(i));
            sheetNew.setColumnHidden(i, sheetOld.isColumnHidden(i));
        }

        for (int i = 0; i < sheetOld.getNumMergedRegions(); i++) {
            CellRangeAddress merged = sheetOld.getMergedRegion(i);
            sheetNew.addMergedRegion(merged);
        }
    }



    private void transform(HSSFWorkbook workbookOld ,XSSFWorkbook workbookNew,HSSFRow rowOld, XSSFRow rowNew) {
        XSSFCell cellNew;
        rowNew.setHeight(rowOld.getHeight());
        //TODO::if (rowOld.getRowStyle() != null) {
            /*Integer hash = rowOld.getRowStyle().hashCode();
            if (!this.styleMap.containsKey(hash))
                this.transform(workbookOld,workbookNew,hash, (XSSFCellStyle)rowOld.getRowStyle(),(HSSFCellStyle)workbookNew.createCellStyle());
            rowNew.setRowStyle(this.styleMap.get(hash));
        }*/
        for (Cell cell : rowOld) {
            cellNew = rowNew.createCell(cell.getColumnIndex(), cell.getCellType());
            if (cellNew != null)
                this.transform(workbookOld,workbookNew,(HSSFCell) cell, cellNew);
        }
        this.lastColumn = Math.max(this.lastColumn, rowOld.getLastCellNum());
    }




    private void transform(HSSFWorkbook workbookOld,XSSFWorkbook workbookNew,HSSFCell cellOld,XSSFCell cellNew) {
        cellNew.setCellComment(cellOld.getCellComment());

        Integer hash = cellOld.getCellStyle().hashCode();
        if (this.styleMap!=null && !this.styleMap.containsKey(hash)) {
            this.transform(workbookOld,workbookNew,hash, cellOld.getCellStyle(),(XSSFCellStyle)workbookNew.createCellStyle());
        }
        cellNew.setCellStyle(this.styleMap.get(hash));

        switch (cellOld.getCellType()) {
        case Cell.CELL_TYPE_BLANK:
            break;
        case Cell.CELL_TYPE_BOOLEAN:
            cellNew.setCellValue(cellOld.getBooleanCellValue());
            break;
        case Cell.CELL_TYPE_ERROR:
            cellNew.setCellValue(cellOld.getErrorCellValue());
            break;
        case Cell.CELL_TYPE_FORMULA:
            cellNew.setCellValue(cellOld.getCellFormula());
            break;
        case Cell.CELL_TYPE_NUMERIC:
            cellNew.setCellValue(cellOld.getNumericCellValue());
            break;
        case Cell.CELL_TYPE_STRING:
            cellNew.setCellValue(cellOld.getStringCellValue());
            break;
        default:
            System.out.println("transform: Unbekannter Zellentyp "
                    + cellOld.getCellType());
        }
    }




    private void transform(HSSFWorkbook workbookOld,XSSFWorkbook workbookNew,Integer hash, HSSFCellStyle styleOld,
            XSSFCellStyle styleNew) {
        styleNew.setAlignment(styleOld.getAlignment());
        styleNew.setBorderBottom(styleOld.getBorderBottom());
        styleNew.setBorderLeft(styleOld.getBorderLeft());
        styleNew.setBorderRight(styleOld.getBorderRight());
        styleNew.setBorderTop(styleOld.getBorderTop());
         styleNew.setDataFormat(this.transform( workbookOld, workbookNew,styleOld.getDataFormat()));
        styleNew.setFillBackgroundColor(styleOld.getFillBackgroundColor());
        styleNew.setFillForegroundColor(styleOld.getFillForegroundColor());
        styleNew.setFillPattern(styleOld.getFillPattern());
        styleNew.setFont(this.transform(workbookNew,styleOld.getFont(workbookOld)));
        styleNew.setHidden(styleOld.getHidden());
        styleNew.setIndention(styleOld.getIndention());
        styleNew.setLocked(styleOld.getLocked());
        styleNew.setVerticalAlignment(styleOld.getVerticalAlignment());
        styleNew.setWrapText(styleOld.getWrapText());
        this.styleMap.put(hash, styleNew);
    }

private short transform(HSSFWorkbook workbookOld,XSSFWorkbook workbookNew,short index) {
    DataFormat formatOld = workbookOld.createDataFormat();
    DataFormat formatNew = workbookNew.createDataFormat();
    return formatNew.getFormat(formatOld.getFormat(index));
}


    private XSSFFont transform(XSSFWorkbook workbookNew,HSSFFont fontOld) {
        XSSFFont fontNew = workbookNew.createFont();
        fontNew.setBoldweight(fontOld.getBoldweight());
        fontNew.setCharSet(fontOld.getCharSet());
        fontNew.setColor(fontOld.getColor());
        fontNew.setFontName(fontOld.getFontName());
        fontNew.setFontHeight(fontOld.getFontHeight());
        fontNew.setItalic(fontOld.getItalic());
        fontNew.setStrikeout(fontOld.getStrikeout());
        fontNew.setTypeOffset(fontOld.getTypeOffset());
        fontNew.setUnderline(fontOld.getUnderline());
        return fontNew;
    }

public static void main(String[] args) throws Exception{
    Xls2Xlsx xls=new Xls2Xlsx(); 
    //xls.transform();
     InputStream isXls = new FileInputStream("c:/OTD1.xls");
     HSSFWorkbook workbookOld     = new HSSFWorkbook(isXls);

    String dest="c:/OTD.xlsx";

    FileOutputStream out = new FileOutputStream(dest);
    XSSFWorkbook workbookNew = new XSSFWorkbook();
    xls.transformHSSF( workbookOld , workbookNew) ;    
    workbookNew.write(out);

    out.close();

//    InputStream isXls = new FileInputStream("c:/OTD1.xls");
//    HSSFWorkbook workbookNew     = new HSSFWorkbook(isXls);



}
}
3
Indranil Nag
//Added xbean-2.3.0.jar/xmlbeans-2.3.0.jar,poi-ooxml-3.7-20101029.jarpoi-ooxml-schemas-3.7-beta1.jar,


import Java.io.*;
import Java.util.*;

import org.Apache.poi.hssf.usermodel.*;
import org.Apache.poi.poifs.filesystem.POIFSFileSystem;
import org.Apache.poi.ss.usermodel.*;
import org.Apache.poi.ss.util.CellRangeAddress;
import org.Apache.poi.xssf.usermodel.*;

public class Xlsx2Xls {

private File path = new File("c:/Integration-TestCases.xls");
private ArrayList<File> inputFiles = new ArrayList<File>();

private int lastColumn = 0;
private HashMap<Integer, HSSFCellStyle> styleMap = new HashMap();

private void getInputFiles() {
    String call = "getInputFiles ";
    if (this.path.isFile()) {
        if (this.path.getAbsolutePath().endsWith(".xls")
                && !new File(this.path.getAbsolutePath() + "x").exists())
            this.inputFiles.add(this.path);
        else {
            System.out
                    .println("Datei endet nicht mit .xls oder XLSX-Datei existiert bereits");
        }
    } else
        for (File f : this.path.listFiles(new FilenameFilter() {
            // anonyme innere Klasse

            @Override
            public boolean accept(File dir, String name) {
                if (name.endsWith(".xls"))
                    return true;
                return false;
            }

        })) {
            if (!new File(f.getAbsoluteFile() + "x").exists()) {
                this.inputFiles.add(f);
            }
        }
    System.out
            .println(call + "Dateien gefunden: " + this.inputFiles.size());
    System.out.println(call + "abgeschlossen");
}

private HSSFWorkbook getWorkBook(File f) throws FileNotFoundException,
        IOException {
    System.out.println("getWorkBook lese " + f.getAbsolutePath());
    POIFSFileSystem fs = new POIFSFileSystem(new BufferedInputStream(
            new FileInputStream(f)));
    HSSFWorkbook workbook = new HSSFWorkbook(fs);
    System.out.println("getWorkBook abgeschlossen");
    return workbook;
}

private void transformXSSF(XSSFWorkbook workbookOld ,HSSFWorkbook workbookNew) {
    String call = "transform ";
    System.out.println(call + "Workbook");
    HSSFSheet sheetNew;
    XSSFSheet sheetOld;
    //TODO::workbookNew.setForceFormulaRecalculation(workbookOld.getForceFormulaRecalculation());
    // workbookNew.setHidden(workbookOld.isHidden()); //[email protected] -
    // von Apache noch nicht implementiert
    workbookNew.setMissingCellPolicy(workbookOld.getMissingCellPolicy());

    for (int i = 0; i < workbookOld.getNumberOfSheets(); i++) {
        sheetOld =  workbookOld.getSheetAt(i);
        sheetNew = workbookNew.getSheet(sheetOld.getSheetName());
        System.out.println(call + "Sheet Name: " + sheetOld.getSheetName());
        sheetNew = workbookNew.createSheet(sheetOld.getSheetName());
        this.transform(workbookOld,workbookNew,sheetOld, sheetNew);
    }
    System.out.println(call + "Styles size: "        + this.styleMap.size());
    System.out.println(call + "abgeschlossen");
}



    private void transform(XSSFWorkbook workbookOld ,HSSFWorkbook workbookNew,XSSFSheet sheetOld, HSSFSheet sheetNew) {
        System.out.println("transform Sheet");

        sheetNew.setDisplayFormulas(sheetOld.isDisplayFormulas());
        sheetNew.setDisplayGridlines(sheetOld.isDisplayGridlines());
        sheetNew.setDisplayGuts(sheetOld.getDisplayGuts());
        sheetNew.setDisplayRowColHeadings(sheetOld.isDisplayRowColHeadings());
        sheetNew.setDisplayZeros(sheetOld.isDisplayZeros());
        sheetNew.setFitToPage(sheetOld.getFitToPage());
        //
        //TODO::sheetNew.setForceFormulaRecalculation(sheetOld.getForceFormulaRecalculation());
        sheetNew.setHorizontallyCenter(sheetOld.getHorizontallyCenter());
        sheetNew.setMargin(Sheet.BottomMargin,
                sheetOld.getMargin(Sheet.BottomMargin));
        sheetNew.setMargin(Sheet.FooterMargin,
                sheetOld.getMargin(Sheet.FooterMargin));
        sheetNew.setMargin(Sheet.HeaderMargin,
                sheetOld.getMargin(Sheet.HeaderMargin));
        sheetNew.setMargin(Sheet.LeftMargin,
                sheetOld.getMargin(Sheet.LeftMargin));
        sheetNew.setMargin(Sheet.RightMargin,
                sheetOld.getMargin(Sheet.RightMargin));
        sheetNew.setMargin(Sheet.TopMargin, sheetOld.getMargin(Sheet.TopMargin));
        sheetNew.setPrintGridlines(sheetNew.isPrintGridlines());
        sheetNew.setRightToLeft(sheetNew.isRightToLeft());
        sheetNew.setRowSumsBelow(sheetNew.getRowSumsBelow());
        sheetNew.setRowSumsRight(sheetNew.getRowSumsRight());
        sheetNew.setVerticallyCenter(sheetOld.getVerticallyCenter());

        HSSFRow rowNew;
        for (Row row : sheetOld) {
            rowNew = sheetNew.createRow(row.getRowNum());
            if (rowNew != null)
                this.transform(workbookOld,workbookNew,(XSSFRow) row, rowNew);
        }

        for (int i = 0; i < this.lastColumn; i++) {
            sheetNew.setColumnWidth(i, sheetOld.getColumnWidth(i));
            sheetNew.setColumnHidden(i, sheetOld.isColumnHidden(i));
        }

        for (int i = 0; i < sheetOld.getNumMergedRegions(); i++) {
            CellRangeAddress merged = sheetOld.getMergedRegion(i);
            sheetNew.addMergedRegion(merged);
        }
    }



    private void transform(XSSFWorkbook workbookOld ,HSSFWorkbook workbookNew,XSSFRow rowOld, HSSFRow rowNew) {
        HSSFCell cellNew;
        rowNew.setHeight(rowOld.getHeight());
        //TODO::if (rowOld.getRowStyle() != null) {
            /*Integer hash = rowOld.getRowStyle().hashCode();
            if (!this.styleMap.containsKey(hash))
                this.transform(workbookOld,workbookNew,hash, (XSSFCellStyle)rowOld.getRowStyle(),(HSSFCellStyle)workbookNew.createCellStyle());
            rowNew.setRowStyle(this.styleMap.get(hash));
        }*/
        for (Cell cell : rowOld) {
            cellNew = rowNew.createCell(cell.getColumnIndex(),
                    cell.getCellType());
            if (cellNew != null)
                this.transform(workbookOld,workbookNew,(XSSFCell) cell, cellNew);
        }
        this.lastColumn = Math.max(this.lastColumn, rowOld.getLastCellNum());
    }




    private void transform(XSSFWorkbook workbookOld,HSSFWorkbook workbookNew,XSSFCell cellOld, HSSFCell cellNew) {
        cellNew.setCellComment(cellOld.getCellComment());

        Integer hash = cellOld.getCellStyle().hashCode();
        if (this.styleMap!=null && !this.styleMap.containsKey(hash)) {
            this.transform(workbookOld,workbookNew,hash, cellOld.getCellStyle(),(HSSFCellStyle)workbookNew.createCellStyle());
        }
        cellNew.setCellStyle(this.styleMap.get(hash));

        switch (cellOld.getCellType()) {
        case Cell.CELL_TYPE_BLANK:
            break;
        case Cell.CELL_TYPE_BOOLEAN:
            cellNew.setCellValue(cellOld.getBooleanCellValue());
            break;
        case Cell.CELL_TYPE_ERROR:
            cellNew.setCellValue(cellOld.getErrorCellValue());
            break;
        case Cell.CELL_TYPE_FORMULA:
            cellNew.setCellValue(cellOld.getCellFormula());
            break;
        case Cell.CELL_TYPE_NUMERIC:
            cellNew.setCellValue(cellOld.getNumericCellValue());
            break;
        case Cell.CELL_TYPE_STRING:
            cellNew.setCellValue(cellOld.getStringCellValue());
            break;
        default:
            System.out.println("transform: Unbekannter Zellentyp "
                    + cellOld.getCellType());
        }
    }




    private void transform(XSSFWorkbook workbookOld,HSSFWorkbook workbookNew,Integer hash, XSSFCellStyle styleOld,
            HSSFCellStyle styleNew) {
        styleNew.setAlignment(styleOld.getAlignment());
        styleNew.setBorderBottom(styleOld.getBorderBottom());
        styleNew.setBorderLeft(styleOld.getBorderLeft());
        styleNew.setBorderRight(styleOld.getBorderRight());
        styleNew.setBorderTop(styleOld.getBorderTop());
         styleNew.setDataFormat(this.transform( workbookOld, workbookNew,styleOld.getDataFormat()));
        styleNew.setFillBackgroundColor(styleOld.getFillBackgroundColor());
        styleNew.setFillForegroundColor(styleOld.getFillForegroundColor());
        styleNew.setFillPattern(styleOld.getFillPattern());
        styleNew.setFont(this.transform(workbookNew,(XSSFFont)styleOld.getFont()));
        styleNew.setHidden(styleOld.getHidden());
        styleNew.setIndention(styleOld.getIndention());
        styleNew.setLocked(styleOld.getLocked());
        styleNew.setVerticalAlignment(styleOld.getVerticalAlignment());
        styleNew.setWrapText(styleOld.getWrapText());
        this.styleMap.put(hash, styleNew);
    }

private short transform(XSSFWorkbook workbookOld,HSSFWorkbook workbookNew,short index) {
    DataFormat formatOld = workbookOld.createDataFormat();
    DataFormat formatNew = workbookNew.createDataFormat();
    return formatNew.getFormat(formatOld.getFormat(index));
}


    private HSSFFont transform(HSSFWorkbook workbookNew,XSSFFont fontOld) {
        HSSFFont fontNew = workbookNew.createFont();
        fontNew.setBoldweight(fontOld.getBoldweight());
        fontNew.setCharSet(fontOld.getCharSet());
        fontNew.setColor(fontOld.getColor());
        fontNew.setFontName(fontOld.getFontName());
        fontNew.setFontHeight(fontOld.getFontHeight());
        fontNew.setItalic(fontOld.getItalic());
        fontNew.setStrikeout(fontOld.getStrikeout());
        fontNew.setTypeOffset(fontOld.getTypeOffset());
        fontNew.setUnderline(fontOld.getUnderline());
        return fontNew;
    }

public static void main(String[] args) throws Exception{
    Xlsx2Xls xls=new Xlsx2Xls(); 
    //xls.transform();
     InputStream isXlsx = new FileInputStream("c:/OTD.xlsx");
     XSSFWorkbook workbookOld     = new XSSFWorkbook(isXlsx);

    String dest="c:/OTD1.xls";

    FileOutputStream out = new FileOutputStream(dest);
    HSSFWorkbook workbookNew = new HSSFWorkbook();
    xls.transformXSSF( workbookOld , workbookNew) ;    
    workbookNew.write(out);

    out.close();

//    InputStream isXls = new FileInputStream("c:/OTD1.xls");
//    HSSFWorkbook workbookNew     = new HSSFWorkbook(isXls);



}
}
2
Indranil Nag
2
trashgod

'SSUsermodel'を使用する必要があるように私には思えます。この件に関する詳細については、ApachePOIのWebサイトを参照してください。

2
Wivani

これが私のアプローチです

import Java.util.ArrayList;
import Java.util.Iterator;
import Java.util.List;
import Java.util.Set;
import Java.util.TreeSet;

import org.Apache.poi.hssf.usermodel.HSSFCell;
import org.Apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.Apache.poi.hssf.usermodel.HSSFPatriarch;
import org.Apache.poi.hssf.usermodel.HSSFPicture;
import org.Apache.poi.hssf.usermodel.HSSFPictureData;
import org.Apache.poi.hssf.usermodel.HSSFRow;
import org.Apache.poi.hssf.usermodel.HSSFShape;
import org.Apache.poi.hssf.usermodel.HSSFSheet;
import org.Apache.poi.hssf.usermodel.HSSFWorkbook;
import org.Apache.poi.ss.usermodel.Cell;
import org.Apache.poi.ss.usermodel.CellStyle;
import org.Apache.poi.ss.usermodel.ClientAnchor;
import org.Apache.poi.ss.usermodel.CreationHelper;
import org.Apache.poi.ss.usermodel.DataFormat;
import org.Apache.poi.ss.usermodel.Drawing;
import org.Apache.poi.ss.usermodel.Font;
import org.Apache.poi.ss.usermodel.Footer;
import org.Apache.poi.ss.usermodel.Header;
import org.Apache.poi.ss.usermodel.Name;
import org.Apache.poi.ss.usermodel.PrintSetup;
import org.Apache.poi.ss.usermodel.Sheet;
import org.Apache.poi.ss.util.CellRangeAddress;
import org.Apache.poi.ss.util.CellReference;
import org.Apache.poi.xssf.usermodel.XSSFCell;
import org.Apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.Apache.poi.xssf.usermodel.XSSFDrawing;
import org.Apache.poi.xssf.usermodel.XSSFName;
import org.Apache.poi.xssf.usermodel.XSSFPicture;
import org.Apache.poi.xssf.usermodel.XSSFPictureData;
import org.Apache.poi.xssf.usermodel.XSSFRow;
import org.Apache.poi.xssf.usermodel.XSSFShape;
import org.Apache.poi.xssf.usermodel.XSSFSheet;
import org.Apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTTwoCellAnchor;

public class XlsXlsxConverter3 {
@SuppressWarnings("unused")
private static class FormulaInfo {

private String sheetName;
private Integer rowIndex;
private Integer cellIndex;
private String formula;

private FormulaInfo(String sheetName, Integer rowIndex, Integer cellIndex, String formula) {
this.sheetName = sheetName;
this.rowIndex = rowIndex;
this.cellIndex = cellIndex;
this.formula = formula;
}

public String getSheetName() {
return sheetName;
}

public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}

public Integer getRowIndex() {
return rowIndex;
}

public void setRowIndex(Integer rowIndex) {
this.rowIndex = rowIndex;
}

public Integer getCellIndex() {
return cellIndex;
}

public void setCellIndex(Integer cellIndex) {
this.cellIndex = cellIndex;
}

public String getFormula() {
return formula;
}

public void setFormula(String formula) {
this.formula = formula;
}
}

static List<FormulaInfo> formulaInfoList = new ArrayList<FormulaInfo>();

public static void refreshFormula(XSSFWorkbook workbook) {
for (FormulaInfo formulaInfo : formulaInfoList) {
workbook.getSheet(formulaInfo.getSheetName()).getRow(formulaInfo.getRowIndex())
.getCell(formulaInfo.getCellIndex()).setCellFormula(formulaInfo.getFormula());
}
formulaInfoList.removeAll(formulaInfoList);
}

public static XSSFWorkbook convertWorkbookHSSFToXSSF(HSSFWorkbook source) {
XSSFWorkbook retVal = new XSSFWorkbook();

for (int i = 0; i < source.getNumberOfSheets(); i++) {

HSSFSheet hssfsheet = source.getSheetAt(i);
XSSFSheet xssfSheet = retVal.createSheet(hssfsheet.getSheetName());

copySheetSettings(xssfSheet, hssfsheet);
copySheet(hssfsheet, xssfSheet);
copyPictures(xssfSheet, hssfsheet);
}

refreshFormula(retVal);

return retVal;
}

private static void copySheet(HSSFSheet source, XSSFSheet destination) {
copySheet(source, destination, true);
}

/**
* @param destination
* the sheet to create from the copy.
* @param the
* sheet to copy.
* @param copyStyle
* true copy the style.
*/
private static void copySheet(HSSFSheet source, XSSFSheet destination, boolean copyStyle) {
int maxColumnNum = 0;
List<CellStyle> styleMap2 = (copyStyle) ? new ArrayList<CellStyle>() : null;
for (int i = source.getFirstRowNum(); i <= source.getLastRowNum(); i++) {
HSSFRow srcRow = source.getRow(i);
XSSFRow destRow = destination.createRow(i);
if (srcRow != null) {
// copyRow(source, destination, srcRow, destRow, styleMap);
copyRow(source, destination, srcRow, destRow, styleMap2);
if (srcRow.getLastCellNum() > maxColumnNum) {
maxColumnNum = srcRow.getLastCellNum();
}
}
}
for (int i = 0; i <= maxColumnNum; i++) {
destination.setColumnWidth(i, source.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
* -
*/
private static void copyRow(HSSFSheet srcSheet, XSSFSheet destSheet, HSSFRow srcRow, XSSFRow destRow,
// Map<Integer, HSSFCellStyle> styleMap) {
List<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());
// pour chaque row
// for (int j = srcRow.getFirstCellNum(); j <= srcRow.getLastCellNum();
// j++) {
int j = srcRow.getFirstCellNum();
if (j < 0) {
j = 0;
}
for (; j <= srcRow.getLastCellNum(); j++) {
HSSFCell oldCell = srcRow.getCell(j); // ancienne cell
XSSFCell 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(),
mergedRegion.getLastRow(), 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);
}
}
}
}

}

/**
* 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);
}

private static void copyPictures(Sheet newSheet, Sheet sheet) {
Drawing drawingOld = sheet.createDrawingPatriarch();
Drawing drawingNew = newSheet.createDrawingPatriarch();
CreationHelper helper = newSheet.getWorkbook().getCreationHelper();

// if (drawingNew instanceof HSSFPatriarch) {
if (drawingOld instanceof HSSFPatriarch) {
List<HSSFShape> shapes = ((HSSFPatriarch) drawingOld).getChildren();
for (int i = 0; i < shapes.size(); i++) {
System.out.println(shapes.size());
if (shapes.get(i) instanceof HSSFPicture) {
HSSFPicture pic = (HSSFPicture) shapes.get(i);
HSSFPictureData picdata = pic.getPictureData();
int pictureIndex = newSheet.getWorkbook().addPicture(picdata.getData(), picdata.getFormat());
ClientAnchor anchor = null;
if (pic.getAnchor() != null) {
anchor = helper.createClientAnchor();
anchor.setDx1(((HSSFClientAnchor) pic.getAnchor()).getDx1());
anchor.setDx2(((HSSFClientAnchor) pic.getAnchor()).getDx2());
anchor.setDy1(((HSSFClientAnchor) pic.getAnchor()).getDy1());
anchor.setDy2(((HSSFClientAnchor) pic.getAnchor()).getDy2());
anchor.setCol1(((HSSFClientAnchor) pic.getAnchor()).getCol1());
anchor.setCol2(((HSSFClientAnchor) pic.getAnchor()).getCol2());
anchor.setRow1(((HSSFClientAnchor) pic.getAnchor()).getRow1());
anchor.setRow2(((HSSFClientAnchor) pic.getAnchor()).getRow2());
anchor.setAnchorType(((HSSFClientAnchor) pic.getAnchor()).getAnchorType());
}
drawingNew.createPicture(anchor, pictureIndex);
}
}
} else {
if (drawingNew instanceof XSSFDrawing) {
List<XSSFShape> shapes = ((XSSFDrawing) drawingOld).getShapes();
for (int i = 0; i < shapes.size(); i++) {
if (shapes.get(i) instanceof XSSFPicture) {
XSSFPicture pic = (XSSFPicture) shapes.get(i);
XSSFPictureData picdata = pic.getPictureData();
int pictureIndex = newSheet.getWorkbook().addPicture(picdata.getData(),
picdata.getPictureType());
XSSFClientAnchor anchor = null;
CTTwoCellAnchor oldAnchor = ((XSSFDrawing) drawingOld).getCTDrawing().getTwoCellAnchorArray(i);
if (oldAnchor != null) {
anchor = (XSSFClientAnchor) helper.createClientAnchor();
CTMarker markerFrom = oldAnchor.getFrom();
CTMarker markerTo = oldAnchor.getTo();
anchor.setDx1((int) markerFrom.getColOff());
anchor.setDx2((int) markerTo.getColOff());
anchor.setDy1((int) markerFrom.getRowOff());
anchor.setDy2((int) markerTo.getRowOff());
anchor.setCol1(markerFrom.getCol());
anchor.setCol2(markerTo.getCol());
anchor.setRow1(markerFrom.getRow());
anchor.setRow2(markerTo.getRow());
}
drawingNew.createPicture(anchor, pictureIndex);
}
}
}
}
}

private static void copyCell(Cell oldCell, Cell newCell, List<CellStyle> styleList) {
if (styleList != null) {
if (oldCell.getSheet().getWorkbook() == newCell.getSheet().getWorkbook()) {
newCell.setCellStyle(oldCell.getCellStyle());
} else {
DataFormat newDataFormat = newCell.getSheet().getWorkbook().createDataFormat();

CellStyle newCellStyle = getSameCellStyle(oldCell, newCell, styleList);
if (newCellStyle == null) {
// Create a new cell style
Font oldFont = oldCell.getSheet().getWorkbook().getFontAt(oldCell.getCellStyle().getFontIndex());
// Find a existing font corresponding to avoid to create a
// new one
Font newFont = newCell
.getSheet()
.getWorkbook()
.findFont(oldFont.getBoldweight(), oldFont.getColor(), oldFont.getFontHeight(),
oldFont.getFontName(), oldFont.getItalic(), oldFont.getStrikeout(),
oldFont.getTypeOffset(), oldFont.getUnderline());
if (newFont == null) {
newFont = newCell.getSheet().getWorkbook().createFont();
newFont.setBoldweight(oldFont.getBoldweight());
newFont.setColor(oldFont.getColor());
newFont.setFontHeight(oldFont.getFontHeight());
newFont.setFontName(oldFont.getFontName());
newFont.setItalic(oldFont.getItalic());
newFont.setStrikeout(oldFont.getStrikeout());
newFont.setTypeOffset(oldFont.getTypeOffset());
newFont.setUnderline(oldFont.getUnderline());
newFont.setCharSet(oldFont.getCharSet());
}

short newFormat = newDataFormat.getFormat(oldCell.getCellStyle().getDataFormatString());
newCellStyle = newCell.getSheet().getWorkbook().createCellStyle();
newCellStyle.setFont(newFont);
newCellStyle.setDataFormat(newFormat);

newCellStyle.setAlignment(oldCell.getCellStyle().getAlignment());
newCellStyle.setHidden(oldCell.getCellStyle().getHidden());
newCellStyle.setLocked(oldCell.getCellStyle().getLocked());
newCellStyle.setWrapText(oldCell.getCellStyle().getWrapText());
newCellStyle.setBorderBottom(oldCell.getCellStyle().getBorderBottom());
newCellStyle.setBorderLeft(oldCell.getCellStyle().getBorderLeft());
newCellStyle.setBorderRight(oldCell.getCellStyle().getBorderRight());
newCellStyle.setBorderTop(oldCell.getCellStyle().getBorderTop());
newCellStyle.setBottomBorderColor(oldCell.getCellStyle().getBottomBorderColor());
newCellStyle.setFillBackgroundColor(oldCell.getCellStyle().getFillBackgroundColor());
newCellStyle.setFillForegroundColor(oldCell.getCellStyle().getFillForegroundColor());
newCellStyle.setFillPattern(oldCell.getCellStyle().getFillPattern());
newCellStyle.setIndention(oldCell.getCellStyle().getIndention());
newCellStyle.setLeftBorderColor(oldCell.getCellStyle().getLeftBorderColor());
newCellStyle.setRightBorderColor(oldCell.getCellStyle().getRightBorderColor());
newCellStyle.setRotation(oldCell.getCellStyle().getRotation());
newCellStyle.setTopBorderColor(oldCell.getCellStyle().getTopBorderColor());
newCellStyle.setVerticalAlignment(oldCell.getCellStyle().getVerticalAlignment());

styleList.add(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(Cell.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());
formulaInfoList.add(new FormulaInfo(oldCell.getSheet().getSheetName(), oldCell.getRowIndex(), oldCell
.getColumnIndex(), oldCell.getCellFormula()));
break;
default:
break;
}
}

private static CellStyle getSameCellStyle(Cell oldCell, Cell newCell, List<CellStyle> styleList) {
CellStyle styleToFind = oldCell.getCellStyle();
CellStyle currentCellStyle = null;
CellStyle returnCellStyle = null;
Iterator<CellStyle> iterator = styleList.iterator();
Font oldFont = null;
Font newFont = null;
while (iterator.hasNext() && returnCellStyle == null) {
currentCellStyle = iterator.next();

if (currentCellStyle.getAlignment() != styleToFind.getAlignment()) {
continue;
}
if (currentCellStyle.getHidden() != styleToFind.getHidden()) {
continue;
}
if (currentCellStyle.getLocked() != styleToFind.getLocked()) {
continue;
}
if (currentCellStyle.getWrapText() != styleToFind.getWrapText()) {
continue;
}
if (currentCellStyle.getBorderBottom() != styleToFind.getBorderBottom()) {
continue;
}
if (currentCellStyle.getBorderLeft() != styleToFind.getBorderLeft()) {
continue;
}
if (currentCellStyle.getBorderRight() != styleToFind.getBorderRight()) {
continue;
}
if (currentCellStyle.getBorderTop() != styleToFind.getBorderTop()) {
continue;
}
if (currentCellStyle.getBottomBorderColor() != styleToFind.getBottomBorderColor()) {
continue;
}
if (currentCellStyle.getFillBackgroundColor() != styleToFind.getFillBackgroundColor()) {
continue;
}
if (currentCellStyle.getFillForegroundColor() != styleToFind.getFillForegroundColor()) {
continue;
}
if (currentCellStyle.getFillPattern() != styleToFind.getFillPattern()) {
continue;
}
if (currentCellStyle.getIndention() != styleToFind.getIndention()) {
continue;
}
if (currentCellStyle.getLeftBorderColor() != styleToFind.getLeftBorderColor()) {
continue;
}
if (currentCellStyle.getRightBorderColor() != styleToFind.getRightBorderColor()) {
continue;
}
if (currentCellStyle.getRotation() != styleToFind.getRotation()) {
continue;
}
if (currentCellStyle.getTopBorderColor() != styleToFind.getTopBorderColor()) {
continue;
}
if (currentCellStyle.getVerticalAlignment() != styleToFind.getVerticalAlignment()) {
continue;
}

oldFont = oldCell.getSheet().getWorkbook().getFontAt(oldCell.getCellStyle().getFontIndex());
newFont = newCell.getSheet().getWorkbook().getFontAt(currentCellStyle.getFontIndex());

if (newFont.getBoldweight() == oldFont.getBoldweight()) {
continue;
}
if (newFont.getColor() == oldFont.getColor()) {
continue;
}
if (newFont.getFontHeight() == oldFont.getFontHeight()) {
continue;
}
if (newFont.getFontName() == oldFont.getFontName()) {
continue;
}
if (newFont.getItalic() == oldFont.getItalic()) {
continue;
}
if (newFont.getStrikeout() == oldFont.getStrikeout()) {
continue;
}
if (newFont.getTypeOffset() == oldFont.getTypeOffset()) {
continue;
}
if (newFont.getUnderline() == oldFont.getUnderline()) {
continue;
}
if (newFont.getCharSet() == oldFont.getCharSet()) {
continue;
}
if (oldCell.getCellStyle().getDataFormatString().equals(currentCellStyle.getDataFormatString())) {
continue;
}

returnCellStyle = currentCellStyle;
}
return returnCellStyle;
}

private static void copySheetSettings(Sheet newSheet, Sheet sheetToCopy) {

newSheet.setAutobreaks(sheetToCopy.getAutobreaks());
newSheet.setDefaultColumnWidth(sheetToCopy.getDefaultColumnWidth());
newSheet.setDefaultRowHeight(sheetToCopy.getDefaultRowHeight());
newSheet.setDefaultRowHeightInPoints(sheetToCopy.getDefaultRowHeightInPoints());
newSheet.setDisplayGuts(sheetToCopy.getDisplayGuts());
newSheet.setFitToPage(sheetToCopy.getFitToPage());

newSheet.setForceFormulaRecalculation(sheetToCopy.getForceFormulaRecalculation());

PrintSetup sheetToCopyPrintSetup = sheetToCopy.getPrintSetup();
PrintSetup newSheetPrintSetup = newSheet.getPrintSetup();

newSheetPrintSetup.setPaperSize(sheetToCopyPrintSetup.getPaperSize());
newSheetPrintSetup.setScale(sheetToCopyPrintSetup.getScale());
newSheetPrintSetup.setPageStart(sheetToCopyPrintSetup.getPageStart());
newSheetPrintSetup.setFitWidth(sheetToCopyPrintSetup.getFitWidth());
newSheetPrintSetup.setFitHeight(sheetToCopyPrintSetup.getFitHeight());
newSheetPrintSetup.setLeftToRight(sheetToCopyPrintSetup.getLeftToRight());
newSheetPrintSetup.setLandscape(sheetToCopyPrintSetup.getLandscape());
newSheetPrintSetup.setValidSettings(sheetToCopyPrintSetup.getValidSettings());
newSheetPrintSetup.setNoColor(sheetToCopyPrintSetup.getNoColor());
newSheetPrintSetup.setDraft(sheetToCopyPrintSetup.getDraft());
newSheetPrintSetup.setNotes(sheetToCopyPrintSetup.getNotes());
newSheetPrintSetup.setNoOrientation(sheetToCopyPrintSetup.getNoOrientation());
newSheetPrintSetup.setUsePage(sheetToCopyPrintSetup.getUsePage());
newSheetPrintSetup.setHResolution(sheetToCopyPrintSetup.getHResolution());
newSheetPrintSetup.setVResolution(sheetToCopyPrintSetup.getVResolution());
newSheetPrintSetup.setHeaderMargin(sheetToCopyPrintSetup.getHeaderMargin());
newSheetPrintSetup.setFooterMargin(sheetToCopyPrintSetup.getFooterMargin());
newSheetPrintSetup.setCopies(sheetToCopyPrintSetup.getCopies());

Header sheetToCopyHeader = sheetToCopy.getHeader();
Header newSheetHeader = newSheet.getHeader();
newSheetHeader.setCenter(sheetToCopyHeader.getCenter());
newSheetHeader.setLeft(sheetToCopyHeader.getLeft());
newSheetHeader.setRight(sheetToCopyHeader.getRight());

Footer sheetToCopyFooter = sheetToCopy.getFooter();
Footer newSheetFooter = newSheet.getFooter();
newSheetFooter.setCenter(sheetToCopyFooter.getCenter());
newSheetFooter.setLeft(sheetToCopyFooter.getLeft());
newSheetFooter.setRight(sheetToCopyFooter.getRight());

newSheet.setHorizontallyCenter(sheetToCopy.getHorizontallyCenter());
newSheet.setMargin(Sheet.LeftMargin, sheetToCopy.getMargin(Sheet.LeftMargin));
newSheet.setMargin(Sheet.RightMargin, sheetToCopy.getMargin(Sheet.RightMargin));
newSheet.setMargin(Sheet.TopMargin, sheetToCopy.getMargin(Sheet.TopMargin));
newSheet.setMargin(Sheet.BottomMargin, sheetToCopy.getMargin(Sheet.BottomMargin));

newSheet.setPrintGridlines(sheetToCopy.isPrintGridlines());
newSheet.setRowSumsBelow(sheetToCopy.getRowSumsBelow());
newSheet.setRowSumsRight(sheetToCopy.getRowSumsRight());
newSheet.setVerticallyCenter(sheetToCopy.getVerticallyCenter());
newSheet.setDisplayFormulas(sheetToCopy.isDisplayFormulas());
newSheet.setDisplayGridlines(sheetToCopy.isDisplayGridlines());
newSheet.setDisplayRowColHeadings(sheetToCopy.isDisplayRowColHeadings());
newSheet.setDisplayZeros(sheetToCopy.isDisplayZeros());
newSheet.setPrintGridlines(sheetToCopy.isPrintGridlines());
newSheet.setRightToLeft(sheetToCopy.isRightToLeft());
newSheet.setZoom(1, 1);
copyPrintTitle(newSheet, sheetToCopy);
}

private static void copyPrintTitle(Sheet newSheet, Sheet sheetToCopy) {
int nbNames = sheetToCopy.getWorkbook().getNumberOfNames();
Name name = null;
String formula = null;

String part1S = null;
String part2S = null;
String formS = null;
String formF = null;
String part1F = null;
String part2F = null;
int rowB = -1;
int rowE = -1;
int colB = -1;
int colE = -1;

for (int i = 0; i < nbNames; i++) {
name = sheetToCopy.getWorkbook().getNameAt(i);
if (name.getSheetIndex() == sheetToCopy.getWorkbook().getSheetIndex(sheetToCopy)) {
if (name.getNameName().equals("Print_Titles")
|| name.getNameName().equals(XSSFName.BUILTIN_PRINT_TITLE)) {
formula = name.getRefersToFormula();
int indexComma = formula.indexOf(",");
if (indexComma == -1) {
indexComma = formula.indexOf(";");
}
String firstPart = null;
;
String secondPart = null;
if (indexComma == -1) {
firstPart = formula;
} else {
firstPart = formula.substring(0, indexComma);
secondPart = formula.substring(indexComma + 1);
}

formF = firstPart.substring(firstPart.indexOf("!") + 1);
part1F = formF.substring(0, formF.indexOf(":"));
part2F = formF.substring(formF.indexOf(":") + 1);

if (secondPart != null) {
formS = secondPart.substring(secondPart.indexOf("!") + 1);
part1S = formS.substring(0, formS.indexOf(":"));
part2S = formS.substring(formS.indexOf(":") + 1);
}

rowB = -1;
rowE = -1;
colB = -1;
colE = -1;
String rowBs, rowEs, colBs, colEs;
if (part1F.lastIndexOf("$") != part1F.indexOf("$")) {
rowBs = part1F.substring(part1F.lastIndexOf("$") + 1, part1F.length());
rowEs = part2F.substring(part2F.lastIndexOf("$") + 1, part2F.length());
rowB = Integer.parseInt(rowBs);
rowE = Integer.parseInt(rowEs);
if (secondPart != null) {
colBs = part1S.substring(part1S.lastIndexOf("$") + 1, part1S.length());
colEs = part2S.substring(part2S.lastIndexOf("$") + 1, part2S.length());
colB = CellReference.convertColStringToIndex(colBs);// CExportExcelHelperPoi.convertColumnLetterToInt(colBs);
colE = CellReference.convertColStringToIndex(colEs);// CExportExcelHelperPoi.convertColumnLetterToInt(colEs);
}
} else {
colBs = part1F.substring(part1F.lastIndexOf("$") + 1, part1F.length());
colEs = part2F.substring(part2F.lastIndexOf("$") + 1, part2F.length());
colB = CellReference.convertColStringToIndex(colBs);// CExportExcelHelperPoi.convertColumnLetterToInt(colBs);
colE = CellReference.convertColStringToIndex(colEs);// CExportExcelHelperPoi.convertColumnLetterToInt(colEs);

if (secondPart != null) {
rowBs = part1S.substring(part1S.lastIndexOf("$") + 1, part1S.length());
rowEs = part2S.substring(part2S.lastIndexOf("$") + 1, part2S.length());
rowB = Integer.parseInt(rowBs);
rowE = Integer.parseInt(rowEs);
}
}

newSheet.getWorkbook().setRepeatingRowsAndColumns(newSheet.getWorkbook().getSheetIndex(newSheet),
colB, colE, rowB - 1, rowE - 1);
}
}
}
}
} 
1

タイプに関係なくワークブックをコピーするためのコードをいくつか実装しました。インターフェイスを使用するため、HSSFWorkbook、XSSFWorkbook、およびSXSSFWorkbookを使用できます。

これにより、画像、フォント、スタイル、行を含むシートがコピーされます。私のユースケースでは、既存のテンプレートに新しい行を挿入してSXSSFWorkbookに書き込む必要があるため、すべてのシートと行を直接コピーするのではなく、シートを選択します。コピーしてから、必要な部分をコピーしたいと思います。

    Workbook template = getTemplateSource(...);
    Workbook wb = new SXSSFWorkbook(...);
    ExcelTemplate builder = new ExcelTemplate(template);

    int sheetIndex = ...;
    Sheet srcSheet = template.getSheetAt(sheetIndex);
    Sheet dstSheet = ExcelTemplate.copySheet(template, wb, sheetIndex);
    int rowNumber = getDataInsertionRow();
    int foot = rowNumber + 1;
    builder.copyRows(wb, srcSheet, dstSheet, 0, rowNumber, 0);
    for (....) {
        writeNewRows(dstSheet, rowNumber++, data);
    }
    builder.copyRows(wb, srcSheet, dstSheet, foot, srcSheet.getLastRowNum() + 1, rowNumber);

そしてここにコードがあります(私はすべてのテストを削除しようとしましたが、未使用の行をいくつか忘れた可能性があります)

package com.systemonenoc.billing.web.view;

import Java.util.HashMap;
import Java.util.Map;

import org.Apache.poi.ss.usermodel.Cell;
import org.Apache.poi.ss.usermodel.CellStyle;
import org.Apache.poi.ss.usermodel.ClientAnchor;
import org.Apache.poi.ss.usermodel.DataFormat;
import org.Apache.poi.ss.usermodel.Drawing;
import org.Apache.poi.ss.usermodel.Font;
import org.Apache.poi.ss.usermodel.Picture;
import org.Apache.poi.ss.usermodel.Row;
import org.Apache.poi.ss.usermodel.Shape;
import org.Apache.poi.ss.usermodel.Sheet;
import org.Apache.poi.ss.usermodel.Workbook;

public class ExcelTemplate {

    private final Workbook template;
    private final Map<Integer, Font> fonts = new HashMap<>();
    private final Map<Integer, CellStyle> styles = new HashMap<>();

    public ExcelTemplate(Workbook template) {
        this.template = template;
    }

    public void switchStyles(Workbook dstWorkbook, CellStyle[] styles) {
        for (int i = 0; i < styles.length; i++) {
            styles[i] = getStyle(dstWorkbook, styles[i]);
        }
    }

    private Font getFont(Workbook dstWorkbook, Font font) {
        return fonts.computeIfAbsent(font.hashCode(), k -> cloneFont(dstWorkbook, font));
    }

    private CellStyle getStyle(Workbook dstWorkbook, CellStyle style) {
        Font font = getFont(dstWorkbook, template.getFontAt(style.getFontIndex()));
        return styles.computeIfAbsent(style.hashCode(), k -> cloneStyle(dstWorkbook, style, dstWorkbook.createDataFormat(), font));
    }

    public void copyRows(Workbook dstWorkbook, Sheet srcSheet, Sheet dstSheet, int from, int to, int offset) {
        for (int r = from; r < to; r++) {
            Row srcRow = srcSheet.getRow(r);
            if (srcRow != null) {
                CellStyle style = srcRow.getRowStyle();
                Row dstRow = dstSheet.createRow(r + offset);
                dstRow.setHeight(srcRow.getHeight());
                if (style != null) {
                    dstRow.setRowStyle(getStyle(dstWorkbook, style));
                }
                for (int c = 0; c < srcRow.getLastCellNum(); c++) {
                    Cell srcCell = srcRow.getCell(c);
                    if (srcCell != null) {
                        int type = getCellType(srcCell);
                        Object value = getCellValue(srcCell);
                        style = srcCell.getCellStyle();
                        Cell newCell = dstRow.createCell(c, type);
                        setCellValue(newCell, value, type);
                        newCell.setCellStyle(getStyle(dstWorkbook, style));
                    }
                }
            }
        }
    }

    public static Sheet copySheet(Workbook srcWorkbook, Workbook dstWorkbook, int sheetIndex) {
        Sheet srcSheet = srcWorkbook.getSheetAt(sheetIndex);
        Sheet dstSheet = dstWorkbook.createSheet(srcSheet.getSheetName());
        dstSheet.setDisplayFormulas(srcSheet.isDisplayFormulas());
        dstSheet.setDisplayGridlines(srcSheet.isDisplayGridlines());
        dstSheet.setDisplayGuts(srcSheet.getDisplayGuts());
        dstSheet.setDisplayRowColHeadings(srcSheet.isDisplayRowColHeadings());
        dstSheet.setDisplayZeros(srcSheet.isDisplayZeros());
        dstSheet.setFitToPage(srcSheet.getFitToPage());
        dstSheet.setForceFormulaRecalculation(srcSheet.getForceFormulaRecalculation());
        dstSheet.setHorizontallyCenter(srcSheet.getHorizontallyCenter());
        dstSheet.setMargin(Sheet.BottomMargin, srcSheet.getMargin(Sheet.BottomMargin));
        dstSheet.setMargin(Sheet.FooterMargin, srcSheet.getMargin(Sheet.FooterMargin));
        dstSheet.setMargin(Sheet.HeaderMargin, srcSheet.getMargin(Sheet.HeaderMargin));
        dstSheet.setMargin(Sheet.LeftMargin, srcSheet.getMargin(Sheet.LeftMargin));
        dstSheet.setMargin(Sheet.RightMargin, srcSheet.getMargin(Sheet.RightMargin));
        dstSheet.setMargin(Sheet.TopMargin, srcSheet.getMargin(Sheet.TopMargin));
        dstSheet.setPrintGridlines(srcSheet.isPrintGridlines());
        dstSheet.setRightToLeft(srcSheet.isRightToLeft());
        dstSheet.setRowSumsBelow(srcSheet.getRowSumsBelow());
        dstSheet.setRowSumsRight(srcSheet.getRowSumsRight());
        dstSheet.setVerticallyCenter(srcSheet.getVerticallyCenter());
        for (int i = 0; i < 20; i++) {
            dstSheet.setColumnWidth(i, srcSheet.getColumnWidth(i));
            dstSheet.setColumnHidden(i, srcSheet.isColumnHidden(i));
        }
        srcSheet.getMergedRegions().forEach(dstSheet::addMergedRegion);
        Drawing<?> d1 = srcSheet.getDrawingPatriarch();
        if (d1 != null) {
            Drawing<?> d2 = dstSheet.getDrawingPatriarch();
            if (d2 == null) {
                d2 = dstSheet.createDrawingPatriarch();
            }
            for (Shape shape : d1) {
                if (shape instanceof Picture) {
                    Picture p = (Picture) shape;
                    ClientAnchor a1 = p.getClientAnchor();
                    int pictureId = dstWorkbook.addPicture(p.getPictureData().getData(), p.getPictureData().getPictureType());
                    ClientAnchor a2 = d2.createAnchor(a1.getDx1(), a1.getDy1(), a1.getDx2(), a1.getDy2(), a1.getCol1(), a1.getRow1(), a1.getCol2(), a1.getRow2());
                    d2.createPicture(a2, pictureId);
                }
            }
        }
        return dstSheet;
    }

    public static Font cloneFont(Workbook dstWorkbook, Font font) {
        Font clone = dstWorkbook.createFont();
        clone.setBold(font.getBold());
        clone.setCharSet(font.getCharSet());
        clone.setColor(font.getColor());
        clone.setFontHeight(font.getFontHeight());
        clone.setFontName(font.getFontName());
        clone.setItalic(font.getItalic());
        clone.setStrikeout(font.getStrikeout());
        clone.setTypeOffset(font.getTypeOffset());
        clone.setUnderline(font.getUnderline());
        return clone;
    }

    public static CellStyle cloneStyle(Workbook dstWorkbook, CellStyle style, DataFormat formatter, Font font) {
        CellStyle clone = dstWorkbook.createCellStyle();
        clone.setAlignment(style.getAlignmentEnum());
        clone.setBorderBottom(style.getBorderBottomEnum());
        clone.setBorderLeft(style.getBorderLeftEnum());
        clone.setBorderRight(style.getBorderRightEnum());
        clone.setBorderTop(style.getBorderTopEnum());
        clone.setDataFormat(formatter.getFormat(style.getDataFormatString()));
        clone.setFillBackgroundColor(style.getFillBackgroundColor());
        clone.setFillForegroundColor(style.getFillForegroundColor());
        clone.setFillPattern(style.getFillPatternEnum());
        clone.setFont(font);
        clone.setHidden(style.getHidden());
        clone.setIndention(style.getIndention());
        clone.setLocked(style.getLocked());
        clone.setVerticalAlignment(style.getVerticalAlignmentEnum());
        clone.setWrapText(style.getWrapText());
        return clone;
    }

    protected static int getCellType(Cell cell) {
        int cellType = cell.getCellType();
        if (cellType == Cell.CELL_TYPE_FORMULA) {
            cellType = cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator()
                    .evaluateFormulaCell(cell);
        }
        return cellType;
    }

    protected static Object getCellValue(Cell cell) {
        switch (getCellType(cell)) {
        case Cell.CELL_TYPE_BLANK:
        case Cell.CELL_TYPE_STRING:
            return cell.getStringCellValue();
        case Cell.CELL_TYPE_BOOLEAN:
            return cell.getBooleanCellValue();
        case Cell.CELL_TYPE_ERROR:
            return cell.getErrorCellValue();
        case Cell.CELL_TYPE_NUMERIC:
            return cell.getNumericCellValue();
        }
        return null;
    }

    protected static void setCellValue(Cell cell, Object value, int type) {
        switch (type) {
        case Cell.CELL_TYPE_BLANK:
            return;
        case Cell.CELL_TYPE_STRING:
            cell.setCellValue((String) value);
            return;
        case Cell.CELL_TYPE_BOOLEAN:
            cell.setCellValue((Boolean) value);
            return;
        case Cell.CELL_TYPE_ERROR:
            cell.setCellErrorValue((Byte) value);
            return;
        case Cell.CELL_TYPE_NUMERIC:
            cell.setCellValue((Double) value);
            return;
        }
    }

}
0
Triqui