Overview Descripción general

There are two good choices for reading & writing Microsoft Excel Spreadsheet files from Java, in a platform independent way, - jexcelapi and Jakarta POI (HSSF) . Hay dos buenas opciones para la lectura y la escritura de hoja de cálculo Microsoft Excel archivos de Java, una plataforma en forma independiente, - jexcelapi Yakarta y POI (HSSF). Both of them provide nice interface to access Excel data structure and even generate new spreadsheet. Ambos proporcionan agradable interfaz de acceso a Excel estructura de datos e incluso generar nuevos hoja de cálculo. I have done extensive tests with both of them for a high-profile project for a Fortune 500 company. Me han hecho extensas pruebas con los dos de ellos de un alto perfil de proyecto para una compañía Fortune 500. Previously also I had successfully used HSSF for another high profile client. Anteriormente también tuve HSSF utilizado con éxito para otro cliente de alto perfil. In the paragraphs below I present my conclusions and sample code for reading Excel spreadsheet from Java using both the libraries. En los párrafos que figuran a continuación presento mis conclusiones y código de muestra para la lectura de hoja de cálculo de Excel utilizando Java, tanto las bibliotecas.

Comparison of JExcelAPI with Jakarta-POI (HSSF) Comparación de JExcelAPI con Yakarta-POI (HSSF)

1. JExcelAPI is clearly not suitable for important data. evidentemente no es adecuado para los datos importantes. It fails to read several files. No para leer varios archivos. Even when it reads it fails on cells for unknown reasons. Incluso cuando se dice que no en las células por razones desconocidas. In short JExcelAPI isn’t suitable for enterprise use. En resumen JExcelAPI no es adecuado utilizar en favor de la empresa.

2. HSSF is the POI Project’s pure Java implementation of the Excel ‘97(-2002) file format. es el PI del Proyecto puro Java de la aplicación Excel'97 (-2002) formato de archivo. It is a mature product and was able to correctly and effortlessly read excel data generated from various sources, including non-MS Excel products like Open Office, and for various versions of Excel. Es un producto maduro y era capaz de forma correcta y sin esfuerzo leer los datos de Excel generados a partir de diversas fuentes, incluidos los no-MS Excel productos como el Open Office, así como para diversas versiones de Excel. It is very robust and well featured. Es muy robusto y bien presentado. Highly recommended. Altamente recomendada.

3. Performance was never a consideration in our tests because a) data integrity is the single most important factor and b) there didn’t appear to be any significant performance difference while running the tests; both of them were very fast. La ejecución nunca ha sido una consideración en nuestras pruebas porque a) la integridad de los datos es el factor más importante y b) no parece haber ninguna diferencia significativa el rendimiento durante la ejecución de las pruebas, tanto de ellos eran muy rápido. We didn’t bother to time it for the above reasons. No molestar a tiempo, por las razones antes mencionadas.

How to read Excel Excel Spreadsheet from Java using Jakarta POI (HSSF) Cómo leer Excel Hoja de cálculo de Excel utilizando Java Yakarta POI (HSSF)

 try {     POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream( file ));     HSSFWorkbook wb = new HSSFWorkbook(fs);     HSSFSheet sheet = wb.getSheetAt(0);     HSSFRow row;     HSSFCell cell;      int rows; // No of rows     rows = sheet.getPhysicalNumberOfRows();      int cols = 0; // No of columns     int tmp = 0;      // This trick ensures that we get the data properly even if it doesn’t start from first few rows     for(int i = 0; i < 10 || i < rows; i++) {         row = sheet.getRow(i);         if(row != null) {             tmp = sheet.getRow(i).getPhysicalNumberOfCells();             if(tmp > cols) cols = tmp;         }     }      for(int r = 0; r < rows; r++) {         row = sheet.getRow(r);         if(row != null) {             for(int c = 0; c < cols; c++) {                 cell = row.getCell((short)c);                 if(cell != null) {                     // Your code here                 }             }         }     } } catch(Exception ioe) {     ioe.printStackTrace(); } try (POIFSFileSystem fs = new POIFSFileSystem (nuevo FileInputStream (archivo)); HSSFWorkbook WB = new HSSFWorkbook (fs); HSSFSheet hoja = wb.getSheetAt (0); HSSFRow fila; HSSFCell celda; int filas; / / n º de filas filas = sheet.getPhysicalNumberOfRows (); int cols = 0; / / n º de columnas int tmp = 0; / / Este truco asegura que se obtienen los datos correctamente, incluso si no se inicia desde primeras filas for (int i = 0; i <10 | | i <filas; i + +) (fila = sheet.getRow (i); if (fila! = null) (tmp = sheet.getRow (i). getPhysicalNumberOfCells (); if (tmp> cols) cols = tmp;)) for (int r = 0, r <filas; r + +) (fila = sheet.getRow (r); if (fila! = null) (for (int c = 0, c <cols, c + +) (celda Row.getCell = ((short) c); si (celular! = Null) (/ / Su código aquí))))) de capturas (Excepción OIE) (ioe.printStackTrace ();) 

