How To Read / Write Excel Spreadsheet From Java Как читать / писать электронную таблицу Excel с Явы
Overview Обзор
There are two good choices for reading & writing Microsoft Excel Spreadsheet files from Java, in a platform independent way, - jexcelapi and Jakarta POI (HSSF) . Есть два хороших вариантов для чтения и написания электронных таблиц Microsoft Excel файлов с Явы, в платформу независимым способом, - jexcelapi и Джакарте POI (HSSF). Both of them provide nice interface to access Excel data structure and even generate new spreadsheet. Оба они обеспечивают Удобный интерфейс для доступа к Excel структуры данных и даже создавать новые таблицы. I have done extensive tests with both of them for a high-profile project for a Fortune 500 company. Я сделал обширные тесты с обеими из них на высоком уровне проекта для компании Fortune 500. Previously also I had successfully used HSSF for another high profile client. Раньше я также успешно использоваться для другого HSSF высокий профиль клиента. In the paragraphs below I present my conclusions and sample code for reading Excel spreadsheet from Java using both the libraries. В пунктах ниже я представляю мои выводы и образец кода для чтения электронных таблиц Excel из Java с использованием библиотеки.
Comparison of JExcelAPI with Jakarta-POI (HSSF) Сравнение с JExcelAPI Джакарта-POI (HSSF)
1. JExcelAPI is clearly not suitable for important data. явно не подходит для важных данных. It fails to read several files. Она не может идти несколько файлов. Even when it reads it fails on cells for unknown reasons. Даже тогда, когда она в нем не говорится о клетках по неизвестным причинам. In short JExcelAPI isn’t suitable for enterprise use. Короче JExcelAPI не подходит для корпоративного использования.
2. HSSF is the POI Project’s pure Java implementation of the Excel ‘97(-2002) file format. является ТОИ проекта чистого Java осуществления Excel 97 (-2002) формат файла. 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. Она является зрелым продуктом и смог правильно и без усилий прочитать excel данных, полученных из различных источников, в том числе не являющихся MS Excel продуктов, как Open Office, а также для различных версий Excel. It is very robust and well featured. Очень надежные и хорошо признакам. Highly recommended. Высоко рекомендуется.
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. Производительность никогда не было рассмотрения в наших испытаниях, поскольку) целостности данных является одним из наиболее важных факторов и б) не существует, как представляется, каких-либо существенных различий производительности во время выполнения тестов; оба они были очень быстро. We didn’t bother to time it for the above reasons. Мы не смущает ко времени его выше причинам.
How to read Excel Excel Spreadsheet from Java using Jakarta POI (HSSF) Как читать Excel таблицу Excel с помощью Java Джакарте 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(); } попробуйте (POIFSFileSystem фс = новый POIFSFileSystem (новый FileInputStream (файл)); HSSFWorkbook ВБ = новый HSSFWorkbook (ПС); HSSFSheet листа = wb.getSheetAt (0); HSSFRow подряд; HSSFCell камере; int строк / / Нет строк строк = sheet.getPhysicalNumberOfRows (); int cols = 0; / / нет колонок int tmp = 0; / / Этот трюк гарантирует, что мы получаем данные должным образом, даже если оно не начинается с первой строки на несколько (я int = 0; я <10 | | я <рядами; я + +) (подряд = sheet.getRow (я), если (строка! недействительными =) (tmp = sheet.getRow (я). getPhysicalNumberOfCells (); если (tmp> cols) cols = tmp;)) за (int р = 0; р <рядами л + +) (подряд = sheet.getRow (р); если (строка! недействительными =) (для (int с = 0; с <cols; с + +) (клеток Row.getCell = ((короткая) с), если (ячейка! Недействительными =) (/ / Ваш код здесь))))) улова (Исключение МОП) (ioe.printStackTrace ();) This sample should get you started. Этот пример должен быстро начать работу. Don’t forget to import appropriately. Не забудьте соответствующим образом импортом.
Gotchas while using Jakarta POI (HSSF) Gotchas при использовании Джакарте POI (HSSF)
- getPhysicalNumberOfRows() returns the physical number of rows which may be more than the actual (logical) number of rows. getPhysicalNumberOfRows () возвращает физическое количество строк, которое может быть больше, чем фактическая (логический) количество строк. The same goes for getPhysicalNumberOfCells(). То же самое можно сказать о getPhysicalNumberOfCells ().
- You should check for nulls when fetching the HSSFRow and HSSFCell objects as shown. Вы должны проверить, nulls при получении HSSFRow и HSSFCell объекты, как показано на рисунке.
- Remember that Excel tables are often sparsely populated. Помните, что таблицы Excel, часто с низкой плотностью населения. So choose your data structures accordingly. Так что выбирать структуры данных, соответственно.
- POI accesses the data by sheet. ТОИ доступ к данным листа. In JExcelAPI you can directly access the data in any row and column. В JExcelAPI вы можете прямого доступа к данным в любой строки и столбца.
How to access Excel Spreadsheet using JExcelAPI Как получить доступ к таблице Excel с помощью 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); } Файл fp = новый файл (файл); попробуйте Рабочая тетрадь (ВБ = Workbook.getWorkbook (ПС); листового листа = wb.getSheet (0); int колонки sheet.getColumns = (); int строк sheet.getRows = (); String Данные, ибо (полковник int = 0; полковник <колонны; колонки + +) (для (int подряд = 0; строки <рядами; подряд + +) (= sheet.getCell данных (столбец, строка). getContents () / / Ваш код здесь ))) Улова (Исключение МОП) (System.out.println ( "Ошибка:" + МОР);)
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); } Файл fp = новый файл (файл); попробуйте Рабочая тетрадь (ВБ = Workbook.getWorkbook (ПС); листового листа = wb.getSheet (0); int колонки sheet.getColumns = (); int строк sheet.getRows = (); String Данные, ибо (полковник int = 0; полковник <колонны; колонки + +) (для (int подряд = 0; строки <рядами; подряд + +) (= sheet.getCell данных (столбец, строка). getContents () / / Ваш код здесь ))) Улова (Исключение МОП) (System.out.println ( "Ошибка:" + МОР);) Gotchas while using JExcelAPI Gotchas при использовании JExcelAPI
- JExcelAPI may often fail to fetch the data from certain cells or even the whole sheet. JExcelAPI может зачастую не могут получить данные из определенных клеток или даже весь лист. Unfortunately it gives a warning instead of an error to indicate the problem. К сожалению, он дает предупреждение вместо того чтобы сообщить об ошибке проблемы.
- JExcelAPI doesn’t expose the full meta-data of the spreadsheet like POI does. JExcelAPI не подвергайте полную мета-данные из таблицы, как ТОИ делает.
- JExcelAPI doesn’t properly recognize the data type in cells. JExcelAPI образом не признать, тип данных в ячейках. In all cases it indicated String data in our tests even when there were numeric or date fields. Во всех случаях она указала, String данных в наших испытаниях, даже когда имеются цифровые или дата областях.
Concluding thoughts on accessing Excel spreadsheets from Java Заключительные соображения относительно доступа к таблицам Excel с Явы
Both JExcelAPI and Jakarta POI (HSSF) are open source software to read & write data from / to Excel spreadsheet even on non-Microsoft platforms. Оба JExcelAPI и Джакарте POI (HSSF) являются открытыми исходными кодами читать и писать данные из / в Excel таблицу даже на не-Microsoft платформ. In my tests HSSF came out to be the clear leader and recommended solution because of robustness and features. В моем тесты HSSF пришли, чтобы быть ясно, лидер и рекомендовал решения, поскольку от надежности и возможностей.
Filed under Поданного в соответствии с Enterprise Software Программное обеспечение предпринимательства , Headline News Headline News , How To Как , J2EE , Java Software Программное обеспечение Java , Open Source Software Open Source Software , Programming Программирование | |
| |
RSS 2.0 RSS 2,0 | |
Trackback this Article | это статья |
Email this Article Отослать Статья
You may also like to read Вы можете также люблю читать |





