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进行解析。