How To Read / Write Excel Spreadsheet From Java Como a leitura / escrita de planilha Excel Java
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);)
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.
Filed under Arquivado em Enterprise Software Enterprise Software , De Headline News Headline News , De How To How To , De J2EE , De Java Software Java Software , De Open Source Software Open Source Software , De Programming Programação | |
| |
RSS 2.0 RSS 2,0 | |
Trackback this Article | este artigo |
Email this Article E-mail este artigo
You may also like to read Você pode também gosta de ler |




May 24th, 2007 at 1:32 pm 24 de maio de 2007 em 1:32 pm
Thanks, Obrigado,
4 the script. 4 o script.
Peter
May 25th, 2007 at 2:12 am 25 de maio de 2007 em 2:12 am
What do you think of jxls (http://jxls.sourceforge.net) ? O que você acha do jxls (http://jxls.sourceforge.net)?
May 26th, 2007 at 5:41 pm 26 de maio de 2007 em 5:41 pm
jxls is simply a wrapper on top of poi to make it easier to create complex excel reports. jxls é simplesmente um wrapper em cima de PI para tornar mais fácil para criar relatórios complexos excel. It is not a substitute for poi-hssf or jexcelapi. Não se trata de um substituto para poi-HSSF ou jexcelapi.
May 31st, 2007 at 9:50 pm 31 de maio de 2007 em 9:50 pm
please tell me how to create a dropdownlist in excel por favor me diga como criar um dropdownlist no Excel
with POI. com PI. Thanks alot. Thanks a lot.
June 4th, 2007 at 12:16 pm 4 de junho de 2007 em 12:16
Interesting comparison of ExcelAPI with Jakarta-POI. Interessante comparação de ExcelAPI com Jacarta-PI. Very useful, thanks for the article. Muito útil, graças ao artigo.
June 20th, 2007 at 7:23 pm 20 de junho de 2007 em 7:23 pm
Sin ningun lugar a dudas poi es un excelente framework para el manejo de hojas de calculo, lo uso desde hace bastante tiempo y nunca tuve mayoer problemas. Sin ningun lugar uma dudas poi es un excelente quadro para el Manejo de hojas de calculo, em verdade, uso desde hace bastante tiempo y nunca tuve mayoer problemas.
July 20th, 2007 at 4:29 am 20 de julho de 2007 em 4:29 am
How did you conclude JExcel API is not suitable for Enterprise? Como você se concluir JExcel API não é adequado para a Empresa?
Can you list the problems faced using JExcel API and how did you overcome them in Jakarta POI? Você pode listar os problemas enfrentados usando JExcel API e como você superá-los em Jacarta PI?
July 26th, 2007 at 1:11 am 26 de julho de 2007 em 1:11 am
There is another choice. Há uma outra escolha.
Jxcell spreadsheet component Jxcell componente planilha
August 14th, 2007 at 3:56 pm 14 de agosto de 2007 em 3:56 pm
En que idioma esta esto Que um idioma en esta esto
August 21st, 2007 at 8:22 am 21 de agosto de 2007 em 8:22 am
plz tell me how i can fetch the data from excel sheet in c code::::::plzzzzz………. plz me dizer como eu posso ir buscar os dados a partir de excel folha, c código :::::: plzzzzz……….
thanks::::: graças :::::
August 31st, 2007 at 1:42 pm 31 de agosto de 2007 em 1:42 pm
Did you test POI for newer versions of Excel than 2002? Foram testados POI para versões mais recentes do Excel do que 2002? Will POI read an Excel 2005 spreadsheet with just basic data? PI irá ler uma planilha Excel 2005 com apenas dados básicos?
September 1st, 2007 at 6:13 am 1 de setembro de 2007 em 6:13 am
@Neelam, @ Neelam,
The best I can suggest is look into the Excel dll files for their interface. O melhor que posso sugerir é olhar para os ficheiros Excel dll para a sua interface. I haven’t read Excel speradsheet in C / C++. Não li Excel speradsheet em C / C + +.
@John, @ John,
I have been using it on client supplied Excel files. Tenho vindo a utilizá-lo cliente fornecidos ficheiros Excel. I don’t know their versions as I use Open Office or Gnumeric to open them on Linux. Não sei como eu usar suas versões Open Office ou gnumeric para abri-las em Linux.
October 23rd, 2007 at 7:26 pm Outubro 23o, 2007 em 7:26 pm
very helpful script! script muito útil! i have another question, though. Tenho uma outra questão, no entanto. have you tried reading charts from an excel file? você já tentou ler gráficos a partir de um arquivo excel? do you have a sample code for that? você tem uma amostra de código que? thank you in advance! agradeço-lhe antecipadamente!
October 25th, 2007 at 6:23 am Outubro 25o, 2007 em 6:23 am
I want to know how to append the spreadsheet using java .Please let me know soon . Eu quero saber a anexar a planilha usando java. Entre em contato conosco em breve. thanks obrigado
October 25th, 2007 at 8:31 am Outubro 25o, 2007 em 8:31 am
Senthil,
Use Jakarta-POI (HSSF) for that. Use Jacarta-PI (HSSF) para isso.
October 31st, 2007 at 1:42 pm Outubro 31o, 2007 em 1:42 pm
You have given example for reading the excel file. Você tem dado exemplo para a leitura do ficheiro Excel. Do you have code snippet to write data to excel template with POI? Você tem code snippet para gravar dados no modelo em excel PI?
November 3rd, 2007 at 7:32 am 3 de novembro de 2007 em 7:32 am
HI.. HI ..
i want to automate the scripting,, so i want the to read the data from excel sheet & with that date it has to write it in to the another text files,, so i can i have source code for this single case.. eu quero automatizar o scripting, de modo a que eu quero para ler os dados da folha de excel e com essa data que tem a escrevê-la para o outro texto em arquivos,, então eu posso ter o código fonte para este único caso ..
November 13th, 2007 at 6:13 am 13 de novembro de 2007 em 6:13 am
Hi.. Oi ..
I need to write data from a microsoft access database onto an excel sheet and any changes or updations in the database should also be reflected on the excel sheet.. Eu preciso escrever os dados de um banco de dados Microsoft Access para uma folha de excel e de quaisquer alterações ou updations na base de dados deverá também ser reflectido sobre a folha excel .. Can anyone help?? Alguém pode ajudar?
Same with importing data from excel to database! Mesmo com o Excel para importar dados de banco de dados!
Thanks.. Obrigado ..
November 13th, 2007 at 12:41 pm 13 de novembro de 2007 em 12:41
You should use Java to transfer data from MS Access to MS Excel. Você deve usar Java para transferir dados do MS Access para MS Excel.
Use the above tutorial to read / write from MS Excel. Use o tutorial acima de leitura / gravação do MS Excel.
Read the Leia o tutorial to read / write from Microsoft Access database using Java tutorial para leitura / escrita de banco de dados Microsoft Access usando Java .
November 13th, 2007 at 12:43 pm 13 de novembro de 2007 em 12:43 pm
Erwin said> have you tried reading charts from an excel file? Erwin disse> Você tentou ler cartas de um arquivo excel?
No. Não.
November 14th, 2007 at 3:40 am 14 de novembro, 2007 at 3:40 am
Thanku angs.. Thanku angs ..
I did use ur code to read an excel file and got too exceptions as ArrayIndexOutOfBound and 2 more.. Eu fiz uso ur código para ler um arquivo excel e comecei também exceções como ArrayIndexOutOfBound e mais 2 ..
If u can jus help me to write whats in my acess database onto an excel file i’ll be thankful.. Se u jus pode ajudar-me a escrever Então, em minha acessos de dados para um arquivo excel Eu vou ser agradecido .. Will be glad if I get some code on it!!! Ficará satisfeito se eu tirar algum código sobre ela!
January 18th, 2008 at 2:45 am 18 de janeiro de 2008, 2:45 am
thx for the info! THX para a info!
January 24th, 2008 at 3:47 am 24 de janeiro de 2008, 3:47 am
I want to write the data in Excel File . Gostaria de escrever os dados no ficheiro Excel. (ie) I want to append the excel file . (ie) Gostaria de anexar o ficheiro Excel. how can i do that? como posso fazer isso?
The original file\’s soft copy is in one subfolder of my project. O arquivo original \ 's soft cópia se encontra em uma subpasta do meu projeto. I want to overwrite that file . Eu quero que sobrescrever o arquivo. Pls help . Pls help. I use jxl jar file in my project . Eu uso jxl arquivo jar do meu projeto.
Thanks in Advance Graças em adiantado
Ganesh
February 4th, 2008 at 1:17 am 4 de fevereiro de 2008, 1:17 am
I used the same code. Eu usei o mesmo código. In the biginning i have only No biginning Tenho apenas
1000 rows, 26 columns then it was working properly. 1000 linhas, 26 colunas então ela estava trabalhando corretamente.
Here the proble cames, now i hav 3000 rows, 29 colomns; at first, my program had worked properly but its taken 1.26 minuts to finish up and i cheacked ie. Aqui o proble vem, agora eu hav 3000 linhas, 29 colomns; em primeiro lugar, o meu programa tinha trabalhado corretamente, mas a sua tomada 1,26 minutos para concluir e i cheacked ie.
taking more time in executing this single line “HSSFWorkbook wb = new HSSFWorkbook(fs);”. tendo mais tempo na execução desta linha única "HSSFWorkbook bu = new HSSFWorkbook (FS);". and at the next time i got this Exception in thread “main” java.lang.OutOfMemoryError: Java heap space. e, na próxima vez que eu comecei esta excepção no tópico "principais" java.lang.OutOfMemoryError: Java heap espaço. finally i executed the same code in some other system, again the same problem… i finalmente executado o mesmo código em algum outro sistema, mais uma vez o mesmo problema…
plz help me to solve this problem.. plz me ajudar a resolver este problema ..
Thanks in Adwnc Graças, em Adwnc
Nandu. NANDU.
February 4th, 2008 at 7:04 am 4 de fevereiro de 2008 em 7:04 am
Thanks Angsuman for this introduction which helped me choose POI. Angsuman Graças a esta introdução, que me ajudou a escolher PI.
I had some difficulty understanding the difference between physical and logical rows and cells and I found out that your code is not working when there are empty rows. Eu tive dificuldade em compreender a diferença entre física e lógica e de linhas de células e eu descobri que seu código não está a funcionar quando há linhas vazias.
You mention in already in your “gotcha’s” but it’s actually the other way around Você menciona, já no seu "gotcha's", mas ele é realmente o contrário
getPhysicalNumberOfRows() may be LESS than the actual rows (retrieved by getLastRowNum() ). getPhysicalNumberOfRows () pode ser inferior ao real linhas (recuperado por getLastRowNum ()).
In your example you mix up the getPhysicalNumberOfRows() and the sheet.getRow(int) which returns the logical row in the sheet which might be a different one if you have empty rows. No seu exemplo você misturar getPhysicalNumberOfRows () e os sheet.getRow (int), que retorna a lógica fila na folha que poderia ser diferente se você tem linhas vazias. The same goes for columns. O mesmo vale para colunas.
February 6th, 2008 at 5:41 pm 6 de fevereiro de 2008 em 5:41 pm
POI HSSF was not usable for me mainly because it didn’t know how to write out number values with the correct format - so things which were percentages in the spreadsheet like “83%” might come out of POI as “0.834444″ which doesn’t work with the rest of the pipeline. POI HSSF não era utilizável por mim principalmente porque não sabemos como escrever no número valores com o formato correto - coisas que eram tão percentagens na planilha como "83%" poderá sair da PI como "0,834444" que doesn ' t trabalhar com o resto do oleoduto.
March 6th, 2008 at 6:43 am 6 de março, 2008, 6:43 am
how to read upload Excel sheet in tamil font in java code a ler upload Excel folha em Tamil código fonte em java
I would like to upload Excel sheet in tamil font using java code Gostaria de fazer upload Excel folha em Tamil java código fonte utilizando
help me ajude-me
April 6th, 2008 at 7:11 am 6 de abril de 2008, 7:11 am
ur’s mail id please, by which i mail u regardings my problems in programing ur correio do id, por favor, pelo que o meu i mail u regardings problemas na programação
April 15th, 2008 at 8:37 am 15 de abril de 2008, 8:37 am
I have one excel file which is 51MB size. Eu tenho um arquivo excel que é 51MB tamanho. i tried to open using POI but fails. eu tentei usar para abrir PI, mas falha. I saved the file using MS Excel with different file name and opened it with POI, it works. Eu salvar o arquivo usando o MS Excel com várias nome do arquivo e abri-la com a PI, ela funciona.
Is it the file problem or with POI? Será que é o arquivo ou a PI problema?
Please suggest. Por favor, sugerem.
April 16th, 2008 at 12:37 pm 16 de abril de 2008, 12:37 pm
I would guess that it is the problem of the spreadsheet. Gostaria de adivinhar que é o problema da folha de cálculo.
April 16th, 2008 at 12:40 pm 16 de abril de 2008, 12:40 pm
I have used POI with thousands of complex spreadsheets without any issues at all. Eu tenho usado PI com milhares de planilhas, sem qualquer complexo em todas as questões.
April 18th, 2008 at 4:18 am 18 de abril de 2008, 4:18 am
I tried POI , with Excel 2003, it’s writing fine , but when I’m trying to open it corrupts the whole Excel file. Tentei PI, com o Excel 2003, é escrever muito bem, mas quando eu estou a tentar abrir ele corrompe todo o ficheiro Excel.
So I tried with JXl, here writing & opening is ok, But it’s not appending new sheet’s. Então, eu tentei com JXl, aqui está escrito e abertura ok, mas também não é aposição da nova folha. it’s always replaces old sheet with newly created sheet.Please any one can help me. é sempre substitui a velha folha recém-criada sheet.Please qualquer um pode ajudar-me.
April 26th, 2008 at 2:02 am 26 de abril de 2008, 2:02 am
Hi, Oi,
Sorry that I am putting question of Jxl in POI forum. Lamentamos que estou colocando em questão de Jxl PI fórum.
I am getting error “java.lang.OutOfMemoryError: Java heap space” while reading file with 10000 records and 95 columns. Estou recebendo erro "java.lang.OutOfMemoryError: Java heap espaço" ao ler arquivo com 10000 registros e 95 colunas. size of file is 14M. tamanho do arquivo é 14m.
I am testing my application through JProfiler. Estou testando o meu pedido através JProfiler.
Is there any restriction of file size or problem while reading throught jxl? Existe alguma restrição do tamanho do ficheiro ou problema ao ler jxl pensamento?
Can anybody help me. Alguém pode me ajudar.
Thanks Obrigado
May 20th, 2008 at 3:07 pm 20 de maio, 2008, 3:07 pm
what do i import to use the JExcelAPI? O que eu importação para usar o JExcelAPI?
June 1st, 2008 at 11:24 am 1 de junho de 2008 em 11:24 am
but how to read excel sheets carying non english language as arabic ? mas a ler folhas Excel carying não Inglês como língua árabe?
June 2nd, 2008 at 12:34 am 2 de junho de 2008, 12:34 am
Mohamed,
I don’t know. Eu não sei. I haven’t tried it. Eu não tentei-o.
June 10th, 2008 at 3:32 am 10 de junho, 2008, 3:32 am
hello everybody, Olá todos,
i have a small problem and need your help on it Eu tenho um pequeno problema, e por isso precisamos da sua ajuda
i need to access my .mpp (Microsoft Project) File eu necessito para acessar a minha. MPP (Microsoft Project) Arquivo
From java…..How can i do that? De java… .. Como posso fazer isso?
knowing that using ready made components is not allowed. sabendo que utilizam componentes prontos feita não é permitido.