How to read an Excel 2013 spreadsheet and write to a Postgresql database?

Asked

Viewed 5,993 times

1

I’m having trouble recording information in the database.

This information I extract from an Excel file.

For example, I have 3 fields and do not know how to take the first cell and record in the bank, then take the second and record and finally take the third and record.

Remembering that are various information that each column has.

My code is like this:

public void readingSheet(String path) {

    try {  

       File file = new File(path);  

       String name = file.toString();  

       int pos = name.lastIndexOf('.');  

       String ext = name.substring(pos + 1);  

       FileInputStream fileIn = new FileInputStream(file);  

       Workbook obj = null;  

       if (ext.equals("xlsx")) {

           try {  
               //Metodo aceita o path do arquivo  
               obj = new XSSFWorkbook(fileIn);  
           } 

           catch (IOException ex) {  
               throw new RuntimeException(ex);  
           }  
       } 

       else if (ext.equals("xls")) {  

           try {  
               //Metodo nao aceita string do path do arquivo  
               obj = new HSSFWorkbook(fileIn);  
           } 
           catch (IOException e) {  
               throw new RuntimeException(e);  
           }  
       }  

       else {  
           throw new IllegalArgumentException("Arquivo recebido não é uma extensão do Excel");  
       }  

       int o = 0;  

       Sheet worksheet = obj.getSheet("Plan1");  

       Row row;  

       Cell cell;  

       for(int i = 1; i<= worksheet.getLastRowNum(); i++){  

           row = worksheet.getRow(i);  

           String linha = "";  

           for(int j = 0; j < 3; j++) {  
               cell = row.getCell(j);  

               if(cell.getCellType()==1)   {
                   linha += " | " + cell.getStringCellValue();
               }

               else {  
                   double aux = 0;  
                   int aux2 = 0;  
                   aux = cell.getNumericCellValue();  
                   aux2 = (int) aux;  
                   linha += " | " + aux2;
              }  
          }  
           System.out.println("");
           System.out.println("Linha: " + linha);  
           System.out.println("");
       }    

   } 

    catch (FileNotFoundException e) {  
      e.printStackTrace();
   }  

}

Thank you all.

  • Could you give examples of column values? Depending on the case if possible, it is simpler to convert the spreadsheet to csv and import this file directly from the database.

  • Of course, username "Fernando" - fullname "Fernando Santos" - password "test"

1 answer

1

I advise to use the library jxl to manipulate excel spreadsheets. I just did not test with excel 2013. Here’s an example of manipulation

The example code is this

import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.read.biff.BiffException;

public void readingSheet(String caminho_arquivo_xls) {
    //objeto relativo ao arquivo excel
    Workbook workbook = null;

    try {
        //Carrega planilha
        WorkbookSettings config = new WorkbookSettings();
        config.setEncoding("Cp1252");//configura acentuação
        workbook = Workbook.getWorkbook(new File(caminho_arquivo_xls),config);//recupera arquivo desejado
        //recupera pagina/planilha/aba do arquivo
        Sheet sheet = workbook.getSheet(0);
        //recupera numero de linhas
        int linhas = sheet.getRows();
        //percorre todas as linhas da planilha
        for (int row = 0; row < linhas; row++) {
            //cria meu objeto que recebe as linhas
            MeuObjeto objeto = new MeuObjeto();
            //verifica se coluna 0 (A) e linha row não é vazia
            if(!sheet.getCell(0,row).getContents().isEmpty()){
                //recupera informação da coluna A linha row.
                objeto.setDadoA(sheet.getCell(0, row).getContents().toString());
            }
            if(!sheet.getCell(1,row).getContents().isEmpty()){
                //recupera informação da coluna B linha row.
                objeto.setDadoB(sheet.getCell(1, row).getContents().toString());
            }
            //chama meu objeto que faz o serviço de salvar no banco de dados
            bancodados.salvarDado(objeto);
        }

    } catch (IOException e) {
        print_erro(e);
    } catch (BiffException e) {
        print_erro(e);
    } catch (NumberFormatException e) {
        print_erro(e);
    } catch(Exception e){
        print_erro(e);
    } finally {
        //fechar
        if (workbook != null)
            workbook.close();
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.