Copy sheet with JXL in Java

后端 未结 6 1660
轮回少年
轮回少年 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:17

    1. Check if readFormat is not null (as mentioned above)
    2. Beware of warning 'Maximum number of format records exceeded. Using default format.' Try use sth like Map to controll number of WritableCellFormat instances.

      public static void createSheetCopy(WritableWorkbook workbook, int from, int to, String sheetName) throws WriteException {
          WritableSheet sheet = workbook.getSheet(from);
          WritableSheet newSheet = workbook.createSheet(sheetName, 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));
                  }
                  WritableCell readCell = sheet.getWritableCell(colIdx, rowIdx);
                  WritableCell newCell = readCell.copyTo(colIdx, rowIdx);
                  CellFormat readFormat = readCell.getCellFormat();
                  if (readFormat != null) {
                      if (!definedFormats.containsKey(readFormat)) {
                          definedFormats.put(readFormat, new WritableCellFormat(readFormat));
                      }
                      newCell.setCellFormat(definedFormats.get(readFormat));
                  }
                  newSheet.addCell(newCell);
              }
          }
      }
      

提交回复
热议问题