2011-05-03 8 views

Respuesta

4

Transpose, como en el intercambio A2 con B1 y A3 con C1 (por lo que las columnas se convierten en filas)?

Si es así, no hay nada integrado, por lo que tendría que hacer un poco de codificación usted mismo. Es probable que desee tomar un par de celdas, guardar el contenido de una (valor y estilo), copiar la segunda a la primera y luego sobrescribir la segunda.

Consulte el quick guide si no está seguro de todas las partes de lectura/escritura.

+0

gracias, pero después de guardar los valores y que viene a pegar de nuevo me dieron una excepción de: excepción en el hilo java.lang.IllegalArgumentException "principal": índice de la hoja (1) está fuera de rango (0. .0) ..... ¿Qué puedo hacer para resolver eso? – Yoni

+0

Supongo que no está usando el mismo libro de trabajo, o está usando un nuevo libro de trabajo en el que no ha creado una hoja. ¡Necesita crear una hoja en el nuevo Libro de trabajo antes de poder poblarlo! – Gagravarr

2

Estaba buscando la misma respuesta y tuve que codificarla yo mismo. Me he adjuntado mi solución, que es bastante simple:

  1. determinar el número de filas
  2. determinar el número máximo de columnas utiliza
  3. iterador sobre cada fila, cada columna y
  4. Guardar el Móvil desde esa fila/columna en una lista simple como un tipo de 'CellModel'
  5. una vez hecho esto, iterar sobre todos los CellModels
  6. columna y fila de índice
  7. Switch y guardar el CellModel en la hoja

El código que he usado es:

public static void transpose(Workbook wb, int sheetNum, boolean replaceOriginalSheet) { 
    Sheet sheet = wb.getSheetAt(sheetNum); 

    Pair<Integer, Integer> lastRowColumn = getLastRowAndLastColumn(sheet); 
    int lastRow = lastRowColumn.getFirst(); 
    int lastColumn = lastRowColumn.getSecond(); 

    LOG.debug("Sheet {} has {} rows and {} columns, transposing ...", new Object[] {sheet.getSheetName(), 1+lastRow, lastColumn}); 

    List<CellModel> allCells = new ArrayList<CellModel>(); 
    for (int rowNum = 0; rowNum <= lastRow; rowNum++) { 
     Row row = sheet.getRow(rowNum); 
     if (row == null) { 
      continue; 
     } 
     for (int columnNum = 0; columnNum < lastColumn; columnNum++) { 
      Cell cell = row.getCell(columnNum); 
      allCells.add(new CellModel(cell)); 
     } 
    } 
    LOG.debug("Read {} cells ... transposing them", allCells.size()); 

    Sheet tSheet = wb.createSheet(sheet.getSheetName() + "_transposed"); 
    for (CellModel cm : allCells) { 
     if (cm.isBlank()) { 
      continue; 
     } 

     int tRow = cm.getColNum(); 
     int tColumn = cm.getRowNum(); 

     Row row = tSheet.getRow(tRow); 
     if (row == null) { 
      row = tSheet.createRow(tRow); 
     } 

     Cell cell = row.createCell(tColumn); 
     cm.insertInto(cell); 
    } 

    lastRowColumn = getLastRowAndLastColumn(sheet); 
    lastRow = lastRowColumn.getFirst(); 
    lastColumn = lastRowColumn.getSecond(); 
    LOG.debug("Transposing done. {} now has {} rows and {} columns.", new Object[] {tSheet.getSheetName(), 1+lastRow, lastColumn}); 

    if (replaceOriginalSheet) { 
     int pos = wb.getSheetIndex(sheet); 
     wb.removeSheetAt(pos); 
     wb.setSheetOrder(tSheet.getSheetName(), pos); 
    } 

} 

private static Pair<Integer, Integer> getLastRowAndLastColumn(Sheet sheet) { 
    int lastRow = sheet.getLastRowNum(); 
    int lastColumn = 0; 
    for (Row row : sheet) { 
     if (lastColumn < row.getLastCellNum()) { 
      lastColumn = row.getLastCellNum(); 
     } 
    } 
    return new Pair<Integer, Integer>(lastRow, lastColumn); 
} 

lo cual el CellModel es una envoltura que contiene los datos de una celda contenida (se puede añadir más atributos si te gusta por ejemplo, comentarios, ...) :

static class CellModel { 
    private int rowNum = -1; 
    private int colNum = -1; 
    private CellStyle cellStyle; 
    private int cellType = -1; 
    private Object cellValue; 

    public CellModel(Cell cell) { 
     if (cell != null) { 
      this.rowNum = cell.getRowIndex(); 
      this.colNum = cell.getColumnIndex(); 
      this.cellStyle = cell.getCellStyle(); 
      this.cellType = cell.getCellType(); 
      switch (this.cellType) { 
       case Cell.CELL_TYPE_BLANK: 
        break; 
       case Cell.CELL_TYPE_BOOLEAN: 
        cellValue = cell.getBooleanCellValue(); 
        break; 
       case Cell.CELL_TYPE_ERROR: 
        cellValue = cell.getErrorCellValue(); 
        break; 
       case Cell.CELL_TYPE_FORMULA: 
        cellValue = cell.getCellFormula(); 
        break; 
       case Cell.CELL_TYPE_NUMERIC: 
        cellValue = cell.getNumericCellValue(); 
        break; 
       case Cell.CELL_TYPE_STRING: 
        cellValue = cell.getRichStringCellValue(); 
        break; 
      } 
     } 
    } 

    public boolean isBlank() { 
     return this.cellType == -1 && this.rowNum == -1 && this.colNum == -1; 
    } 

    public void insertInto(Cell cell) { 
     if (isBlank()) { 
      return; 
     } 

     cell.setCellStyle(this.cellStyle); 
     cell.setCellType(this.cellType); 
     switch (this.cellType) { 
      case Cell.CELL_TYPE_BLANK: 
       break; 
      case Cell.CELL_TYPE_BOOLEAN: 
       cell.setCellValue((boolean) this.cellValue); 
       break; 
      case Cell.CELL_TYPE_ERROR: 
       cell.setCellErrorValue((byte) this.cellValue); 
       break; 
      case Cell.CELL_TYPE_FORMULA: 
       cell.setCellFormula((String) this.cellValue); 
       break; 
      case Cell.CELL_TYPE_NUMERIC: 
       cell.setCellValue((double) this.cellValue); 
       break; 
      case Cell.CELL_TYPE_STRING: 
       cell.setCellValue((RichTextString) this.cellValue); 
       break; 
     } 
    } 

    public CellStyle getCellStyle() { 
     return cellStyle; 
    } 

    public int getCellType() { 
     return cellType; 
    } 

    public Object getCellValue() { 
     return cellValue; 
    } 

    public int getRowNum() { 
     return rowNum; 
    } 

    public int getColNum() { 
     return colNum; 
    } 

} 
Cuestiones relacionadas