Overview Visão geral

There are two good choices for reading & writing Microsoft Excel Spreadsheet files from Java, in a platform independent way, - jexcelapi and Jakarta POI (HSSF) . Existem duas boas opções de leitura e escrita de arquivos Microsoft Excel Spreadsheet Java, na forma de uma plataforma independente, - jexcelapi Jacarta e POI (HSSF). Both of them provide nice interface to access Excel data structure and even generate new spreadsheet. Ambos de proporcionar-lhes acesso a interface agradável Excel estrutura de dados e até mesmo gerar nova planilha. I have done extensive tests with both of them for a high-profile project for a Fortune 500 company. Eu tenho feito testes extensivos com tanto deles para um projeto de alto nível para uma empresa Fortune 500. Previously also I had successfully used HSSF for another high profile client. Eu também tinha anteriormente utilizado com sucesso HSSF para outro grande visibilidade cliente. In the paragraphs below I present my conclusions and sample code for reading Excel spreadsheet from Java using both the libraries. Nos parágrafos abaixo a apresentação do meu conclusões eo código de amostra para a leitura de planilha Excel Java usando ambas as bibliotecas.

Comparison of JExcelAPI with Jakarta-POI (HSSF) Comparação de JExcelAPI com Jacarta-PI (HSSF)

1. JExcelAPI is clearly not suitable for important data. claramente não é o adequado para dados importantes. It fails to read several files. Ela não consegue ler vários arquivos. Even when it reads it fails on cells for unknown reasons. Mesmo quando se lê ele falhar em células por razões desconhecidas. In short JExcelAPI isn’t suitable for enterprise use. Em suma JExcelAPI não é adequado para uso empresarial.

2. HSSF is the POI Project’s pure Java implementation of the Excel ‘97(-2002) file format. PI é o Projeto da pura Java execução do Excel'97 (-2002) formato de arquivo. 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. É um produto maduro e foi capaz de ler correctamente e sem esforço excel dados gerados a partir de várias fontes, incluindo os não-MS Excel produtos como Open Office, e para várias versões do Excel. It is very robust and well featured. É muito sólido e bem caracterizado. Highly recommended. Altamente recomendado.

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. Desempenho nunca foi uma consideração em nossos testes, porque a) a integridade dos dados é o factor mais importante e, b) lá não se afigura nenhuma diferença significativa o desempenho do computador enquanto estiver executando os testes; tanto deles foram muito rápidos. We didn’t bother to time it for the above reasons. Nós não incomodar a tempo, pelas razões acima expostas.

How to read Excel Excel Spreadsheet from Java using Jakarta POI (HSSF) Como ler Excel Excel Spreadsheet de Java usando Jacarta 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(); } tente (POIFSFileSystem fs = new POIFSFileSystem (novo FileInputStream (arquivo)); HSSFWorkbook bu = new HSSFWorkbook (FS); HSSFSheet folha wb.getSheetAt = (0); HSSFRow fila; HSSFCell célula; int linhas; / / n º de linhas linhas = sheet.getPhysicalNumberOfRows (); int cols = 0; / / n º de colunas int tmp = 0; / / Esse truque garante que nós temos os dados corretamente mesmo que não comece a partir do primeiras fileiras para (int i = 0; i <10 | | i <linhas; i + +) (linha = sheet.getRow (i); se (fila! = null) (tmp = sheet.getRow (i). getPhysicalNumberOfCells (); se (tmp> cols) cols = tmp;)) for (int r = 0; r <linhas; r + +) (linha = sheet.getRow (r); se (fila! = null) (for (int c = 0, c <cols; c + +) (celular Row.getCell = ((curta) c); se (celular! = Null) (/ / Seu código aqui))))) catch (Excepção OIE) (ioe.printStackTrace ();) 

This sample should get you started. Esta amostra deve você começar. Don’t forget to import appropriately. Não se esqueça de importação adequadamente.

Gotchas while using Jakarta POI (HSSF) Gotchas enquanto utiliza Jacarta POI (HSSF)

  • getPhysicalNumberOfRows() returns the physical number of rows which may be more than the actual (logical) number of rows. getPhysicalNumberOfRows () retorna o número de linhas físicas que podem ser mais do que o real (lógico) número de linhas. The same goes for getPhysicalNumberOfCells(). O mesmo vale para getPhysicalNumberOfCells ().
  • You should check for nulls when fetching the HSSFRow and HSSFCell objects as shown. É preciso verificar quando nulls para tirar o HSSFRow e HSSFCell objetos como mostrado.
  • Remember that Excel tables are often sparsely populated. Lembre-se que muitas vezes são quadros Excel escassamente povoada. So choose your data structures accordingly. Portanto, escolha o seu estruturas de dados em conformidade.
  • POI accesses the data by sheet. PI acessa os dados por folha. In JExcelAPI you can directly access the data in any row and column. Em JExcelAPI você pode acessar diretamente os dados, em qualquer linha e coluna.

How to access Excel Spreadsheet using JExcelAPI Como aceder a planilha 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); } Arquivo fp = new File (arquivo); tente trabalho wb = (Workbook.getWorkbook (fp); Folha folha wb.getSheet = (0); int colunas = sheet.getColumns (); int linhas = sheet.getRows (); String dados; for (int col = 0; col <colunas; col + +) (for (int linha = 0; fila <linhas; row + +) (dados = sheet.getCell (col, linha). getContents () / / Seu código aqui ))) Catch (Excepção OIE) (System.out.println ( "Erro:" + OIE);) 

Gotchas while using JExcelAPI Gotchas enquanto utiliza JExcelAPI

  • JExcelAPI may often fail to fetch the data from certain cells or even the whole sheet. JExcelAPI maio muitas vezes não conseguem ir buscar os dados a partir de determinadas células, ou mesmo toda a folha. Unfortunately it gives a warning instead of an error to indicate the problem. Infelizmente, ele dá um aviso em vez de um erro ao indicar o problema.
  • JExcelAPI doesn’t expose the full meta-data of the spreadsheet like POI does. JExcelAPI não se expor a plena meta-dados da planilha como PI faz.
  • JExcelAPI doesn’t properly recognize the data type in cells. JExcelAPI não reconhecer corretamente o tipo de dados em células. In all cases it indicated String data in our tests even when there were numeric or date fields. Em todos os casos, é indicada String dados em nossos testes, mesmo quando havia numérica ou data campos.

Concluding thoughts on accessing Excel spreadsheets from Java Concluindo pensamentos sobre o acesso a partir de planilhas Excel Java

Both JExcelAPI and Jakarta POI (HSSF) are open source software to read & write data from / to Excel spreadsheet even on non-Microsoft platforms. Tanto JExcelAPI Jacarta e POI (HSSF) são software de fonte aberta para ler e gravar dados de / para a planilha Excel, mesmo em plataformas não-Microsoft. In my tests HSSF came out to be the clear leader and recommended solution because of robustness and features. Na minha testes HSSF veio a ser o líder e clara solução recomendada por causa da robustez e as características.