Reading XLS in Java

3

I have a class to read an xls in java, and I need to know how to print one column next to another as well as in xls itself. So far I've only been able to print in a single race or online.

NOTE: I'm using the jxl library.

Follow the code:

Workbook workbook = Workbook.getWorkbook( new File( "C:\Users\lm\Desktop\planilha.xls" ));

        Sheet sheet = workbook.getSheet( 0 );

        int rows = sheet.getRows();
        int columns = sheet.getColumns();


        for ( int i = 0; i < columns; i++ )
        {
            for ( int j = 0; j < rows; j++ )
            {
                Cell cell = sheet.getCell( i , j );

                System.out.println( cell.getContents() );
            }

        }

        workbook.close();
    
asked by anonymous 21.12.2016 / 17:47

1 answer

4

Let's break the problem down into two parts:

  • Transform the worksheet into an array of String s.
  • Draw an array of String s using System.out.println .
  • Here is the resulting code:

    public String[][] planilha(String nome)
        try (Workbook workbook = Workbook.getWorkbook(new File(nome))) {
            Sheet sheet = workbook.getSheet(0);
    
            int rows = sheet.getRows();
            int columns = sheet.getColumns();
            String[][] matriz = new String[rows][columns];
    
            for (int i = 0; i < columns; i++) {
                for (int j = 0; j < rows; j++) {
                    Cell cell = sheet.getCell(i, j);
                    matriz[j][i] = cell.getContents();
                }
            }
        }
    }
    
    private static String padRight(String s, int tamanho) {
        StringBuilder sb = new StringBuilder(tamanho);
        sb.append(s);
        for (int i = s.length(); i < tamanho; i++) {
            sb.append(' ');
        }
        return sb.toString();
    }
    
    public void imprimirMatriz(String[][] matriz) {
    
        // Primeiro calcula o tamanho de cada coluna.
        int colunas = matriz[0].length;
        int[] tamanhoColunas = new int[colunas];
        for (String[] linha : matriz) {
            for (int i = 0; i < colunas; i++) {
                int t = linha[i].length();
                if (tamanhoColunas[i] < t) tamanhoColunas[i] = t;
            }
        }
    
        // Imprime a matriz.
        // Usa a função padRight para preencher os espaços corretamente.
        for (String[] linha : matriz) {
            for (int i = 0; i < colunas; i++) {
                System.out.print(padRight(linha[i], tamanhos[i] + 1));
            }
            System.out.println();
        }
    }
    
    public void teste() {
        String[][] matriz = planilha("C:\Users\lm\Desktop\planilha.xls");
        imprimirMatriz(matriz);
    }
    
        
    21.12.2016 / 18:07