1. 程式人生 > 其它 >Java 操作Word表格資料

Java 操作Word表格資料

Java 操作Word表格資料

1、word內容

2、pom.xml檔案,新增相關依賴支援。

     <!--Word操作-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>4.0.0</version>
        </dependency>

3、建測試類

import com.alibaba.fastjson.JSON;
import com.example.sbmpsqlite.entity.Stu;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; public class DocHang { public static void main(String[] args) { String url = "C:\\Users\\Desktop\\word\\120502.doc"; readWordFile(url); } public static void readWordFile(String fileName) { List<String> listWordLine = new ArrayList<>();
try { FileInputStream in = new FileInputStream(fileName); POIFSFileSystem pfs = new POIFSFileSystem(in); HWPFDocument hwpf = new HWPFDocument(pfs); Range range = hwpf.getRange(); TableIterator it = new TableIterator(range); while (it.hasNext()) { Table tb = (Table) it.next(); for (int i = 0; i < tb.numRows(); i++) { TableRow tr = tb.getRow(i); String text = tr.text(); if (text.startsWith("序號")) { continue; } listWordLine.add(text); System.out.println("行:" + text); // for (int j = 0; j < tr.numCells(); j++) { // TableCell td = tr.getCell(j); // //System.out.println("列:"+td.text()); // for (int k = 0; k < td.numParagraphs(); k++) { // Paragraph para = td.getParagraph(k); // String str = para.text(); // System.out.println("單元格:" + str); // } // } } } } catch (Exception e) { e.printStackTrace(); } wordLine(listWordLine); } public static void wordLine(List<String> listWordLine) { List<Stu> stusNewList = new ArrayList<>(); for (String strWordLine : listWordLine) { if (strWordLine.contains("\u0007")) { Stu stu = new Stu(); String[] split = strWordLine.split("\u0007"); List<String> strsToList = Arrays.asList(split); System.out.println("List陣列:" + strsToList); stu.setId(strsToList.get(0)); stu.setSex(strsToList.get(1)); stu.setGrade(strsToList.get(2)); stu.setAge(strsToList.get(3)); stu.setName(strsToList.get(4)); stu.setX1(strsToList.get(5)); stu.setX2(strsToList.get(6)); stu.setX3(strsToList.get(7)); stu.setX4(strsToList.get(8)); stusNewList.add(stu); } } System.out.println("結果資料:" + JSON.toJSONString(stusNewList)); } }

4、輸出結果

List陣列:[1, 男, 五, 9, 曼, XXX, XXX, XXX, XXX]
List陣列:[2, 女, 五, 8, 加, XXX, XXX, XXX, XXX]
結果資料:[{"age":"9","grade":"五","id":"1","name":"曼","sex":"男","x1":"XXX","x2":"XXX","x3":"XXX","x4":"XXX"},{"age":"8","grade":"五","id":"2","name":"加","sex":"女","x1":"XXX","x2":"XXX","x3":"XXX","x4":"XXX"}]

說明:此方式只能對.doc字尾的word進行解析。