1. Главная страница » Компьютеры

Apache poi word примеры

Автор: | 16.12.2019

Apache POI представляет собой API, который позволяет использовать файлы MS Office в Java приложениях. Данная библиотека разрабатывается и распространяется Apache Software Foundation и носит открытый характер. Apache POI включает классы и методы для чтения и записи информации в документы MS Office.

Компоненты Apache POI

Описание компонентов

HSSF Horrible Spreadsheet Format Компонент чтения и записи файлов MS-Excel, формат XLS
XSSF XML Spreadsheet Format Компонент чтения и записи файлов MS-Excel, формат XLSX
HPSF Horrible Property Set Format Компонент получения наборов свойств файлов MS-Office
HWPF Horrible Word Processor Format Компонент чтения и записи файлов MS-Word, формат DOC
XWPF XML Word Processor Format Компонент чтения и записи файлов MS-Word, формат DOCX
HSLF Horrible Slide Layout Format Компонент чтения и записи файлов PowerPoint, формат PPT
XSLF XML Slide Layout Format Компонент чтения и записи файлов PowerPoint, формат PPTX
HDGF Horrible DiaGram Format Компонент работы с файлами MS-Visio, формат VSD
XDGF XML DiaGram Format Компонент работы с файлами MS-Visio, формат VSDX
Читайте также:  Oukitel k10000 pro 32gb black

Список компонентов

Наименование (артeфакт) Необходимые компоненты
poi commons-logging, commons-codec, commons-collections, log4j
poi-scratchpad poi
poi-ooxml poi, poi-ooxml-schemas
poi-ooxml-schemas xmlbeans
poi-examples poi, poi-scratchpad, poi-ooxml
ooxml-schemas xmlbeans
ooxml-security xmlbeans

Подключение Apache POI к проекту

Для подключения Apache POI к проекту необходимо скачать соответствующие библиотеки с официального сайта https://poi.apache.org/download.html.

Если в проекте используется фреймворк maven, то необходимо установить одну из следующих зависимостей (версия может быть более новой) :

На странице описания примера чтения файлов Excel приведен проект, включающий необходимый набор файлов библиотеки Apache POI (poi-3.16.jar, poi-ooxml-3.16.jar, poi-ooxml-schemas-3.16.jar) и сопутствующих библиотек.

На странице рассматриваются следующие классы, используемые для работы с файлами Excel из приложений Java.

  • рабочая книга — HSSFWorkbook, XSSFWorkbook
  • лист книги — HSSFSheet, XSSFSheet
  • строка — HSSFRow, XSSFRow
  • ячейка — HSSFCell, XSSFCell
  • стиль — стили ячеек HSSFCellStyle, XSSFCellStyle
  • шрифт — шрифт ячеек HSSFFont, XSSFFont

Поскольку описание всех классов и методов не разместить на одной странице, то ниже по тексту приводятся ссылки для перехода к исходной документации.

Классы и методы Apache POI для работы с файлами Excel

