es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Escribir datos en un archivo excel xls utilizando Java.

Tengo datos guardados en una tabla (que ya los he recopilado de un archivo) y quiero escribirlos en un archivo Excel xls usando Java.

Solo estoy compartiendo la clase principal, porque muestra cómo guardo mis datos en una tabla.

“`
public static void main(String args[]) throws FileNotFoundException {

<pre><code>SylkParser test = new SylkParser();

Reader reader = new FileReader("file.slk");

List<sylkrecord> parsed = test.parseRecords(reader);

SylkSheet sheet = new SylkSheet(parsed);

String[][] table = new String[47][8];
// imprimir matriz en forma rectangular
for (int i=1; i<47; i++) {
for (int j=1; j<8; j++) {

String data = new String();

if (sheet.getCell(i,j) == null) { data = ""; }

else if (sheet.getCell(i,j).valueStr instanceof String) {data = sheet.getCell(i,j).valueStr; }

else if (sheet.getCell(i,j).valueNumber instanceof Number) {data = sheet.getCell(i,j).valueNumber.toString();}

table[i][j]=data;//tu valor
System.out.println(table[i][j]);

}
}
</code></pre>

}
“`

Tags:  ,

Answer

  1. Avatar for davy.ai

    Para escribir los datos recopilados en un archivo Excel xls, podemos utilizar la biblioteca Apache POI que proporciona clases y métodos para crear y modificar archivos de Microsoft Office. Aquí hay un ejemplo de cómo utilizar POI para crear un nuevo archivo xls y llenarlo con los datos de la tabla que hemos creado:

    import java.io.FileOutputStream;
    import java.io.IOException;
    import org.apache.poi.ss.usermodel.Cell;
    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.xssf.usermodel.XSSFWorkbook;
    
    public static void main(String args[]) throws FileNotFoundException {
    
            //... código previo para crear la tabla ...
    
            Workbook workbook = new XSSFWorkbook(); // crear una nueva instancia de Workbook
            Sheet sheet = workbook.createSheet("Hoja 1"); // crear una nueva hoja
    
            // llenar la hoja con datos de la tabla
            for (int i = 0; i < table.length; i++) {
                Row row = sheet.createRow(i);
                for (int j = 0; j < table[0].length; j++) {
                    Cell cell = row.createCell(j);
                    cell.setCellValue(table[i][j]);
                }
            }
    
            try {
                FileOutputStream outputStream = new FileOutputStream("archivo_salida.xlsx");
                workbook.write(outputStream);
                outputStream.close();
                System.out.println("Archivo Excel escrito exitosamente.");
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    

    En este ejemplo, creamos una nueva instancia de XSSFWorkbook, creamos una nueva hoja llamada “Hoja 1” utilizando el método createSheet, y luego llenamos la hoja con los datos de nuestra tabla utilizando un bucle for anidado. Finalmente, escribimos el libro de trabajo en un nuevo archivo llamado “archivo_salida.xlsx” utilizando un FileOutputStream.

    Se debe tener en cuenta que estamos utilizando XSSFWorkbook en lugar de HSSFWorkbook, ya que este último es para el formato de archivo xls más antiguo (anterior a 2007), mientras que el primero es para el formato xlsx más nuevo.

Comments are closed.