Hssfworkbook - How to copy one spreadsheet to another?

Asked

Viewed 622 times

3

I have a spreadsheet of excel I need to copy some data into another spreadsheet. This old spreadsheet is like a "base", I need to copy only the header and caption part (with the cell style, in addition to the text).

I’m using the library Hssfworkbook, but I’m not sure how to proceed.

I saw in the stackoverflow ingles the code, but I found the medium confusing


abaOrigem = origem.getSheetAt(0);
abaDestino = destino.createSheet(abaOrigem.getSheetName());

for (int indiceLinha = 0; indiceLinha < 5; indiceLinha++) {
    copiarLinha(abaOrigem, abaDestino, destino, indiceLinha);
}

The error that appears:

Exception in thread "main" java.lang.NullPointerException
    at testeExcel.CopiaXLS.pegarValorCelula(CopiaXLS.java:102)
    at testeExcel.CopiaXLS.copiarLinha(CopiaXLS.java:63)
    at testeExcel.CopiaXLS.copiar(CopiaXLS.java:30)
    at testeExcel.app.main(app.java:14)
  • 2

    It is not easier for you to copy the file as a whole?

  • no.. pq this file means a "base file", it has data that will not be used in the new spreadsheet but other data will be copied.

  • So it improves a little your question by putting the format that the file is and some additional information, such as the code you tried so far...

  • I rewrote the question! thanks for the tip ;D

  • You want to completely copy a tab?

  • in the worksheet there are 2 tabs, the first tab want only the header (the first lines). In the second tab I want it complete

Show 1 more comment

1 answer

2


I created a class to accomplish what you want based on in this answer:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import static org.apache.poi.ss.usermodel.CellType.BLANK;
import static org.apache.poi.ss.usermodel.CellType.NUMERIC;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

public class CopiaXLS {

  public static void copiar(String caminho) throws IOException, InvalidFormatException {
    String extensao;
    Workbook origem;
    Workbook destino;
    Sheet abaOrigem;
    Sheet abaDestino;
    File arquivoDestino;

    extensao = caminho.substring(caminho.lastIndexOf("."), caminho.length());
    origem = WorkbookFactory.create(new File(caminho));

    if (extensao.toUpperCase().equals(".XLS")) {
      destino = new HSSFWorkbook();
    } else {
      destino = new SXSSFWorkbook();
    }

    // Primeira aba
    abaOrigem = origem.getSheetAt(0);
    abaDestino = destino.createSheet(abaOrigem.getSheetName());

    copiarLinha(abaOrigem, abaDestino, destino, 0); // Copia o cabeçalho

    // Segunda aba
    abaOrigem = origem.getSheetAt(1);
    abaDestino = destino.createSheet(abaOrigem.getSheetName());

    for (int indiceLinha = abaOrigem.getFirstRowNum(); indiceLinha < abaOrigem.getLastRowNum(); indiceLinha++) {
      copiarLinha(abaOrigem, abaDestino, destino, indiceLinha); // Copia o cabeçalho
    }

    origem.close();
    arquivoDestino = new File(caminho.substring(0, caminho.lastIndexOf(".")) + " - Cópia" + extensao);
    destino.write(new FileOutputStream(arquivoDestino));
    destino.close();
  }

  private static void copiarLinha(Sheet abaOrigem, Sheet abaDestino, Workbook destino, int indiceLinha) {
    Row linhaOrigem;
    Row linhaDestino;

    linhaOrigem = abaOrigem.getRow(indiceLinha);
    linhaDestino = abaDestino.createRow(indiceLinha);

    for (int indiceCelula = linhaOrigem.getFirstCellNum(); indiceCelula < linhaOrigem.getLastCellNum(); indiceCelula++) {
      Cell celulaOrigem = linhaOrigem.getCell(indiceCelula);
      Cell celulaDestino = linhaDestino.createCell(indiceCelula);
      CellStyle estiloDestino = destino.createCellStyle();

      definirValorCelula(celulaDestino, pegarValorCelula(celulaOrigem));
      estiloDestino.cloneStyleFrom(celulaOrigem.getCellStyle());
      celulaDestino.setCellStyle(estiloDestino);
    }
  }

  private static void definirValorCelula(Cell celula, Object valor) {
    if (valor instanceof Boolean) {
      celula.setCellValue((boolean) valor);
    } else if (valor instanceof Byte) {
      celula.setCellValue((byte) valor);
    } else if (valor instanceof Double) {
      celula.setCellValue((double) valor);
    } else if (valor instanceof String) {
      if (((String) valor).startsWith("=")) { //  Formula String
        celula.setCellFormula(((String) valor).substring(1));
      } else {
        celula.setCellValue((String) valor);
      }
    } else {
      throw new IllegalArgumentException();
    }
  }

  private static Object pegarValorCelula(Cell celula) {
    switch (celula.getCellTypeEnum()) {
      case BOOLEAN:
        return celula.getBooleanCellValue(); // boolean
      case ERROR:
        return celula.getErrorCellValue(); // byte
      case NUMERIC:
        return celula.getNumericCellValue(); // double
      case STRING:
      case BLANK:
        return celula.getStringCellValue(); // String
      case FORMULA:
        return "=" + celula.getCellFormula(); // Fórmula
      default:
        throw new IllegalArgumentException();
    }
  }
}

To run you use the following method:

public static void main(String[] args) {
  try {
    CopiaXLS.copiar("C:/meu arquivo.xls");
  } catch (IOException ex) {
    Logger.getLogger(Teste.class.getName()).log(Level.SEVERE, null, ex);
  } catch (InvalidFormatException ex) {
    Logger.getLogger(Teste.class.getName()).log(Level.SEVERE, null, ex);
  }
}
  • Thank you for your answer, you have helped me a lot already, but I still have one question. In the copy method, in the first tab I want to copy the first 5 lines and not only the first. But when I do this modification, or use the same as you did for the second tab, the error java.lang.Nullpointerexception appears

  • @Mariteixeira did the for from 0 to 4? Can you XLS to evaluate?

  • So... xls is my job, I can’t pass but yes, I did the 4

  • @Complicated mariteixeira. In which line gives the exception?

  • the error that appears is in the answer below

  • @Mariteixeira without the impossible file to help you more than that. Unfortunately you can not know what is wrong in the cell to treat this.

  • I made a file very similar to what I want to use... how do I send you and you see? I can add the file here (I’m new to the stack)

  • @Mariteixeira you can put it on google drive or anywhere else that gives you a link to download later and put the link in your question

  • Arq upload is blocked here, but I made a spreadsheet in Google Sheets so just export. https://docs.google.com/spreadsheets/d/1nAQCpJgDGwHAk-d80jpmpOxXFlSIql2l_PTvWKjXqKM/edit?usp=sharing

  • @Mariteixeira tested here and with this spreadsheet you Upou works normally

  • is... I think it’s a file error, I copied and pasted it into another file and it was. Thank you @sorack

  • @Mariteixeira tranquil. I will update my response to support XLSX also. One detail: Merged columns do not work correctly in this solution. If the answer has met you do not forget to mark it as chosen so that other people with the same doubt can benefit also.

Show 7 more comments

Browser other questions tagged

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