Excel to java table

I had the same issue, i’ve was aware that the implementation via the standard (Apache POI) why cost so much time so after searching and looking around, i have found a better why (JXLS-Reader)

first of all use/import/include the library jxls-reader

    <dependency>
        <groupId>org.jxls</groupId>
        <artifactId>jxls-reader</artifactId>
        <version>2.0.3</version>
    </dependency>

then create an XML file used by the library for the correspondence between the columns and the your object attributes, this XML take as parameter an initialized list to fill it by extracted data (Employee objects) from the Excel file, in your example, it will look like :

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<workbook>
    <worksheet idx="0">
        <section startRow="0" endRow="0" />
        <loop startRow="1" endRow="1" items="employeeList" var="employee" varType="com.department.Employee">
            <section startRow="1" endRow="1">
            <mapping row="1"  col="0">employee.empNo</mapping>
            <mapping row="1"  col="1">employee.empName</mapping>
            </section>
            <loopbreakcondition>
                <rowcheck offset="0">
                    <cellcheck offset="0"></cellcheck>
                </rowcheck>
            </loopbreakcondition>
        </loop>
    </worksheet>
</workbook>

Then in Java, initialize the list of the Employees (where the result of parsing will be included), then call the JXLS reader by the input Excel file and the XML mapping, it will look like:

package com.department;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;


public class ExcelProcessor {

    private static Logger logger = LoggerFactory.getLogger(ExcelProcessor.class);

    public void parseExcelFile(File excelFile) throws Exception{
        final List<Employee> employeeList = new ArrayList<Employee>();
        InputStream xmlMapping = new BufferedInputStream(ExcelProcessor.class.getClassLoader().getResourceAsStream("proBroMapping.xml"));
        ReaderConfig.getInstance().setUseDefaultValuesForPrimitiveTypes(true);
        ReaderConfig.getInstance().setSkipErrors(true);
        InputStream inputXLS;
        try{
            XLSReader mainReader = ReaderBuilder.buildFromXML(xmlMapping);
            inputXLS = new BufferedInputStream(new FileInputStream(excelFile));
            final Map<String, Object> beans = new HashMap<String, Object>();
            beans.put("employeeList", employeeList);
            mainReader.read(inputXLS, beans);
            System.out.println("Employee data are extracted successfully from the Excel file, number of Employees is: "+employeeList.size());
        } catch(java.lang.OutOfMemoryError ex){
            // Case of a very large file that exceed the capacity of the physical memory
               ex.printStackTrace();
            throw new Exception(ex.getMessage());
        } catch (IOException ex) {
            logger.error(ex.getMessage());
            throw new Exception(ex.getMessage());
        } catch (SAXException ex) {
            logger.error(ex.getMessage());
            throw new Exception(ex.getMessage());
        } catch (InvalidFormatException ex) {
            logger.error(ex.getMessage());
            throw new Exception(ex.getMessage());
        } finally {
            IOUtils.closeQuietly(inputStream);
        }

    }

}

Hope this helps anyone having such a problem !

carlwils

When you need to create a table in a Word document based on data from an Excel worksheet, you may usually complete the task by simply copying and pasting. But in the process, the formatting of the table may be lost and then you’ll need to reformat it in the Word document. This article will share how to programmatically convert Excel data into a Word table and retain its formatting in Java application.

Install Free Spire.Office for Java

To convert Excel data into a Word table in Java, you’ll need to install the Free Spire.Office for Java library. The library is completely free for both commercial and personal use. Below are two methods to install it.
Method 1: Download the free library and unzip it, then add the Spire.Office.jar file to your project as dependency.

Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.office.free</artifactId>
        <version>5.3.1</version>
    </dependency>
</dependencies>

Enter fullscreen mode

Exit fullscreen mode

Sample Code

To convert Excel date to Word table, you’ll need to get the value of a specific Excel cell using CellRange.getValue() method and then add it to a cell of the Word table using TableCell.addParagraph().appendText() method. To retain the table formatting, you can copy the font style and cell style from Excel to the Word table using the custom method copyStyle(). The complete sample code is shown below.

