1

Preciso editar um arquivo XLS já criado, porém estou conseguindo apenas se crio um arquivo novo e deleto o antigo, até agora está dando certo porém gostaria de saber se é possível editar o arquivo antigo e não ter que deletar o antigo e criar um novo com o mesmo nome.

    String autEdit = request.getParameter("aut");
    response.setContentType("text/html;charset=UTF-8");
    File file = new File("C:\\Tratados\\4-600dpi.xls");
    Workbook workbook = null;
    try {
        workbook = Workbook.getWorkbook(new File("C:\\teste.xls"));
    } catch (BiffException ex) {
        Logger.getLogger(autorizacao.class.getName()).log(Level.SEVERE, null, ex);
    }
    WritableWorkbook copy = Workbook.createWorkbook(new File("C:\\Teste.xls"), workbook);

    Sheet sheet = workbook.getSheet(0);
    int linhas = sheet.getRows();
    int i = 0, x = 0;
    WritableSheet sheet2 = copy.getSheet(0);
    for (i = x; i < linhas; i++) {
        Cell a1 = sheet.getCell(0, i);
        WritableCell a2 = sheet2.getWritableCell(1, i);
        WritableCell a3 = sheet2.getWritableCell(2, i);

        String as1 = a1.getContents();
        String as2 = a2.getContents();
        String as3 = a3.getContents();

        if ("-".equals(as2)){
            Label l = (Label) a2;
            l.setString(autEdit);
            Label ll = (Label) a3;
            ll.setString("Editado");
            linhas = i - 1;

        }
    }
    copy.write();
    file.delete();
    try {
        copy.close();
    } catch (WriteException ex) {
        Logger.getLogger(autorizacao.class.getName()).log(Level.SEVERE, null, ex);
    }
    workbook.close();

3 Respostas 3

1

Usando a biblioteca Apache Poi você pode fazer de uma das seguintes maneiras:

XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(caminho));

OU ainda

 Workbook wb = WorkbookFactory.create(new File(caminho));

Onde caminho é uma string com o caminho para o seu arquivo fisico.
Uma vez que tenha o workbook você pode manipular as planilhas, células entre outros atributos como quiser, da maneira que já está fazendo no trecho de código apresentado.

Esta referência possui um link para uma classe java que exemplifica a leitura de um arquivo existente no item "Reading or modifying an existing file": http://poi.apache.org/spreadsheet/how-to.html#user_api

4
  • WorkbookFactory está dando um erro dizendo que precisaria criar uma classe no pacote, não teria apenas que colocar a importação ou o WorkbookFactory não esta incluso na biblioteca JXL que é a que estou usando
    – R.Santos
    21/09/2016 às 14:26
  • Então, a solução que postei é usando a Apache POI, que considero uma biblioteca melhor e mais atualizada para trabalhar com excel no Java. Você está usando a JExcelAPI provavelmente por isso está dando erro. 21/09/2016 às 14:30
  • Ah certo vou tentar baixar essa biblioteca então e testar tua solução? Tu teria por acaso um link para download dessa biblioteca?
    – R.Santos
    21/09/2016 às 14:32
  • Procure nesta página poi.apache.org/download.html É bem semelhante a que você está usando, encontre exemplos dela neste link: poi.apache.org/spreadsheet/quick-guide.html 21/09/2016 às 16:01
1

Consegui desta forma editar uma planilha já criada:

try {
        HSSFWorkbook workbook;
        try (FileInputStream file = new FileInputStream(new File("C:\\teste.xls"))) {
            workbook = new HSSFWorkbook(file);
            HSSFSheet sheet = workbook.getSheetAt(0);
            for (int i = 0; i < sheet.getPhysicalNumberOfRows(); i++) {

                Row row = sheet.getRow(i);
                org.apache.poi.ss.usermodel.Cell a1 = row.getCell(1);
                org.apache.poi.ss.usermodel.Cell a2 = row.getCell(2);

                String as1 = a1.getStringCellValue();

                if (as1.equals("-")) {
                    a1.setCellValue("teste");
                    a2.setCellValue("EDITADO");
                    i = sheet.getPhysicalNumberOfRows();
                }
            }
            file.close();

            FileOutputStream outFile = new FileOutputStream(new File("C:\\teste.xls"));
            workbook.write(outFile);
            outFile.close();
            System.out.println("Arquivo Excel editado com sucesso!");
        }
    } catch (FileNotFoundException e) {
        System.out.println("Arquivo Excel não encontrado!");
    } catch (IOException e) {
        System.out.println("Erro na edição do arquivo!");
    }
0

isso ai resolve o que precisa

    XSSFWorkbook workbook = null;
File file = new File("C:\\Teste.xls");
FileOutputStream out = null;
XSSFSheet excelSheet = null;
CellStyle style = null;
XSSFFont font = null;
Map<String, Object[]> excelData = new TreeMap<String, Object[]>();
// verifica se o arquivo existe
if (file.exists()) {
    FileInputStream inputStream = new FileInputStream(file);
    workbook = new XSSFWorkbook(inputStream);
    // vefirifica se planilha existe
    if (workbook.getSheet(excelSheetName) != null) {
        excelSheet = workbook.getSheet(excelSheetName);
    } else {
        excelSheet = workbook.createSheet(excelSheetName);
        addIntoCell(excelData, excelSheet, "0", style);
    }
} else {
    workbook = new XSSFWorkbook();
    if (workbook.getSheet(excelSheetName) != null) {
        excelSheet = workbook.getSheet(excelSheetName);
    } else {
        excelSheet = workbook.createSheet(excelSheetName);
       // vefirifica se planilha existe
        addIntoCell(excelData, excelSheet, "0", style);
    }
}

Depois feche os stream abertos

2
  • o XSSFWorkbook fica dizendo que é necessário criar uma classe para ele no pacote, o XSSFWorkbook não é incluso na biblioteca JXL que é a que estou usando?
    – R.Santos
    21/09/2016 às 14:28
  • Deve ser porque a classe é protegida, veja outra class em sua lib JXL que seja semelhante e use. 21/09/2016 às 14:34

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .