首頁 > 軟體

Java 如何將表格資料匯入word檔案中

2021-06-18 16:01:34

Java 表格資料匯入word檔案中

個人覺得這個功能實在搞笑,沒什麼意義,沒辦法提了需求就要實現,(太好說話了把我)

我的實現是再word中生成一個與 excel行,列 一樣的一個表格,然後把從excel拿到的資料(exList引數)依次放到word表格中

    public static void createFile(HttpServletResponse response, String fileName, List<List<String>> exList) {
  
        try {
            setResponseHeader(response, fileName);
            //生成一個word模版檔案
            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);
                }
                //將資料插入表格中  pos:0 表示 第一個表格
                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");
        //要儲存的檔名
        response.setHeader("Content-Disposition", "attachment;filename=" + name + ".docx");
        response.addHeader("Pargam", "no-cache");
        response.addHeader("Cache-Control", "no-cache");
    }

Java poi匯入word表格資料的經過

一、過程及遇到的問題和解決思路

需要匯入的是一個word檔案,內容是以表格的形式儲存在word中

1、poi對word表格的空格處可以自動識別出來並賦值為 " ",這一點比poi匯入excel人性化(excel預設是跳過這個空格)

2、對於某些情況下,肉眼無法看出表格格式問題,但是程式可以識別出來,懷疑是表格後期人工修改過,導致表格外觀沒問題但是行列屬性不一致,導致讀取時遇到這些地方報錯,解決思路:可以在讀取每一行之前先判斷列數是否正確,poi中可以獲取每行的列數,不正確的證明此列有問題,捨棄跳過。

二、程式碼

<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);
        //輸出書籤資訊
        //  this.printInfo(doc.getBookmarks());
        //輸出文字
        //  System.out.println(doc.getDocumentText());
        Range range = doc.getRange();
        //   this.printInfo(range);
        //讀表格
        List<TableColumn> tableColumns = this.readTable(range);
        //讀列表
        //  this.readList(range);
        //把當前HWPFDocument寫到輸出流中
        // doc.write(new FileOutputStream("D:\temp\test.doc"));
        is.close();
        return tableColumns;
    }
 
    /**
     * 輸出書籤資訊
     * @param bookmarks
     */
    private void printInfo(Bookmarks bookmarks) {
        int count = bookmarks.getBookmarksCount();
        System.out.println("書籤數量:" + count);
        Bookmark bookmark;
        for (int i=0; i<count; i++) {
            bookmark = bookmarks.getBookmark(i);
            System.out.println("書籤" + (i+1) + "的名稱是:" + bookmark.getName());
            System.out.println("開始位置:" + bookmark.getStart());
            System.out.println("結束位置:" + bookmark.getEnd());
        }
    }
 
    /**
     * 讀表格
     * 每一個回車符代表一個段落,所以對於表格而言,每一個單元格至少包含一個段落,每行結束都是一個段落。
     * @param range
     */
    private List<TableColumn> readTable(Range range) {
        List<TableColumn> tableColumns = new ArrayList<>();
        //遍歷range範圍內的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);
//
//                    //輸出單元格的文字
//                    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;
    }
 
    /**
     * 讀列表
     * @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());
            }
        }
    }
 
    /**
     * 輸出Range
     * @param range
     */
    private void printInfo(Range range) {
        //獲取段落數
        int paraNum = range.numParagraphs();
        System.out.println(paraNum);
        for (int i=0; i<paraNum; i++) {
            System.out.println("段落" + (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());
        }
    }
}

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com