ImportWord.java 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package com.diagbot.api;
  2. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  3. import org.apache.poi.xwpf.usermodel.XWPFDocument;
  4. import org.apache.poi.xwpf.usermodel.XWPFTable;
  5. import org.apache.poi.xwpf.usermodel.XWPFTableCell;
  6. import org.apache.poi.xwpf.usermodel.XWPFTableRow;
  7. import java.io.FileInputStream;
  8. import java.util.Iterator;
  9. import java.util.List;
  10. public class ImportWord {
  11. public static void main(String[] args) {
  12. String filepath = "E:\\危重病人APACHE II评分表量表.docx";
  13. parseWord(filepath);
  14. }
  15. /**
  16. * 读取文档中表格
  17. * @param filePath
  18. */
  19. public static void parseWord(String filePath){
  20. try{
  21. FileInputStream in = new FileInputStream(filePath);//载入文档
  22. // 处理docx格式 即office2007以后版本
  23. if(filePath.toLowerCase().endsWith("docx")){
  24. //word 2007 图片不会被读取, 表格中的数据会被放在字符串的最后
  25. XWPFDocument xwpf = new XWPFDocument(in);//得到word文档的信息
  26. Iterator<XWPFTable> it = xwpf.getTablesIterator();//得到word中的表格
  27. // 设置需要读取的表格 set是设置需要读取的第几个表格,total是文件中表格的总数
  28. int set = 1, total = 4;
  29. int num = set;
  30. // 过滤前面不需要的表格
  31. // for (int i = 0; i < set-1; i++) {
  32. // it.hasNext();
  33. // it.next();
  34. // }
  35. while(it.hasNext()){
  36. XWPFTable table = it.next();
  37. System.out.println("这是第" + num + "个表的数据");
  38. List<XWPFTableRow> rows = table.getRows();
  39. //读取每一行数据
  40. for (int i = 0; i < rows.size(); i++) {
  41. XWPFTableRow row = rows.get(i);
  42. //读取每一列数据
  43. List<XWPFTableCell> cells = row.getTableCells();
  44. for (int j = 0; j < cells.size(); j++) {
  45. XWPFTableCell cell = cells.get(j);
  46. //输出当前的单元格的数据
  47. System.out.print(cell.getText() + "\t");
  48. }
  49. System.out.println();
  50. }
  51. // 过滤多余的表格
  52. while (num < total) {
  53. it.hasNext();
  54. it.next();
  55. num += 1;
  56. }
  57. }
  58. }
  59. }catch(Exception e){
  60. e.printStackTrace();
  61. }
  62. }
  63. }