This sample should get you started. Esta muestra debe ir abriendo boca. Don’t forget to import appropriately. No se olvide de importación adecuadamente.

Gotchas while using Jakarta POI (HSSF) Errores durante el uso de Yakarta POI (HSSF)

  • getPhysicalNumberOfRows() returns the physical number of rows which may be more than the actual (logical) number of rows. getPhysicalNumberOfRows () devuelve el número físico de filas que pueden ser más que el real (lógica) el número de filas. The same goes for getPhysicalNumberOfCells(). Lo mismo puede decirse de getPhysicalNumberOfCells ().
  • You should check for nulls when fetching the HSSFRow and HSSFCell objects as shown. Usted debe verificar para nulls cuando de buscar el HSSFRow y HSSFCell objetos como se muestra.
  • Remember that Excel tables are often sparsely populated. Recuerde que los cuadros de Excel son a menudo escasamente pobladas. So choose your data structures accordingly. Por lo tanto, elegir su estructuras de datos en consecuencia.
  • POI accesses the data by sheet. PI accede a los datos de hoja. In JExcelAPI you can directly access the data in any row and column. En JExcelAPI puede acceder directamente los datos en cualquier fila y columna.

How to access Excel Spreadsheet using JExcelAPI Cómo acceder a hoja de cálculo de Excel usando JExcelAPI

 File fp = new File(file); try {     Workbook wb = Workbook.getWorkbook(fp);     Sheet sheet = wb.getSheet(0);     int columns = sheet.getColumns();     int rows = sheet.getRows();      String data;     for(int col = 0;col < columns;col++) {         for(int row = 0;row < rows;row++) {             data = sheet.getCell(col, row).getContents();             // Your code here         }     } } catch(Exception ioe) {     System.out.println("Error: " + ioe); } Archivo fp = new File (archivo); try (Hoja de WB = Workbook.getWorkbook (fp); Hoja de hoja = wb.getSheet (0); int columnas = sheet.getColumns (); int filas = sheet.getRows (); String datos; for (int col = 0; col <columnas; col + +) (for (int fila = 0; fila <filas; fila + +) (datos = sheet.getCell (col, fila). getContents (); / / Su código aquí ))) De capturas (Excepción OIE) (System.out.println ( "Error:" + OIE);) 

Gotchas while using JExcelAPI Errores durante el uso de JExcelAPI

  • JExcelAPI may often fail to fetch the data from certain cells or even the whole sheet. JExcelAPI a menudo puede dejar de buscar los datos de determinadas células, o incluso toda la hoja. Unfortunately it gives a warning instead of an error to indicate the problem. Lamentablemente se da una advertencia en lugar de un mensaje de error para indicar el problema.
  • JExcelAPI doesn’t expose the full meta-data of the spreadsheet like POI does. JExcelAPI no exponer a la plena meta-datos de la hoja de cálculo como el PDI hace.
  • JExcelAPI doesn’t properly recognize the data type in cells. JExcelAPI no reconocer adecuadamente el tipo de datos en las celdas. In all cases it indicated String data in our tests even when there were numeric or date fields. En todos los casos de cadenas de datos se indica en nuestras pruebas, incluso cuando había numérico o los campos de fecha.

Concluding thoughts on accessing Excel spreadsheets from Java Reflexiones finales sobre el acceso a hojas de cálculo Excel de Java

Both JExcelAPI and Jakarta POI (HSSF) are open source software to read & write data from / to Excel spreadsheet even on non-Microsoft platforms. Ambos JExcelAPI y Yakarta POI (HSSF) son el software de fuente abierta para leer y escribir datos desde / a hoja de cálculo de Excel, incluso en que no sea de Microsoft plataformas. In my tests HSSF came out to be the clear leader and recommended solution because of robustness and features. En mis pruebas HSSF llegó a ser el claro líder y solución recomendada por la robustez y características.