Java 如何复制.xlsx完整工作簿

Java 如何复制.xlsx完整工作簿,java,apache-poi,Java,Apache Poi,我有用java复制.xls工作簿的解决方案,但无法复制.xlsx工作簿。 任何人都有解决办法。 我搜索了google、stackoverflow,找到了只复制xls文件的解决方案。我没有测试我的代码。写它只是为了给你一个做什么的基本想法 public class CopyXSSFWorkbook { public static void main(String[] args) { // Read xlsx file XSSFWorkbook oldWo

我有用java复制.xls工作簿的解决方案,但无法复制.xlsx工作簿。 任何人都有解决办法。
我搜索了google、stackoverflow,找到了只复制xls文件的解决方案。

我没有测试我的代码。写它只是为了给你一个做什么的基本想法

public class CopyXSSFWorkbook {

    public static void main(String[] args) {

        // Read xlsx file
        XSSFWorkbook oldWorkbook = null;
        try {
            oldWorkbook = (XSSFWorkbook) WorkbookFactory.create(new File("old.xlsx"));
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        final XSSFWorkbook newWorkbook = new XSSFWorkbook();

        // Copy style source
        final StylesTable oldStylesSource = oldWorkbook.getStylesSource();
        final StylesTable newStylesSource = newWorkbook.getStylesSource();

        oldStylesSource.getFonts().forEach(font -> newStylesSource.putFont(font, true));
        oldStylesSource.getFills().forEach(fill -> newStylesSource.putFill(new XSSFCellFill(fill.getCTFill())));
        oldStylesSource.getBorders()
                .forEach(border -> newStylesSource.putBorder(new XSSFCellBorder(border.getCTBorder())));

        // Copy sheets
        for (int sheetNumber = 0; sheetNumber < oldWorkbook.getNumberOfSheets(); sheetNumber++) {
            final XSSFSheet oldSheet = oldWorkbook.getSheetAt(sheetNumber);
            final XSSFSheet newSheet = newWorkbook.createSheet(oldSheet.getSheetName());

            newSheet.setDefaultRowHeight(oldSheet.getDefaultRowHeight());
            newSheet.setDefaultColumnWidth(oldSheet.getDefaultColumnWidth());

            // Copy content
            for (int rowNumber = oldSheet.getFirstRowNum(); rowNumber < oldSheet.getLastRowNum(); rowNumber++) {
                final XSSFRow oldRow = oldSheet.getRow(rowNumber);
                if (oldRow != null) {
                    final XSSFRow newRow = newSheet.createRow(rowNumber);
                    newRow.setHeight(oldRow.getHeight());

                    for (int columnNumber = oldRow.getFirstCellNum(); columnNumber < oldRow
                            .getLastCellNum(); columnNumber++) {
                        newSheet.setColumnWidth(columnNumber, oldSheet.getColumnWidth(columnNumber));

                        final XSSFCell oldCell = oldRow.getCell(columnNumber);
                        if (oldCell != null) {
                            final XSSFCell newCell = newRow.createCell(columnNumber);

                            // Copy value
                            setCellValue(newCell, getCellValue(oldCell));

                            // Copy style
                            XSSFCellStyle newCellStyle = newWorkbook.createCellStyle();
                            newCellStyle.cloneStyleFrom(oldCell.getCellStyle());
                            newCell.setCellStyle(newCellStyle);
                        }
                    }
                }
            }
        }

        try {
            oldWorkbook.close();
            newWorkbook.write(new FileOutputStream("new.xlsx"));
            newWorkbook.close();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

    private static void setCellValue(final XSSFCell cell, final Object value) {
        if (value instanceof Boolean) {
            cell.setCellValue((boolean) value);
        } else if (value instanceof Byte) {
            cell.setCellValue((byte) value);
        } else if (value instanceof Double) {
            cell.setCellValue((double) value);
        } else if (value instanceof String) {
            if (value.startsWith("=")) { 
                //  Formula String  
                cell.setCellFormula(value.substring(1));
            } else {
                cell.setCellValue(cstr);
            }
        } else {
            throw new IllegalArgumentException();
        }
    }

    private static Object getCellValue(final XSSFCell cell) {
        switch (cell.getCellTypeEnum()) {
            case BOOLEAN:
                return cell.getBooleanCellValue(); // boolean
            case ERROR:
                return cell.getErrorCellValue(); // byte
            case NUMERIC:
                return cell.getNumericCellValue(); // double
            case STRING:
            case BLANK:
                return cell.getStringCellValue(); // String
            case FORMULA:
                return  "=" + cell.getCellFormula(); // String for formula
            default:
                throw new IllegalArgumentException();
        }
    }
}
公共类CopyXSSFWorkbook{
公共静态void main(字符串[]args){
//读取xlsx文件
XSSFWorkbook oldWorkbook=null;
试一试{
oldWorkbook=(XSSFWorkbook)WorkbookFactory.create(新文件(“old.xlsx”);
}捕获(例外e){
e、 printStackTrace();
返回;
}
最终XSSFWorkbook newWorkbook=新XSSFWorkbook();
//复制样式源
final StylesTable oldStylesSource=oldWorkbook.getStylesSource();
final StylesTable newStylesSource=newWorkbook.getStylesSource();
oldStylesSource.getFonts().forEach(font->newStylesSource.putFont(font,true));
oldStylesSource.getFills().forEach(fill->newStylesSource.putFill(新的XSSFCellFill(fill.getCTFill()));
oldStylesSource.getBorders()
.forEach(border->newStylesSource.putBorder(新的XSSFCellBorder(border.getCTBorder()));
//复印纸
对于(int sheetNumber=0;sheetNumber
使用Apache POI XSSF库:

public void copyFile(String sourcePath, String destinationPath) throws IOException {
    FileInputStream excelFile = new FileInputStream(new File(sourcePath));
    Workbook workbook = new XSSFWorkbook(excelFile);
    FileOutputStream outputStream = new FileOutputStream(destinationPath);
    workbook.write(outputStream);
    workbook.close();
}

如果任何人想要更简单的过程,只需使用Files.copy:

File originalWb = new File("orginalWb.xlsx"); 
File clonedWb = new File("clonedWb.xlsx");
Files.copy(originalWb.toPath(), clonedW.toPath());

不需要任何臃肿的代码

在内存中克隆工作簿(如果您可以复制):

阿帕奇POI

POI在
XLS/XLSX
文件上执行这些步骤<代码>XLS:HSSF工作簿,XLSX:XSSF工作簿

  • 以流(FileStream)的形式读取文件:SystemFile到JavaFileObject
  • 创建工作簿表单流。流到XSSFWorkbook JavaObject
  • 使用POI函数可以对Java工作簿对象执行CURD操作
  • 将Java工作簿对象转换为文件/流
  • 注:行/列/表的索引从表0开始

    在图纸上执行以下操作:

    XLSX文件,带有
    Sheet1,Sheet2

    获取工作表\u移除其他工作表(表1)。XLSX文件:
    Sheet1

    公共静态XSSFSheet getSheet_RemoveOthers(字符串sourceFileSheetName){
    XSSFSheet srcSheet=workBook.getSheet(sourceFileSheetName);
    //Sheet srcSheet=oldWorkbook.getSheetAt(0);
    int srcSheetIndex=workBook.getSheetIndex(srcSheet);
    System.out.println(“srcSheetIndex:+srcSheetIndex”);
    int numberOfSheets=workBook.getNumberOfSheets();
    对于(int-indexAt=0;indexAtpublic static Workbook cloneWorkbook(final Workbook workbook) {
      try {
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(4096);
        workbook.write(outputStream);
        return WorkbookFactory.create(new ByteArrayInputStream(outputStream.toByteArray()));
      } catch (final IOException ex) {
        log.warn("Error cloning workbook", ex);
        return null; // or throw exception
      }
    }