import com.spire.doc.*;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.PageOrientation;
import com.spire.doc.documents.VerticalAlignment;
import com.spire.doc.fields.TextRange;
import com.spire.xls.*;

public class ExportExcelToWord {

    public static void main(String[] args) {

        //Load an Excel file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("test.xlsx");

        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        //Create a Word document
        Document doc = new Document();
        Section section = doc.addSection();
        section.getPageSetup().setOrientation(PageOrientation.Portrait);

        //Add a table
        Table table = section.addTable(true);
        table.resetCells(sheet.getLastRow(), sheet.getLastColumn());

        //Merge cells
        mergeCells(sheet, table);

        for (int r = 1; r <= sheet.getLastRow(); r++) {

            //Set row Height
            table.getRows().get(r - 1).setHeight((float) sheet.getRowHeight(r));

            for (int c = 1; c <= sheet.getLastColumn(); c++) {
                CellRange xCell = sheet.getCellRange(r, c);
                TableCell wCell = table.get(r - 1, c - 1);

                //Get value of a specific Excel cell and add it to a cell of Word table
                TextRange textRange = wCell.addParagraph().appendText(xCell.getValue());

                //Copy font and cell style from Excel to Word
                copyStyle(textRange, xCell, wCell);
            }
        }

        //Save the document to a Word file
        doc.saveToFile("ExportTableToWord.docx", FileFormat.Docx);
    }

    //Merge cells if any
    private static void mergeCells(Worksheet sheet, Table table) {
        if (sheet.hasMergedCells()) {

            //Get merged cell ranges from Excel
            CellRange[] ranges = sheet.getMergedCells();
            for (int i = 0; i < ranges.length; i++) {
                int startRow = ranges[i].getRow();
                int startColumn = ranges[i].getColumn();
                int rowCount = ranges[i].getRowCount();
                int columnCount = ranges[i].getColumnCount();

                //Merge corresponding cells in Word table
                if (rowCount > 1 && columnCount > 1) {
                    for (int j = startRow; j <= startRow + rowCount ; j++) {
                        table.applyHorizontalMerge(j - 1, startColumn - 1, startColumn - 1 + columnCount - 1);
                    }
                    table.applyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount -1);
                }
                if (rowCount > 1 && columnCount == 1 ) {
                    table.applyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount -1);
                }
                if (columnCount > 1 && rowCount == 1 ) {
                    table.applyHorizontalMerge(startRow - 1, startColumn - 1,  startColumn - 1 + columnCount-1);
                }
            }
        }
    }

    //Copy cell style of Excel to Word table
    private static void copyStyle(TextRange wTextRange, CellRange xCell, TableCell wCell) {

        //Copy font style
        wTextRange.getCharacterFormat().setTextColor(xCell.getStyle().getFont().getColor());
        wTextRange.getCharacterFormat().setFontSize((float) xCell.getStyle().getFont().getSize());
        wTextRange.getCharacterFormat().setFontName(xCell.getStyle().getFont().getFontName());
        wTextRange.getCharacterFormat().setBold(xCell.getStyle().getFont().isBold());
        wTextRange.getCharacterFormat().setItalic(xCell.getStyle().getFont().isItalic());

        //Copy backcolor
        wCell.getCellFormat().setBackColor(xCell.getStyle().getColor());

        //Copy horizontal alignment
        switch (xCell.getHorizontalAlignment()) {
            case Left:
                wTextRange.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Left);
                break;
            case Center:
                wTextRange.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
                break;
            case Right:
                wTextRange.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Right);
                break;
        }

        //Copy vertical alignment
        switch (xCell.getVerticalAlignment()) {
            case Bottom:
                wCell.getCellFormat().setVerticalAlignment(VerticalAlignment.Bottom);
                break;
            case Center:
                wCell.getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                break;
            case Top:
                wCell.getCellFormat().setVerticalAlignment(VerticalAlignment.Top);
                break;
        }
    }
}

Enter fullscreen mode

Exit fullscreen mode

ExceltoWord

Интеграция электронных таблиц MS Excel и Java.