May 24th, 2007 at 1:32 pm 24 мая 2007 года в 1:32 вечера
Thanks, Спасибо,
4 the script. 4 сценария.
Peter Петр
May 25th, 2007 at 2:12 am 25 мая 2007 года в 2:12 утра
What do you think of jxls (http://jxls.sourceforge.net) ? Что вы думаете о jxls (http://jxls.sourceforge.net)?
May 26th, 2007 at 5:41 pm 26 мая 2007 года в 5:41 вечера
jxls is simply a wrapper on top of poi to make it easier to create complex excel reports. jxls просто обертка поверх Пои, чтобы его было легче создавать сложные excel докладов. It is not a substitute for poi-hssf or jexcelapi. Он не подменяет Пои-hssf или jexcelapi.
May 31st, 2007 at 9:50 pm 31 мая 2007 года в 9:50 вечера
please tell me how to create a dropdownlist in excel пожалуйста, расскажите мне о том, как создать dropdownlist в excel
with POI. с POI. Thanks alot. Спасибо большое.
June 4th, 2007 at 12:16 pm 4 июня 2007 года в 12:16 вечера
Interesting comparison of ExcelAPI with Jakarta-POI. Интересное сравнение с ExcelAPI Джакарта-POI. Very useful, thanks for the article. Очень полезно, спасибо за статью.
June 20th, 2007 at 7:23 pm 20 июня 2007 года в 7:23 вечера
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 site сайт dudas Пои-эс-снимите Отлично рамки пара эль manejo де hojas де calculo вот uso desde зайца bastante пребывание у nunca tuve mayoer проблем.
July 20th, 2007 at 4:29 am 20 июля 2007 года в 4:29 утра
How did you conclude JExcel API is not suitable for Enterprise? Как вы заключить JExcel API не подходит для предприятия?
Can you list the problems faced using JExcel API and how did you overcome them in Jakarta POI? Можете ли Вы перечень проблем, с которыми сталкивается с помощью API JExcel и как Вы их преодоления в Джакарте POI?
July 26th, 2007 at 1:11 am 26 июля 2007 года в 1:11 утра
There is another choice. Существует еще один выбор.
Jxcell spreadsheet component Jxcell таблицы компонента
August 14th, 2007 at 3:56 pm 14 августа 2007 года в 3:56 вечера
En que idioma esta esto En, что язык этой esto
August 21st, 2007 at 8:22 am 21 августа 2007 года в 8:22 утра
plz tell me how i can fetch the data from excel sheet in c code::::::plzzzzz………. plz скажите мне, каким образом я могу получить данные из листа в excel с кодом :::::: plzzzzz……….
thanks::::: Благодаря :::::
August 31st, 2007 at 1:42 pm 31 августа 2007 года в 1:42 вечера
Did you test POI for newer versions of Excel than 2002? Вы имели в ТОИ для испытаний новых версий Excel, чем 2002? Will POI read an Excel 2005 spreadsheet with just basic data? Будет ТОИ читать электронную таблицу Excel 2005 с только что базовые данные?
September 1st, 2007 at 6:13 am 1 сентября 2007 года в 6:13 утра
@Neelam, @ Нилам,
The best I can suggest is look into the Excel dll files for their interface. Лучше я могу предположить, это смотреть в Excel dll файлов для их взаимодействия. I haven’t read Excel speradsheet in C / C++. Я не читал Excel speradsheet в C / C + +.
@John, @ Джон,
I have been using it on client supplied Excel files. Я уже используют ее на клиента поставляется Excel-файлов. I don’t know their versions as I use Open Office or Gnumeric to open them on Linux. Я не знаю их версии, как я использую Open Office или Gnumeric, чтобы открыть их на Linux.
October 23rd, 2007 at 7:26 pm 23 октября 2007 года в 7:26 вечера
very helpful script! очень полезно скрипта! i have another question, though. я есть другой вопрос, однако. have you tried reading charts from an excel file? Вы пробовали чтения карт из архива? do you have a sample code for that? есть ли у вас образец кода для этого? thank you in advance! спасибо заранее!
October 25th, 2007 at 6:23 am 25 октября 2007 года в 6:23 утра
I want to know how to append the spreadsheet using java .Please let me know soon . Я хочу знать, как добавить таблицу с помощью java. Пожалуйста, дайте мне знать в ближайшее время. thanks благодарность
October 25th, 2007 at 8:31 am 25 октября 2007 года в 8:31 утра
Senthil,
Use Jakarta-POI (HSSF) for that. Используйте Джакарта-POI (HSSF) за это.
October 31st, 2007 at 1:42 pm 31 октября 2007 года в 1:42 вечера
You have given example for reading the excel file. Вы дали пример для чтения архива. Do you have code snippet to write data to excel template with POI? У вас есть фрагмент кода записать данные в excel шаблон с POI?
November 3rd, 2007 at 7:32 am 3 ноября 2007 года в 7:32 утра
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.. я хочу, чтобы автоматизировать скриптов,, поэтому я хочу читать данные из excel листа и с этой даты он должен записать его в другой текстовых файлов, поэтому я могу ли я иметь исходный код для этого ни одного случая ..
November 13th, 2007 at 6:13 am 13 ноября 2007 года в 6:13 утра
Hi.. Привет ..
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.. Мне нужно написать данные от корпорации Майкрософт доступа к базе данных на excel листа и каких-либо изменений или updations в базу данных должна быть также отражена в excel лист .. Can anyone help?? Может ли кто-нибудь помочь?
Same with importing data from excel to database! То же самое с импорта данных из excel к базе данных!
Thanks.. Спасибо ..
November 13th, 2007 at 12:41 pm 13 ноября 2007 года в 12:41 вечера
You should use Java to transfer data from MS Access to MS Excel. Вы должны использовать Java для передачи данных из MS Access в MS Excel.
Use the above tutorial to read / write from MS Excel. Используйте выше учебник для чтения / записи из MS Excel.
Read the Читать tutorial to read / write from Microsoft Access database using Java учебное пособие для чтения / записи из базы данных Microsoft Access, используя Java .
November 13th, 2007 at 12:43 pm 13 ноября 2007 года в 12:43 вечера
Erwin said> have you tried reading charts from an excel file? Эрвин сказал> Вы пробовали чтения карт из архива?
No. Количество
November 14th, 2007 at 3:40 am 14 ноября 2007 года в 3:40 утра
Thanku angs.. Thanku angs ..
I did use ur code to read an excel file and got too exceptions as ArrayIndexOutOfBound and 2 more.. Я сделал использованием ур-код следующим образом архива и получили слишком исключениями, ArrayIndexOutOfBound и 2 подробнее ..
If u can jus help me to write whats in my acess database onto an excel file i’ll be thankful.. Если у jus может мне помочь написать whats в моей базе данных на acess архива, я буду благодарна .. Will be glad if I get some code on it!!! Будем очень рады, если я получаю определенный код на ней!
January 18th, 2008 at 2:45 am 18 января 2008 года в 2:45 утра
thx for the info! thx за информацию!
January 24th, 2008 at 3:47 am 24 января 2008 года в 3:47 утра
I want to write the data in Excel File . Я хочу записать данные в файл Excel. (ie) I want to append the excel file . (то есть) Я хочу добавить архива. how can i do that? Как я могу это сделать?
The original file\’s soft copy is in one subfolder of my project. Исходный файл \ 'ы электронном виде находится в подпапке, один из моих проектов. I want to overwrite that file . Я хочу перезаписать этот файл. Pls help . Pls помочь. I use jxl jar file in my project . Я использую jxl горшок файл в моем проекте.
Thanks in Advance Заранее благодарим
Ganesh Ганеш
February 4th, 2008 at 1:17 am 4 февраля 2008 года в 1:17 утра
I used the same code. Я использовал тот же код. In the biginning i have only В biginning я только
1000 rows, 26 columns then it was working properly. 1000 строк, 26 колонок то она работает правильно.
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. Здесь proble cames, сейчас я hav 3000 строк, 29 colomns; во-первых, моя программа работала правильно, но ее принято 1,26 минуты до конца и я cheacked то есть.
taking more time in executing this single line “HSSFWorkbook wb = new HSSFWorkbook(fs);”. принимая больше времени при выполнении этой одной строке "HSSFWorkbook ВБ = новый HSSFWorkbook (ПС)". and at the next time i got this Exception in thread “main” java.lang.OutOfMemoryError: Java heap space. и в следующий раз, когда я получил эту исключение в нити "основные" java.lang.OutOfMemoryError: Java куча пространства. finally i executed the same code in some other system, again the same problem… наконец, я казнен же код в некоторые другие системы, опять же проблема…
plz help me to solve this problem.. plz помогите мне решить эту проблему ..
Thanks in Adwnc Благодаря, в Adwnc
Nandu.
February 4th, 2008 at 7:04 am 4 февраля 2008 года в 7:04 утра
Thanks Angsuman for this introduction which helped me choose POI. Благодаря Angsuman для этого введения, которые помогли мне выбрать POI.
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. Я не совсем пониманию различия между физическим и логическим строк и ячеек, и я выяснил, что код не работает при наличии пустых строк.
You mention in already in your “gotcha’s” but it’s actually the other way around Вы сказали уже в Вашем "в Гоча", но он-таки наоборот
getPhysicalNumberOfRows() may be LESS than the actual rows (retrieved by getLastRowNum() ). getPhysicalNumberOfRows () может быть меньше фактической строк (извлекается 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. В вашем примере вы смешивать getPhysicalNumberOfRows () и sheet.getRow (int), которая возвращает логическую строку в листе, которые могли бы быть другой, если у вас есть пустые строки. The same goes for columns. То же самое можно сказать о колоннах.
February 6th, 2008 at 5:41 pm 6 февраля 2008 года в 5:41 вечера
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. ТОИ HSSF не было полезно для меня главным образом потому, что она не умеет писать из числа ценностей с правильный формат - это вещи, которые были проценты в таблице как "83%" может выйти из ТОИ как "0,834444", которые doesn " т работу с остальной частью трубопровода.
March 6th, 2008 at 6:43 am 6 марта 2008 года в 6:43 утра
how to read upload Excel sheet in tamil font in java code читать загрузить Excel листа в тамильский шрифт на Яве код
I would like to upload Excel sheet in tamil font using java code Я хотел бы загрузить Excel листа в тамильский шрифта с помощью java код
help me помогите мне
April 6th, 2008 at 7:11 am 6 апреля 2008 года в 7:11 утра
ur’s mail id please, by which i mail u regardings my problems in programing ур почтового идентификатора, пожалуйста, в которой я regardings почте у моих проблем в программирование
April 15th, 2008 at 8:37 am 15 апреля 2008 года в 8:37 утра
I have one excel file which is 51MB size. Я один архива, который 51MB размера. i tried to open using POI but fails. я попытался открыть с помощью, но не ТОИ. I saved the file using MS Excel with different file name and opened it with POI, it works. Я сохранил файл, используя MS Excel в другое имя файла и открыла его с ТОИ, она работает.
Is it the file problem or with POI? Является ли это проблемой или файл с POI?
Please suggest. Просьба предложить.
April 16th, 2008 at 12:37 pm 16 апреля 2008 года в 12:37 вечера
I would guess that it is the problem of the spreadsheet. Я думаю, что это проблема таблицы.
April 16th, 2008 at 12:40 pm 16 апреля 2008 года в 12:40 вечера
I have used POI with thousands of complex spreadsheets without any issues at all. Я использовал ТОИ с тысячами сложные электронные таблицы без каких-либо проблем вообще.
April 18th, 2008 at 4:18 am 18 апреля 2008 года в 4:18 утра
I tried POI , with Excel 2003, it’s writing fine , but when I’m trying to open it corrupts the whole Excel file. Я попытался ТОИ, с Excel 2003 года, он в письменном виде штрафа, но, когда Я пытаюсь открыть его коррумпирует целом Excel-файла.
So I tried with JXl, here writing & opening is ok, But it’s not appending new sheet’s. Так что я попытался с JXl, здесь письменной форме и в порядке открытия, но он не добавляется новый лист в. it’s always replaces old sheet with newly created sheet.Please any one can help me. она всегда заменяет старую лист с недавно созданной sheet.Please какого-либо одного может мне помочь.
April 26th, 2008 at 2:02 am 26 апреля 2008 года в 2:02 утра
Hi, Привет,
Sorry that I am putting question of Jxl in POI forum. Извините, что я сдачи вопрос Jxl в ТОИ форуме.
I am getting error “java.lang.OutOfMemoryError: Java heap space” while reading file with 10000 records and 95 columns. Я получаю ошибку "java.lang.OutOfMemoryError: Java куча пространства" при чтении файла с 10000 записей и 95 колонок. size of file is 14M. Размер файла 14M.
I am testing my application through JProfiler. Я тестирования моему заявлению через JProfiler.
Is there any restriction of file size or problem while reading throught jxl? Есть ли какие-либо ограничения по размеру файла или проблемы при чтении мысли jxl?
Can anybody help me. Может ли кто-либо помочь мне.
Thanks Спасибо
May 20th, 2008 at 3:07 pm 20 мая 2008 года в 3:07 вечера
what do i import to use the JExcelAPI? Что мне импортировать использовать JExcelAPI?
June 1st, 2008 at 11:24 am 1 июня 2008 года в 11:24 утра
but how to read excel sheets carying non english language as arabic ? но как читать excel листы carying, не английский язык, как арабский?
June 2nd, 2008 at 12:34 am 2 июня 2008 года в 12:34 утра
Mohamed, Мохамед,
I don’t know. Я не знаю. I haven’t tried it. Я не проверял.
June 10th, 2008 at 3:32 am 10 июня 2008 года в 3:32 утра
hello everybody, привет всем,
i have a small problem and need your help on it Я имею небольшие проблемы, и нужна ваша помощь по нему
i need to access my .mpp (Microsoft Project) File Мне необходимо получить доступ к моей. ПКД (Microsoft Project) файл
From java…..How can i do that? С Явы… .. как я могу это сделать?
knowing that using ready made components is not allowed. зная о том, что использование готовых компонентов, не допускается.