Рабочая книга HSSFWorkbook, XSSFWorkbook

  • HSSFWorkbook
  • org.apache.poi.hssf.usermodel
  • класс чтения и записи файлов Microsoft Excel в формате .xls, совместим с версиями MS-Office 97-2003;
  • XSSFWorkbook
    • org.apache.poi.xssf.usermodel
    • класс чтения и записи файлов Microsoft Excel в формате .xlsx, совместим с MS-Office 2007 или более поздней версии.
    • Конструкторы класса HSSFWorkbook

      preservenodes является необязательным параметром, который определяет необходимость сохранения узлов типа макросы.

      Конструкторы класса XSSFWorkbook

      Основные методы HSSFWorkbook, XSSFWorkbook

      Метод Описание
      createSheet () Создание страницы книги HSSFSheet, XSSFSheet
      createSheet (String name) Создание страницы с определенным наименованием
      CreateFont () Создание шрифта
      createCellStyle () Создание стиля

      С полным перечнем всех методов класса XSSFWorkbook можно познакомиться на странице http://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFWorkbook.html.

      Читайте также:  Ozon код на 500 рублей

      Классы листов книги, HSSFSheet, XSSFSheet

      • org.apache.poi.hssf.usermodel.HSSFSheet
      • org.apache.poi.xssf.usermodel.XSSFSheet

      Классы HSSFSheet, XSSFSheet включают свойства и методы создания строк, определения размера колонок, слияния ячеек в одну область и т.д.

      Основные методы классов работы с листами

      Метод Описание
      addMergedRegion (CellRangeAddress) Определение области слияния ячеек страницы
      autoSizeColumn (int column) Автоматическая настройка ширины колонки column (отсчет от 0)
      setColumnWidth (int column, int width) Настройка ширины колонки column (отсчет от 0)
      createRow (int row) Создание строки row (отсчет от 0)
      getRow (int row) Получение ссылки на строку row (отсчет от 0)

      С полным перечнем всех методов класса XSSFSheet можно познакомиться на странице https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFSheet.html

      Классы строк HSSFRow, XSSFRow

      • org.apache.poi.hssf.usermodel.HSSFRow
      • org.apache.poi.xssf.usermodel.XSSFRow

      Классы HSSFRow, XSSFRow включают свойства и методы работы со строками, создания ячеек в строке и т.д.

      Основные методы классов HSSFRow, XSSFRow

      Метод Описание
      setHeight (short) Определение высоты строки
      getHeight() Получение значения высоты в twips’ах (1/20)
      getHeightInPoints() Получение значение высоты
      createCell (int) Создание ячейки в строке (отсчет от 0)
      getCell(int) Получение ссылки на ячейку
      getFirstCellNum() Получение номера первой ячейки в строке
      setRowStyle(CellStyle) Определение стиля всей строки

      С полным перечнем всех методов класса XSSFRow можно познакомиться на странице http://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFRow.html

      Классы ячеек HSSFCell, XSSFCell

      Ячейки электронной таблицы используются для размещения информации. В ячейке может быть представлено числовое значение, текст или формула. Также ячейка может содержать комментарий.

      Классы HSSFCell, XSSFCell включают свойства и методы работы с ячейками таблицы.

      Основные методы классов HSSFCell, XSSFCell

      Метод Описание
      getBooleanCellValue() Чтение логического значения ячейки
      getDateCellValue() Чтение значения ячейки типа java.util.Date
      getNumericCellValue() Чтение числового значения ячейки типа double
      getStringCellValue() Чтение текстового значения ячейки (java.lang.String)
      setCellValue(boolean) Определение логического значения ячейки
      setCellValue(java.util.Calendar) Определение значения ячейки типа даты
      setCellValue(java.util.Date) Определение значения ячейки типа даты
      getCellTypeEnum() Чтение типа значения ячейки CellType
      setCellComment(Comment) Запись комментария в ячейку
      getCellComment() Чтение комментария ячейки
      removeCellComment() Удаление комментария ячейки
      setHyperlink(Hyperlink) Запись гиперссылки в ячейку
      getHyperlink() Чтение гиперссылки XSSFHyperlink в ячейке
      removeHyperlink() Удаления гиперссылки ячейки
      getCellFormula() Чтение формулы, например SUM(C4:E4)
      setCellFormula(String) Определение формулы, например =SUM(C4:E4)
      getCellStyle() Чтение стиля ячейки (XSSFCellStyle)
      setCellStyle(CellStyle) Определение стиля ячейки
      getColumnIndex() Определение индекса ячейки
      setAsActiveCell() Определение активности ячейки

      С полным перечнем всех методов класса XSSFCell можно познакомиться на странице http://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFCell.html

      Классы стилей ячеек HSSFCellStyle, XSSFCellStyle

      С полным перечнем всех свойств и методов класса XSSFCellStyle можно познакомиться на странице http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/CellStyle.html

      Ниже в качестве примера представлен метод, формирующий стиль ячейки, в которой :

      • текст центрируется по вертикали и горизонтали;
      • обрамление ячейки представляет тонкую черную линию по периметру;
      • текст переносится на следующую строку (не ячейку), если не вмещается в размер ячейки.

      Метод setWrapText позволяет определить флаг переноса текста в ячейке согласно ее размеру (ширине). Чтобы перенести текст принудительно, можно в текстовой строке установить символы CRCL, например "Разделитель
      текста".

      Классы шрифтов HSSFFont, XSSFFont

      С полным перечнем всех свойств и методов класса XSSFFont можно познакомиться на странице http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Font.html

      Ниже в качестве примера представлен метод, формирующий шрифт типа "Times New Roman" :

      Примеры создания файлов Excel и определение стилей ячеек рассмотрены здесь.

      Добрый день.
      Подскажите пожалуйста, есть шаблон документа Word, в котором имеется некоторый набор полей, в которые необходимо выгрузить соответствующие данные: ФИО, дата и так далее.
      Можно ли в Apache POI как-то получить эти поля и записать в них значения?

      Many a time, a software application is required to generate reference documents in Microsoft Word file format. Sometimes, an application is even expected to receive Word files as input data.

      Any Java programmer who wants to produce MS-Office files as output must use a predefined and read-only API to do so.

      What is Apache POI?

      Apache POI is a popular API that allows programmers to create, modify, and display MS-Office files using Java programs. It is an open source library developed and distributed by Apache Software Foundation to design or modify MS-Office files using Java program. It contains classes and methods to decode the user input data or a file into MS-Office documents.

      Components of Apache POI

      Apache POI contains classes and methods to work on all OLE2 Compound documents of MS-Office. The list of components of this API is given below −

      POIFS (Poor Obfuscation Implementation File System) − This component is the basic factor of all other POI elements. It is used to read different files explicitly.

      HSSF (Horrible SpreadSheet Format) − It is used to read and write .xls format of MS-Excel files.

      XSSF (XML SpreadSheet Format) − It is used for .xlsx file format of MS-Excel.

      HPSF (Horrible Property Set Format) − It is used to extract property sets of the MS-Office files.

      HWPF (Horrible Word Processor Format) − It is used to read and write .doc extension files of MS-Word.

      XWPF (XML Word Processor Format) − It is used to read and write .docx extension files of MS-Word.

      HSLF (Horrible Slide Layout Format) − It is used to read, create, and edit PowerPoint presentations.

      HDGF (Horrible DiaGram Format) − It contains classes and methods for MS-Visio binary files.

      HPBF (Horrible PuBlisher Format) − It is used to read and write MS-Publisher files.

      This tutorial guides you through the process of working on MS-Word files using Java. Therefore the discussion is confined to HWPF and XWPF components.

      Note − OLDER VERSIONS OF POI SUPPORT BINARY FILE FORMATS SUCH AS DOC, XLS, PPT, ETC. VERSION 3.5 ONWARDS, POI SUPPORTS OOXML FILE FORMATS OF MS-OFFICE SUCH AS DOCX, XLSX, PPTX, ETC.

      This chapter takes you through the process of setting up Apache POI on Windows and Linux based systems. Apache POI can be easily installed and integrated with your current Java environment, following a few simple steps without any complex setup procedures. User administration is required while installation.

      System Requirements

      JDK Java SE 2 JDK 1.5 or above
      Memory 1 GB RAM (recommended)
      Disk Space No minimum requirement
      Operating System Version Windows XP or above, Linux

      Let us now proceed with the steps to install Apache POI.

      Step 1: Verify your Java Installation

      First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the two commands mentioned below, depending on the platform you are working on.

      If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table −

      Platform Command Sample Output
      Windows

      Open command console and type −

      Java version "1.7.0_60"

      Java (TM) SE Run Time Environment (build 1.7.0_60-b19)

      Java Hotspot (TM) 64-bit Server VM (build 24.60-b09,mixed mode)

      Linux

      Open command terminal and type −

      java version "1.7.0_25"

      Open JDK Runtime Environment (rhel-2.3.10.4.el6_4-x86_64)

      Open JDK 64-Bit Server VM (build 23.7-b01, mixed mode)

      We assume that the readers of this tutorial have Java SDK version 1.7.0_60 installed on their system.

      In case you do not have Java SDK, download its current version from https://www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed.

      Step 2: Set your Java Environment

      Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example,

      Platform Description Windows Set JAVA_HOME to C:ProgramFilesjavajdk1.7.0_60 Linux Export JAVA_HOME = /usr/local/java-current

      Append the full path of Java compiler location to the System Path.

      Platform Description
      Windows Append the String "C:Program FilesJavajdk1.7.0_60in" to the end of the system variable PATH.
      Linux Export PATH = $PATH:$JAVA_HOME/bin/

      Execute the command java — version from the command prompt as explained above.

      Step 3: Install Apache POI Library

      Download the latest version of Apache POI from https://poi.apache.org/download.html and unzip its contents to a folder from where the required libraries can be linked to your Java program. Let us assume the files are collected in a folder on C drive.

      The following images shows the directories and the file structure inside the downloaded folder −

      Add the complete path of the five jars as highlighted in the above image to the CLASSPATH.

      Platform Description
      Windows

      Append the following strings to the end of the user variable CLASSPATH −

      Linux

      This chapter takes you through the classes and methods of Apache POI for managing a Word document.

      Document

      This is a marker interface (interface do not contain any methods), that notifies that the implemented class can be able to create a word document.

      XWPFDocument

      This is a class under org.apache.poi.xwpf.usermodel package. It is used to create MS-Word Document with .docx file format.

      >

      Sr.No. Method & Description 1

      Commits and saves the document.

      Appends a new paragraph to this document.

      Creates an empty table with one row and one column as default.

      Creates a table of content for Word document.

      Returns the paragraph(s) that holds the text of the header or footer.

      Returns the styles object used.

      For the remaining methods of this class, refer the complete API document at −

      XWPFParagraph

      This is a class under org.apache.poi.xwpf.usermodel package and is used to create paragraph in a word document. This instance is also used to add all types of elements into word document.

      >

      Sr.No. Method & Description 1

      Appends a new run to this paragraph.

      Returns the paragraph alignment which shall be applied to the text in this paragraph.

      Specifies the paragraph alignment which shall be applied to the text in this paragraph.

      Specifies the border which shall be displayed below a set of paragraphs, which have the same set of paragraph border settings.

      Specifies the border which shall be displayed on the left side of the page around the specified paragraph.

      Specifies the border which shall be displayed on the right side of the page around the specified paragraph.

      Specifies the border which shall be displayed above a set of paragraphs which have the same set of paragraph border settings.

      For the remaining methods of this class, refer the complete API document at −

      XWPFRun

      This is a class under org.apache.poi.xwpf.usermodel package and is used to add a region of text to the paragraph.

      >

      Sr.No. Method & Description 1

      Specifies that a break shall be placed at the current location in the run content.

      Specifies that a tab shall be placed at the current location in the run content.

      Sets text color.

      Specifies the font size which shall be applied to all noncomplex script characters in the content of this run when displayed.

      Sets the text of this text run.

      Specifies whether the bold property shall be applied to all non-complex script characters in the content of this run when displayed in a document.

      For the remaining methods of this class, refer the complete API document at −

      XWPFStyle

      This is a class under org.apache.poi.xwpf.usermodel package and is used to add different styles to the object elements in a word document.

      >

      Sr.No. Method & Description 1

      It is used to get StyleID of the next style.

      It is used to get StyleID of the style.

      It is used to get styles.

      It is used to set styleID.

      For the remaining methods of this class, refer the complete API document at −

      XWPFTable

      This is a class under org.apache.poi.xwpf.usermodel package and is used to add table data into a word document.

      >

      Sr.No. Method & Description 1

      Adds a new column for each row in this table.

      addRow(XWPFTableRow row, int pos)

      Adds a new Row to the table at position pos.

      Creates a new XWPFTableRow object with as many cells as the number of columns defined in that moment.

      Sets the width of the column.

      For the remaining methods of this class, refer the complete API document at: POI API Documentation

      XWPFWordExtractor

      This is a class under org.apache.poi.xwpf.extractor package. It is a basic parser class used to extract the simple text from a Word document.

      >

      Sr.No. Method & Description 1

      Retrieves all the text from the document.

      For the remaining methods of this class, refer the complete API document at: POI API Documentation

      Here the term ‘document’ refers to a MS-Word file. After completion of this chapter, you will be able to create new documents and open existing documents using your Java program.

      Create Blank Document

      The following simple program is used to create a blank MS-Word document −

      Save the above Java code as CreateDocument.java, and then compile and execute it from the command prompt as follows −

      If your system environment is configured with the POI library, it will compile and execute to generate a blank Excel file named createdocument.docx in your current directory and display the following output in the command prompt −

      In this chapter you will learn how to create a Paragraph and how to add it to a document using Java. Paragraph is a part of a page in a Word file.

      After completing this chapter, you will be able to create a Paragraph and perform read operations on it.

      Create a Paragraph

      First of all, let us create a Paragraph using the referenced classes discussed in the earlier chapters. By following the previous chapter, create a Document first, and then we can create a Paragraph.

      The following code snippet is used to create a spreadsheet −

      Run on Paragraph

      You can enter the text or any object element, using Run. Using Paragraph instance you can create run.

      The following code snippet is used to create a Run.

      Write into a Paragraph

      Let us try entering some text into a document. Consider the below text data −

      The following code is used to write the above data into a paragraph.

      Save the above Java code as CreateParagraph.java, and then compile and run it from the command prompt as follows −

      It will compile and execute to generate a Word file named createparagraph.docx in your current directory and you will get the following output in the command prompt −

      The createparagraph.docx file looks as follows.

      In this chapter, you will learn how to apply border to a paragraph using Java programming.

      Applying Border

      The following code is used to apply Borders in a Document −

      Save the above code in a file named ApplyingBorder.java, compile and execute it from the command prompt as follows −

      If your system is configured with the POI library, then it will compile and execute to generate a Word document named applyingborder.docx in your current directory and display the following output −

      The applyingborder.docx file looks as follows −

      In this chapter, you will learn how to create a table of data in a document. You can create a table data by using XWPFTable class. By adding each Row to table and adding each cell to Row, you will get table data.

      Create Table

      The following code is used to creating table in a document −

      Save the above code in a file named CreateTable.java. Compile and execute it from the command prompt as follows −

      It generates a Word file named createtable.docx in your current directory and display the following output on the command prompt −

      The createtable.docx file looks as follows −

      This chapter shows how to apply different font styles and alignments in a Word document using Java. Generally, Font Style contains: Font size, Type, Bold, Italic, and Underline. And Alignment is categorized into left, center, right, and justify.

      Font Style

      The following code is used to set different styles of font −

      Save the above code as FontStyle.java and then compile and execute it from the command prompt as follows −

      It will generate a Word file named fontstyle.docx in your current directory and display the following output on the command prompt −

      The fontstyle.docx file looks as follows.

      Alignment

      The following code is used to set alignment to the paragraph text −

      Save the above code as AlignParagraph.java and then compile and execute it from the command prompt as follows −

      It will generate a Word file named alignparagraph.docx in your current directory and display the following output in the command prompt −

      The alignparagraph.docx file looks as follows −

      This chapter explains how to extract simple text data from a Word document using Java. In case you want to extract metadata from a Word document, make use of Apache Tika.

      For .docx files, we use the class org.apache.poi.xwpf.extractor.XPFFWordExtractor that extracts and returns simple data from a Word file. In the same way, we have different methodologies to extract headings, footnotes, table data, etc. from a Word file.

      The following code shows how to extract simple text from a Word file −

      Добавить комментарий

      Ваш адрес email не будет опубликован. Обязательные поля помечены *