Описание:

В современном мире очень много случаев, при которых необходимо интегрировать MS
Excel с Java. Например, при разработке Enterprise-приложения в некой финансовой
сфере, вам необходимо предоставить счет для заинтересованных лиц, а проще всего
выставлять счет на MS Excel.

Обзор существующих API MS Excel для Java:

Рассмотрим основные API:

  • Docx4j — это API с открытым исходным кодом, для создания и манипулирования документами формата Microsoft Open XML, к которым отросятся Word docx, Powerpoint pptx, Excel xlsx файлы. Он очень похож на Microsoft OpenXML SDK, но реализован на языке Java. Docx4j использует JAXB архитектуру для создания представления объекта в памяти. Docx4j акцентирует свое внимание на всесторонней поддержке заявленного формата, но от пользователя данного API требуется знание и понимание технологии JAXB и структуры Open XML.

  • Apache POI — это набор API с открытым исходным кодом, который предлагает определенные функции для чтения и записи различных документов, базирующихся на Office Open XML стандартах (OOXML) и Microsoft OLE2 форматe документов (OLE2). OLE2 файлы включают большинство Microsoft Office форматов, таких как doc, xls, ppt. Office Open XML формат это новый стандарт базирующийся на XML разметке, и используется в файлах Microsoft office 2007 и старше.

  • Aspose for Java — набор платных Java APIs, которые помогают разработчикам в работе с популярными форматами бизнес файлов, такими как документы Microsoft Word, таблицы Microsoft Excel, презентации Microsoft PowerPoint, PDF файлы Adobe Acrobat, emails, изображения, штрих-коды и оптические распознавания символов.

Каждое API проектируется для того, чтобы выполнять широкий спектр создания документов, различные манипуляции и преобразования быстро и легко, экономя время и позволяя разработчикам успешно программировать. Ни один API с открытым исходным кодом не имеет одной и той же комплексной поддержки функций.

Все Aspose’s APIs используют простую объектную модель документа, а одно API предназначено для работы с набором связанных форматов. Aspose’s Microsoft Office APIs, Aspose.Cells, Aspose.Words, Aspose.Slides, Aspose.Email, и Aspose.Tasks легки в работе, эффективны, надежны и независимы от других библиотек.

Преимуществом APIs с открытым исходным кодом является то, что они бесплатны и каждый может настроить их под свои задачи и цели. Это очень удобно, если у пользователя есть достаточно времени и ресурсов. Однако данные APIs не всегда имеют поддержку или документацию, и поддерживают небольшое количество функций и вариантов. Этот недостаток стоит разработчикам времени, и сокращает надежность их приложений. К преимуществам проприетарных (коммерческих) API можно отнести комплексную поддержку функционала с подробной документацией, регулярное обновление, гарантию отсутствия ошибок и обратную связь с разработчиками APIs.

В данной программе будем использовать Apache POI

Ссылки на полезные ресурсы

  • https://habr.com/post/56817/
  • https://poi.apache.org/apidocs/index.html — официальная документация
  • http://java-online.ru/java-excel.xhtml

Задание:

В данной работе вы должны реализовать следующее:

  1. Чтение с ячейки MS Excel в Java

  2. Запись с Java в MS Excel

Инструкция

  • Для обращения к MS Excel версии до 2003 включительно года с Java используется класс HSSFWorkbook
  • Для обращения к MS Excel версии 2007 и позднее с Java используется класс XSSFWorkbook
  • При операциях Обновление или Запись необходимо, чтобы MS Excel был закрыт.
Чтение ячейки с MS Excel

