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>
}
“`
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:
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.