Java How to Import Table Data into an word Document

  • 2021-09-20 20:30:00
  • OfStack

The Java table data is imported into the word document

Personally, I think this function is really funny, meaningless, and I can't put forward the demand to be realized. (Too easy to talk to me)

My implementation is to generate a table in word like row and column of excel, and then put the data obtained from excel (exList parameters) into word table in turn


    public static void createFile(HttpServletResponse response, String fileName, List<List<String>> exList) {
  
        try {
            setResponseHeader(response, fileName);
            // Generate 1 A word Template file 
            XWPFDocument document = new XWPFDocument();
 
            XWPFTable table = document.createTable(exList.size(), exList.get(0).size());
            XWPFTableRow row;
 
            for (int i = 0; i < exList.size(); i++) {
 
                List<String> sdf = exList.get(i);
 
                row = table.getRow(i);
 
                for (int j = 0; j < exList.get(i).size(); j++) {
                    String s =sdf.get(j);
                    row.getCell(j).setText(s);
                    row.getCell(j).setWidthType(TableWidthType.AUTO);
                }
                // Insert data into a table   pos : 0  Denote   No. 1 1 Tables 
                document.setTable(0,table);
            }
            ServletOutputStream outputStream = response.getOutputStream();
            BufferedOutputStream bufferStream = new BufferedOutputStream(outputStream, 1024);
            document.write(bufferStream);
            document.close();
            bufferStream.close();;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void setResponseHeader(HttpServletResponse response, String name) {
        try {
            name = new String(name.getBytes(), "ISO8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
 response.setContentType("multipart/form-data");
        // The name of the file to save 
        response.setHeader("Content-Disposition", "attachment;filename=" + name + ".docx");
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
    }

Java poi Importing word Table Data

1. Process, problems encountered and solutions

What needs to be imported is an word document, the contents of which are saved in the form of tables in word

1. poi can automatically identify the space in word table and assign it as "", which is more humane than poi importing excel (excel skips this space by default)

2. In some cases, The problem of table format can't be seen with naked eyes, However, the program can identify it, and it is suspected that the table has been manually modified in the later stage, which leads to no problem in the appearance of the table but the column and column attributes are not 1, which leads to errors reported in these places when reading. The solution is to judge whether the number of columns is correct before reading every 1 row, and the number of columns per row can be obtained in poi, which incorrectly proves that there is something wrong with this column and abandons skipping.

2. Code


<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.17</version>
        </dependency>

package com.example.importtomysql; 
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*; 
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; 
public class ImportWord {
    public List<TableColumn> testReadByDoc(String path) throws Exception {
        File f = new File(path);
        InputStream is = new FileInputStream(f);
        HWPFDocument doc = new HWPFDocument(is);
        // Output bookmark information 
        //  this.printInfo(doc.getBookmarks());
        // Output text 
        //  System.out.println(doc.getDocumentText());
        Range range = doc.getRange();
        //   this.printInfo(range);
        // Read a table 
        List<TableColumn> tableColumns = this.readTable(range);
        // Read list 
        //  this.readList(range);
        // Put the current HWPFDocument Write to the output stream 
        // doc.write(new FileOutputStream("D:\\temp\\test.doc"));
        is.close();
        return tableColumns;
    }
 
    /**
     *  Output bookmark information 
     * @param bookmarks
     */
    private void printInfo(Bookmarks bookmarks) {
        int count = bookmarks.getBookmarksCount();
        System.out.println(" Number of bookmarks: " + count);
        Bookmark bookmark;
        for (int i=0; i<count; i++) {
            bookmark = bookmarks.getBookmark(i);
            System.out.println(" Bookmark " + (i+1) + " The name of is: " + bookmark.getName());
            System.out.println(" Start position: " + bookmark.getStart());
            System.out.println(" End position: " + bookmark.getEnd());
        }
    }
 
    /**
     *  Read a table 
     *  Every 1 A carriage return stands for 1 So for the table, each 1 Cells containing at least 1 A paragraph, and each line ends with 1 A paragraph. 
     * @param range
     */
    private List<TableColumn> readTable(Range range) {
        List<TableColumn> tableColumns = new ArrayList<>();
        // Traversal range Within the scope table . 
        TableIterator tableIter = new TableIterator(range);
        Table table;
        TableRow row;
        TableCell cell;
        int i=0;
        int k=0;
        while (tableIter.hasNext()&&i<=1) {
 
            table = tableIter.next();
            int rowNum = table.numRows();
            for (int j=0; j<rowNum; j++) {
                TableColumn tableColumn = new TableColumn();
                row = table.getRow(j);
                int cellNum = row.numCells();
//                for (int k=0; k<cellNum; k++) {
//                    cell = row.getCell(k, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
//
//                    // Output the text of the cell 
//                    System.out.println(cell.text().trim());
//                }
                k++;
                if(12==cellNum){
                    tableColumn.setId(row.getCell(0).text().trim());
                    tableColumn.setSscj(row.getCell(1).text().trim());
                    tableColumn.setQlfl(row.getCell(2).text().trim());
                    tableColumn.setXmmc(row.getCell(3).text().trim());
                    tableColumn.setZx(row.getCell(4).text().trim());
                    tableColumn.setBlx(row.getCell(5).text().trim());
                    tableColumn.setSsyj(row.getCell(6).text().trim());
                    tableColumn.setCbjg(row.getCell(7).text().trim());
                    tableColumn.setZrsx(row.getCell(8).text().trim());
                    tableColumn.setSxyj(row.getCell(9).text().trim());
                    tableColumn.setZzqx(row.getCell(10).text().trim());
                    tableColumn.setZzyj(row.getCell(11).text().trim());
//                tableColumn.setBz(row.getCell(12).text().trim());
                    tableColumns.add(tableColumn);
  
                    if(679==k){
                        System.out.println(k  +" " +row.getCell(0).text().trim()+" " +row.getCell(3).text().trim());
                    }
//                    System.out.println(k +" " +row.getCell(0).text().trim()+" "+row.getCell(3).text().trim());
                }else {
                    System.out.println(k);
                }
 
            }
            i++;
        }
        return tableColumns;
    }
 
    /**
     *  Read list 
     * @param range
     */
    private void readList(Range range) {
        int num = range.numParagraphs();
        Paragraph para;
        for (int i=0; i<num; i++) {
            para = range.getParagraph(i);
            if (para.isInList()) {
                System.out.println("list: " + para.text());
            }
        }
    }
 
    /**
     *  Output Range
     * @param range
     */
    private void printInfo(Range range) {
        // Get the number of paragraphs 
        int paraNum = range.numParagraphs();
        System.out.println(paraNum);
        for (int i=0; i<paraNum; i++) {
            System.out.println(" Paragraph " + (i+1) + " : " + range.getParagraph(i).text());
        }
        int secNum = range.numSections();
        System.out.println(secNum);
        Section section;
        for (int i=0; i<secNum; i++) {
            section = range.getSection(i);
            System.out.println(section.getMarginLeft());
            System.out.println(section.getMarginRight());
            System.out.println(section.getMarginTop());
            System.out.println(section.getMarginBottom());
            System.out.println(section.getPageHeight());
            System.out.println(section.text());
        }
    }
}

Related articles: