Copy sheet with JXL in Java

后端 未结 6 1624
轮回少年
轮回少年 2021-01-03 05:21

I would like to copy a sheet from an existing XLS document to a new one to a new location.
How could I do this with JXL?

Workbook w1 = Workbook.getWork         


        
6条回答
  •  攒了一身酷
    2021-01-03 06:09

    Just an update, the "copyto" function does not work with a cell, some modified code: This takes a readable workbook, index number of the sheet to be copied, the writable workbook and the index number where the sheet needs to be copied, works fine for copying a sheet from one workbook to another.

    private static WritableSheet createSheetCopy(Workbook w, int from, int to,
                WritableWorkbook writeableWorkbook) throws WriteException {
            Sheet sheet = w.getSheet(from);
            WritableSheet newSheet = writeableWorkbook.getSheet(to);
            // Avoid warning
            // "Maximum number of format records exceeded. Using default format."
            Map definedFormats = new HashMap();
            for (int colIdx = 0; colIdx < sheet.getColumns(); colIdx++) {
                newSheet.setColumnView(colIdx, sheet.getColumnView(colIdx));
                for (int rowIdx = 0; rowIdx < sheet.getRows(); rowIdx++) {
                    if (colIdx == 0) {
                        newSheet.setRowView(rowIdx, sheet.getRowView(rowIdx));
                    }
                    Cell readCell = sheet.getCell(colIdx, rowIdx);
                    Label label = new Label(colIdx, rowIdx, readCell.getContents());
                    CellFormat readFormat = readCell.getCellFormat();
                    if (readFormat != null) {
                        if (!definedFormats.containsKey(readFormat)) {
                            definedFormats.put(readFormat, new WritableCellFormat(
                                    readFormat));
                        }
                        label.setCellFormat(definedFormats.get(readFormat));
                    }
                    newSheet.addCell(label);
                }
            }
            return newSheet;
        }
    

提交回复
热议问题