Чтобы считать данные с xlsx необходимо исполнить следующие шаги:

    //filePath - это путь до MS Excel
    Workbook book = new XSSFWorkbook(new FileInputStream(filePath);
    //считывается лист по индексу sheet_index. sheet_index начинается с 0
    Sheet sheet = book.getSheetAt(sheet_index);
    //считывается row по индексу row_index. row_index начинается с 0
    Row row = sheet.getRow(row_index);
    //считывается cell по индексу cell_index. cell_index начинается с 0
    Cell cell = sheet.getCell(cell_index);
Запись в ячейку MS Excel
    Workbook book = new XSSFWorkbook();
    //name - имя листа
    Sheet sheet = book.createSheet(name);
    Row row = sheet.createRow(i);
    Cell cell = row.createCell(j);
    FileInputStream fileOut = new FileInputStream(filePath);
    book.write(fileOut);
    fileOut.close();
Обновление ячейки в существующем листе MS Excel
    Workbook workbook = new XSSFWorkbook(new FileInputStream(filePath));
    Sheet sheet = workbook.getSheetAt(i);
    Row row = sheet.getRow(j);
    Cell cell = row.getCell(k);
    cell.setCellValue(value);

Подготовка: загрузка библиотек и зависимостей

Конечно, существует достаточно много открытых библиотек, которые позволяют работать с Excel файлами в Java, например, JXL, но мы будем использовать имеющую самый обширный API и самую популярную — Apache POI. Чтобы её использовать, вам нужно скачать jar файлы и добавить их через Eclipse вручную, или вы можете предоставить это Maven.

Во втором случае вам нужно просто добавить следующие две зависимости:

	<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.12</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.12</version>
    </dependency>
  </dependencies>

Самое удобное в Maven — что он загрузит не только указанные poi.jar и poi-ooxml.jar, но и все jar файлы, которые используются внутри, то есть xmlbeans-2.6.0.jar,
stax-api-1.0.1.jar, poi-ooxml-schemas-3.12.jar и commons-codec-1.9.jar

Выполнение:

  1. Создать проект на java с помощью maven.

  2. Следовать инструкции «Подготовка:…» описанная выше.

  3. Создать Excel файл в корневой папке проекта.

  4. Записать в A1 и A2 любые целые числа.

  5. В папке src/main/java создать класс IOCell

    1. Создать поле
    1. Создать конструктор
    IOCell(String filePath) { this.filePath = new File(filePath)}
    1. Создать метод для чтения c Excel в Java
    public Cell getCell(int sheet, int row, int column) {
        Workbook workbook = null;
        try (FileInputStream file = new FileInputStream(filePath)) {
            workbook = new XSSFWorkbook(file);
        } catch (FileNotFoundException e) {
            System.out.println("file is not exists");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook.getSheetAt(sheet).getRow(row).getCell(column);
    }
    1. Создать метод для записи с Java в Excel
        public void setCell(int row, int column, double val) {
        Workbook workbook = null;
         try (FileInputStream file = new FileInputStream(filePath)) {
             workbook = new XSSFWorkbook(file);
             Sheet sheet = workbook.getSheetAt(0);
             sheet.getRow(row).getCell(column).setCellValue(val);
         } catch (IOException e) {
             e.printStackTrace();
         }
        try (OutputStream fileOut = new FileOutputStream(filePath)) {
            workbook.write(fileOut);
        } catch (FileNotFoundException e) {
            System.out.println("file is not exist AAAA");
        } catch (IOException e) {
            e.printStackTrace();
        }
    
    }
    
  6. В папке src/main/java создать класс Main

    1. Создать поле
        private static final String filePath = "NAME_OF_EXCEL_FILE";
    1. Создать метод
    public static void main(String[] args) {
        IOCell ioCell = new IOCell(filePath);
    
        Cell x = ioCell.getCell(0, 1, 0);
        Cell y = ioCell.getCell(0,  1, 1);
        System.out.println("first number: " + x.toString());
        System.out.println("second number: " + y.toString());
        //Write x * y
        ioCell.setCell(4, 0, x.getNumericCellValue() * y.getNumericCellValue());
        //Write x + y
        ioCell.setCell(4, 1, x.getNumericCellValue() + y.getNumericCellValue());
        System.out.println("Interactions is complete successfully");
    }
  7. Запускаем приложение и смотрим в консоль.

Понравилась статья? Поделить с друзьями:
  • Excel to html with formulas
  • Excel to html with formatting
  • Excel to html table online
  • Excel to google document
  • Excel to google contacts