Cập nhật nội dung chi tiết về Parse Word Document Using Apache Poi Example mới nhất trên website Beiqthatgioi.com. Hy vọng thông tin trong bài viết sẽ đáp ứng được nhu cầu ngoài mong đợi của bạn, chúng tôi sẽ làm việc thường xuyên để cập nhật nội dung mới nhằm giúp bạn nhận được thông tin nhanh chóng và chính xác nhất.
In this article we will be discussing about ways and techniques to read word documents in Java using Apache POI library. The word document may contain images, tables or plain text. Apart from this a standard word file has header and footers too. Here in the following examples we will be parsing a word document by reading its different paragraph, runs, images, tables along with headers and footers. We will also take a look into identifying different styles associated with the paragraphs such as font-size, font-family, font-color etc.
Maven Dependencies
Following is the poi maven depedency required to read word documents. For latest artifacts visit here
chúng tôi
<dependencies> <dependency> <groupId>org.apache.poi
</groupId> <artifactId>poi-ooxml
</artifactId> <version>3.16
</version> </dependency> </dependencies>Reading Complete Text from Word Document
The class XWPFDocument has many methods defined to read and extract .docx file contents. getText() can be used to read all the texts in a .docx word document. Following is an example.
TextReader.java
public class
TextReader {public static void
main(String[] args) {try
{ FileInputStream fis =new
FileInputStream("test.docx"
); XWPFDocument xdoc =new
XWPFDocument(OPCPackage.open(fis)); XWPFWordExtractor extractor =new
XWPFWordExtractor(xdoc); System.out
.println(extractor.getText()); }catch
(Exception ex) { ex.printStackTrace(); } } }Reading Headers and Foooters of Word Document
HeaderFooter.java
public class
HeaderFooterReader {public static void
main(String[] args) {try
{ FileInputStream fis =new
FileInputStream("test.docx"
); XWPFDocument xdoc =new
XWPFDocument(OPCPackage.open(fis)); XWPFHeaderFooterPolicy policy =new
XWPFHeaderFooterPolicy(xdoc); XWPFHeader header = policy.getDefaultHeader();if
(header !=null
) { System.out
.println(header.getText()); } XWPFFooter footer = policy.getDefaultFooter();if
(footer !=null
) { System.out
.println(footer.getText()); } }catch
(Exception ex) { ex.printStackTrace(); } } }Output
This is Header
This is footer
Read Each Paragraph of a Word Document
Among the many methods defined in XWPFDocument class, we can use getParagraphs() to read a .docx word document paragraph chúng tôi method returns a list of all the paragraphs(XWPFParagraph) of a word document. Again the XWPFParagraph has many utils method defined to extract information related to any paragraph such as text alignment, style associated with the paragrpahs.
To have more control over the text reading of a word document,each paragraph is again divided into multiple runs. Run defines a region of text with a common set of properties.Following is an example to read paragraphs from a .docx word document.
ParagraphReader.java
public class
ParagraphReader {public static void
main(String[] args) {try
{ FileInputStream fis =new
FileInputStream("test.docx"
); XWPFDocument xdoc =new
XWPFDocument(OPCPackage.open(fis)); List paragraphList = xdoc.getParagraphs();for
(XWPFParagraph paragraph : paragraphList) { System.out
.println(paragraph.getText()); System.out
.println(paragraph.getAlignment()); System.out
.print(paragraph.getRuns().size()); System.out
.println(paragraph.getStyle());// Returns numbering format for this paragraph, eg bullet or lowerLetter.
System.out
.println(paragraph.getNumFmt()); System.out
.println(paragraph.getAlignment()); System.out
.println(paragraph.isWordWrapped()); System.out
.println("********************************************************************"
); } }catch
(Exception ex) { ex.printStackTrace(); } } }Reading Tables from Word Document
Following is an example to read tables present in a word document. It will print all the text rows wise.
TableReader.java
public class
TableReader {public static void
main(String[] args) {try
{ FileInputStream fis =new
FileInputStream("test.docx"
); XWPFDocument xdoc =new
XWPFDocument(OPCPackage.open(fis)); Iterator bodyElementIterator = xdoc.getBodyElementsIterator();while
(bodyElementIterator.hasNext()) { IBodyElement element = bodyElementIterator.next();if
("TABLE"
.equalsIgnoreCase(element.getElementType().name())) { List tableList = element.getBody().getTables();for
(XWPFTable table : tableList) { System.out
.println("Total Number of Rows of Table:"
+ table.getNumberOfRows());for
(int
i = 0; i for (int
j = 0; j out.println(table.getRow(i).getCell(j).getText()); } } } } } }catch
(Exception ex) { ex.printStackTrace(); } } }Reading Styles from Word Document
Styles are associated with runs of a paragraph. There are many methods available in the XWPFRun class to identify the styles associated with the text.There are methods to identify boldness, highlighted words, capitalized words etc.
StyleReader.java
public class
StyleReader {public static void
main(String[] args) {try
{ FileInputStream fis =new
FileInputStream("test.docx"
); XWPFDocument xdoc =new
XWPFDocument(OPCPackage.open(fis)); List paragraphList = xdoc.getParagraphs();for
(XWPFParagraph paragraph : paragraphList) {for
(XWPFRun rn : paragraph.getRuns()) { System.out
.println(rn.isBold()); System.out
.println(rn.isHighlighted()); System.out
.println(rn.isCapitalized()); System.out
.println(rn.getFontSize()); } System.out
.println("********************************************************************"
); } }catch
(Exception ex) { ex.printStackTrace(); } } }Reading Image from Word Document
Following is an example to read image files from a word document.
public class
ImageReader {public static void
main(String[] args) {try
{ FileInputStream fis =new
FileInputStream("test.docx"
); XWPFDocument xdoc =new
XWPFDocument(OPCPackage.open(fis)); List pic = xdoc.getAllPictures();if
(!pic.isEmpty()) { System.out
.print(pic.get(0).getPictureType()); System.out
.print(pic.get(0).getData()); } }catch
(Exception ex) { ex.printStackTrace(); } } }Conclusion
Download source
How To Use The Document Map In Microsoft Word
Once upon a time, Word’s Document Map had a poor reputation. That reputation was justified. Until Word 2002, it was very flaky. I’ve had Word 2000 crash while displaying the Document Map more times than I can remember.
But from Word 2002, it improved a lot, and in Word 2010 it has been re-vamped and moved to centre stage. The document map is very useful, so give it a go.
How to invoke Document Map
Figure 1: The three parts to the Navigation Pane in Word 2010
To see the Document Map:
In all versions except Word 2007: Alt-V-D. (We lost the old keyboard shortcut in Word 2007, but it was reinstated for Word 2010!!)
You’ll see the Document Map on the left of your Word screen.
What does the Document Map do?
Strictly speaking, it doesn’t do anything. It just sits there on the left of your screen. What it shows you, however, can be very useful. It shows an outline of your document. That is, it shows all the headings in your document. You get to choose whether to show just the highest-level headings, or lower-level headings as well.
How to get Document Map to display something useful
To get Document Map to display useful headings, apply the built-in heading styles to the headings in your document.
There are many ways to apply the heading styles.
In Word 2003 and earlier versions, the easiest way is probably to use the Styles combobox on the toolbar. (And if you’re used to using that, in Word 2007 and Word 2010, you can reinstate the Styles combobox to the Quick Access Toolbar.)
From the Styles combo box, choose Heading 1 for your main headings, Heading 2 for sub-headings and Heading 3 for minor headings, and so on.
How to use the Document Map to move around your document quickly
How to use the Document Map to see where you are in a document
If you have a really big document, it’s sometimes easy to get “lost”. You can see a page of text, but it’s hard to know where you are in the document.
Document Map is a good way to solve this problem. As you move around your document, the Document Map will highlight the current heading.
For example, in Figure 1, I can see that the cursor is within the section with the heading “Balloons”. In Figure 2, I can see that the cursor is within the section “Sea transport”.
How to control the number of levels that Document Map displays
There are two controls available:
How to change the format of the text in the Document Map
In Word 2007 and earlier versions, text in the Document Map is shown in style Document Map. Modify the Document Map style to suit your needs. I find that 10pt Tahoma works well. This feature was removed from Word 2010.
How to change the width of the Document Map
Hover over the vertical bar separating the Document Map from your text. Drag left or right to suit your needs. See Figure 3.
Figure 3: Hover over the vertical bar to the right of the Document Map and drag to change the width of the Document Map.
How to use the Document Map in Word 2010
The Document Map has changed substantially in Word 2010 (Figure 4). It’s not even officially called the Document Map any more, but since it does not have a new name, it seems sensible to keep using the old one.
It now shares the new “Navigation Pane” with a panel for Find and one for Thumbnails. (Except they’re not called Find and Thumbnails any more either; but, like the Document Map they don’t have new names, so using the old names seems sensible.)
There good things about the changes:
Best of all: I can drag a heading in the Document Map, and the heading, and all the paragraphs of text “below” it, will move.
The old pre-Word 2007 keyboard shortcut of Alt-V-D has been reinstated. So I can open the new Document Map with the keyboard shortcut I’ve been using for a decade or more.
Word no longer guesses about what to show in the Document Map. It displays paragraphs based solely on each paragraph’s outline level.
But there are things I don’t like so much about the new Document Map:
It shows a lot less content than the old one. It’s pretty, but because the headings are in little buttons, each one takes up a lot more space. We lose 40% to 50% of the content compared with Word 2007 (the smaller your screen resolution, the bigger the hit).
To change the number of heading levels displayed in the Document Map requires one more mouse movement than the old version. One more mouse movement in this case is a change from 2 to 3, or a reduction in productivity of 50%.
There is some [NOTE: outdated link removed by Lene Fredborg 29-Dec-2016] some good material about the new Document Map at chúng tôi written during the beta testing of Office 2010.
There are several problems with Document Map:
Document Map doesn’t show headings that are in tables. I find this really annoying. It’s a known bug that has been inherited by the “new” Document Map of Word 2010. I guess it won’t get fixed any time soon.
Document Map doesn’t show headings that are in text boxes. Even the “new” Document Map of Word 2010 fails to show headings in a text box. Until Word 2007, text in a text box did not appear in the table of contents. So we weren’t likely to put a heading in a text box. Since that bug was fixed, we can put headings in a text box, and it’s the only straight-forward way to lay text over an image. So the failure of the new document map to show headings is particularly irritating.
In the Paragraph dialog, on the Line and Page Breaks tab, tick “Page Break Before”. Or, better, use the “Keep with Next” setting to keep the paragraph on the same page as the next paragraph. Or, better still, format your document using styles that have been modified with an appropriate “Keep with next” setting.
In Word 2007 and earlier versions, sometimes the Document Map decides to display tiny, unreadable type. It’s a known bug. The solution is to switch to Outline View and then back again. That is:
For the curious or the frustrated: How does Word decide what to display in Document Map?
Word 2007 and earlier versions
More usefully, the Outline Level can be derived from the style you apply to your text. The built-in heading styles have their Outline Level fixed (Heading 1 has Outline Level 1, Heading 2 has Outline Level 2 and so on). If you create a custom style, you can modify it to have the Outline level you choose.
If your document has text with appropriate Outline Levels, Document Map will use those outline levels. If Word can’t find any text with appropriate Outline Levels, then, in Word 2007 and earlier versions, Word will guess. (In Word 2010, Word no longer guesses. Hooray!)
Turn off Document Map.
Create a new Word document.
Copy the following text into your document:
A small line of text The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.Another short line The quick brown fox jumps over the lazy dog. jumps over the lazy dog.Few words here The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.
Turn on Document Map.
You can see that Word has guessed that short, bold lines are headings and has changed the Outline Level of the paragraphs.
Since no-one ever wants Word to guess, make sure you apply appropriate styles (which have appropriate Outline Levels) to your text. Then you will be controlling what displays in Document Map.
Word 2010
Word displays text in the Document Map based entirely on the Outline Level of the paragraph. It does not guess.
Acknowledgement Fellow MVP Klaus Linke worked out the problem with the missing heading numbering in Document Map.
Đọc Ghi Excel File Sử Dụng Apache Poi
Do vậy, trong bài viết này, mình đã giới thiệu về Apache POI là một thư viện mã nguồn mở cho phép chúng ta thao tác với các tập tin định dạng microsoft office. Trong bài viết này chúng ta sẽ cùng nhau tìm hiểu cách đọc và ghi excel file sử dụng Apache POI.
Maven denpendency
Để thao tác được với Excel file, chúng ta cần thêm các denpendency cần thiết.
Một số lưu ý khi sử dụng Apache POI
Bài viết này sẽ hướng dẫn các bạn cách đọc và ghi file excel sử dụng thư viện Apache POI. Tuy nhiên có một số lưu ý sau các bạn cần chú ý để có thể triển khai cho từng trường hợp của mình.
Tiền tố HSSF được đặt trước các tên class dùng để thao tác với các file định dạng Microsoft Excel 2003.
Tiền tố XSFF được đặt trước các tên class dùng để thao tác với các file định dạng Microsoft Excel 2007.
XSSFWorkbook và HSSFWorkbook là các class đại diện cho một excel workbook.
HSSFSheet và XSSFSheet là các class đại diện cho một excel WorkSheet.
Row đại diện cho một dòng.
Cell đại diện cho một ô trong một hàng xác định.
Trong bài hướng dẫn này, các bạn sẽ được hướng dẫn cách đọc ghi file excel Microsoft Excel 2007 có đôi là xlsx, có nghĩa là chúng ta sẽ sử dụng các class có tiền tố là XSFF để đọc file exel.
Ghi excel file
Để ghi một excel file cần qua những bước cơ bản sau:
Tạo workbook.
Tạo một sheet trong workbook.
Tạo một dòng trong sheet.
Thêm một cột trong sheet.
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileOutputStream; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class Main { public static void main(String[] args) { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet("student Details"); data.put("1", new Object[]{"ID", "NAME", "LASTNAME"}); data.put("2", new Object[]{1, "Pankaj", "Kumar"}); data.put("3", new Object[]{2, "Prakashni", "Yadav"}); data.put("4", new Object[]{3, "Ayan", "Mondal"}); data.put("5", new Object[]{4, "Virat", "kohli"}); int rownum = 0; for (String key : keyset) { Row row = sheet.createRow(rownum++); Object[] objArr = data.get(key); int cellnum = 0; for (Object obj : objArr) { Cell cell = row.createCell(cellnum++); if (obj instanceof String) cell.setCellValue((String) obj); else if (obj instanceof Integer) cell.setCellValue((Integer) obj); } } try { FileOutputStream out = new FileOutputStream(new File("gfgcontribute.xlsx")); workbook.write(out); out.close(); System.out.println("gfgcontribute.xlsx written successfully on disk."); } catch (Exception e) { e.printStackTrace(); } } }Đọc file excel
Để đọc một excel file chúng ta cũng có các bước sau:
Khởi tạo một workbook instance từ excel file.
Lấy sheet từ workbook.
Đọc từng dòng, mỗi dòng lấy giá trị từ từng cột.
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.util.Iterator; public class Main { public static void main(String[] args) { try { FileInputStream file = new FileInputStream(new File("gfgcontribute.xlsx")); XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet = workbook.getSheetAt(0); while (rowIterator.hasNext()) { Row row = rowIterator.next(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: System.out.print(cell.getNumericCellValue() + "t"); break; case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue() + "t"); break; } } System.out.println(""); } file.close(); } catch (Exception e) { e.printStackTrace(); } } }Output:
IDtNAMEtLASTNAMEt1.0tPankajtKumart2.0tPrakashnitYadavt3.0tAyantMondalt4.0tVirattkohlit
Note: Nếu bạn muốn đọc một file tại một đường dẫn khác, thì bạn chỉ việc thay
FileInputStream file = new FileInputStream(new File("gfgcontribute.xlsx"));thành đường dẫn bạn mong muốn.
Thêm dữ liệu vào sheet
Nếu bạn đã có một excel sẵn và muốn ghi thêm dự liệu vào đó, thì chỉ cần lấy sheet đó ra từ workbook, đi đến dòng cuối cùng và bắt đầu ghi thêm dữ liệu vào.
private static final String FILE_NAME = "C:\Users\pankaj\Desktop\projectOutput\blo.xlsx"; public static void write() throws IOException, InvalidFormatException { InputStream inp = new FileInputStream(FILE_NAME); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(0); int num = sheet.getLastRowNum(); Row row = sheet.createRow(++num); row.createCell(0).setCellValue("xyz"); ..... .. FileOutputStream fileOut = new FileOutputStream(FILE_NAME); wb.write(fileOut); fileOut.close(); }Nguồn tham khảo
https://www.geeksforgeeks.org/reading-writing-data-excel-file-using-apache-poi/
Đọc Ghi File Excel Trong Java Sử Dụng Apache Poi
1- Apache POI là gì?
Apache POI là một thư viện mã nguồn mở Java, được cung cấp bởi Apache, nó là một thư viện đầy sức mạnh giúp bạn làm việc với các tài liệu của Microsoft như Word, Excel, Power point, Visio,…
POI là viết tắt của“Poor Obfuscation Implementation”. Các định dạng file của Microsoft được giấu kín. Những kỹ sư của Apache phải cố gắng để tìm hiểu nó, và họ thấy rằng Microsoft đã tạo ra các định dạng phức tạp một cách không cần thiết. Và cái tên thư viện bắt nguồn từ sự hài ước.
Poor Obfuscation Implementation: Sự thực hiện cái nghèo nàn ngu muội. (Tạm dịch là vậy).
Trong tài liệu này tôi hướng dẫn các bạn sử dụng Apache POI để làm việc với Excel.
Apache POI hỗ trợ bạn làm việc với các định dạng của Microsoft, các class của nó thường có tiếp đầu ngữ HSSF, XSSF, HPSF, … Nhìn vào tiếp đầu ngữ của một class bạn có thể biết được class đó hỗ trợ loại định dạng nào.
Chẳng hạn để làm việc với các định dạng Excel (XLS) bạn cần các class:
HSSFWorkbook
HSSFSheet
HSSFCellStyle
HSSFDataFormat
HSSFFont
…
Apache POI cung cấp cho bạn các interfaceWorkbook,Sheet,Row,Cell,… và các class thể hiện (implementation) tương ứng là HSSFWorkbook, HSSFSheet, HSSFRow, HSSFCell,…
Nếu project của bạn sử dụng Maven, bạn chỉ cần khai báo thư viện một cách đơn giản trong chúng tôi :
Nếu bạn không sử dụng Maven bạn có thể download thư viện Apache POI tại:
Download về và giải nén, để làm việc với Excel bạn cần ít nhất 3 file jar:
poi-**.jar
lib/commons-codec-**.jar
lib/commons-collections4-**.jar
Trong tài liệu này, tôi tạo một Project Maven đơn giản có tên ApachePOIExcel
Group ID: org.o7planning
Artifact ID: ApachePOIExcel
Microsoft Office các phiên bản trước đây (97-2003) các file excel có định dạng XLS và các phiên bản mới thường sử dụng định dạng XSLX. Để thao tác với các file XSL bạn cần sử dụng các class có tiếp đầu ngữ HSSF. Còn đối với các file định dạng XSLX cần sử dụng các class có tiếp đầu ngữ XSSF.
Chú ý: Trong tài liệu này tôi đang sử dụng Apache POI 3.15, API có nhiều thay đổi so với phiên bản cũ hơn. Có nhiều phương thức sẽ bị loại bỏ trong phiên bản tương lai (Apache POI 4.x). POI đang hướng tới sử dụng Enum thay thế cho các hằng số trong API của nó.
7- Cập nhập file Excel có sẵnTrong ví dụ này, tôi đọc file excel chúng tôi và cập nhập các giá trị cho cột Salary tăng lên 2 lần.
Kết quả sau khi cập nhập:
Nếu bạn có kiến thức về Excel, sẽ không khó để bạn thiết lập một công thức. Với Apache POI bạn có thể tạo một Cell có kiểu CellType.FORMULA, giá trị của nó được tính dựa trên một công thức.
SUM
Ví dụ: Tính tổng các ô trên cùng cột “C” từ dòng thứ 2 tới dòng thứ 4:
cell = row.createCell(rowIndex, CellType.FORMULA); cell.setCellFormula("SUM(C2:C4)");Công thức từ các ô riêng lẻ:
cell = row.createCell(rowIndex, CellType.FORMULA); cell.setCellFormula("0.1*C2*D3");Với một cell có kiểu FORMULA bạn có thể in ra công thức của nó và sử dụng FormulaEvaluator để tính toán giá trị của ô cho bởi công thức đó.
String formula = cell.getCellFormula(); FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); CellValue cellValue = evaluator.evaluate(cell); double value = cellValue.getNumberValue(); String value = cellValue.getStringValue(); boolean value = cellValue.getBooleanValue();Bạn đang đọc nội dung bài viết Parse Word Document Using Apache Poi Example trên website Beiqthatgioi.com. Hy vọng một phần nào đó những thông tin mà chúng tôi đã cung cấp là rất hữu ích với bạn. Nếu nội dung bài viết hay, ý nghĩa bạn hãy chia sẻ với bạn bè của mình và luôn theo dõi, ủng hộ chúng tôi để cập nhật những thông tin mới nhất. Chúc bạn một ngày tốt lành!