快速搭建spring boot项目使用 Apache POI解析word文档

  • 写在前面
    想必Java程序员对Apache POI已经相当了解了,我们常用它处理MS Excel文档,将数据批量导入数据库,交给程序处理,亦或是将数据从应用中下载下来。其实POI远比我们想象得要强大的多,它包含很多组件: POIFS (此组件是所有其他POI元件的基本因素。它被用来明确地读取不同的文件HSSF (它被用来读取和写入MS-Excel文件的xls格式) 、XSSF (它是用于MS-Excel中XLSX文件格式) 、HPSF (它用来提取MS-Office文件属性设置) 、HWPF (它是用来读取和写入MS-Word的文档doc扩展名的文件) 、XWPF (它是用来读取和写入MS-Word的docx扩展名的文件) 、HSLF (它是用于读取,创建和编辑PowerPoint演示文稿) 、HDGF (它包含类和方法为MS-Visio的二进制文件) 、HPBF (它被用来读取和写入MS-Publisher文件) 。那么,今天我们先了解一下POI是如何处理word文档的。

  • 首先用maven快速搭建一个spring boot 项目
添加pom文件
<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring.boot.version>1.5.9.RELEASE</spring.boot.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <!-- Import dependency management from Spring Boot -->
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring.boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
创建application.yml修改启动端口为8088。server.port=8088
添加启动主类
@SpringBootApplication
public class WordParseApplication {
        public static void main(String[] args) {
            SpringApplication.run(WordParseApplication.class, args);
        }
}
引入控制类验证项目是否搭建成功
package com.hello.word.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhangwq 
 */
@RestController
@RequestMapping(value = "/hello",produces = MediaType.APPLICATION_JSON_VALUE)
public class PoiWordController {
    @RequestMapping(value = "/word",method = RequestMethod.GET)
    public String helloWord(@RequestParam(value = "name") String string){
        return string;
    }

}

访问地址:http://localhost:8088/hello/word?name=helloword


项目搭建成功。

  • 引入poi和swagger相关依赖
<!-- 引入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>

为了方便测试我们引入swagger,直接图形化界面调用接口

 <!-- 引入swagger相关jar包 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
        </dependency>

  • 创建swagger配置类
package com.hello.word.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration //让Spring来加载该类配置
@EnableSwagger2 //启用Swagger2
public class SwaggerConfig {
    @Bean
    public Docket dataManagerApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("POI解析word文档")
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.hello.word.controller"))
                .paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("POI解析word文档")
                .description("POI解析word文档,包括doc和docx格式")
                .termsOfServiceUrl("-----")
                .contact(new Contact("zhangwq","----", "[email protected]"))
                .version("1.0").build();
    }

}

  • PoiWordController中添加如下方法,解析doc和docx需要使用不同的组件,具体内容见代码注释。注:word文档中,将硬回车作为段落区分的标识,该方法将每个段落分别放入map中,返回给前台。
/**
     * 按段落解析一个word文档
     * @param file
     * @return
     * @throws Exception
     */
    @ApiOperation(value="解析word文档", notes="按段落解析word文档")
    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public Map uploadFile(@RequestParam(value = "file", required = true) MultipartFile file){
        String textFileName=file.getOriginalFilename();
        Map wordMap = new LinkedHashMap();//创建一个map对象存放word中的内容
        try {
            if(textFileName.endsWith(".doc")){ //判断文件格式
                InputStream fis = file.getInputStream();
                WordExtractor wordExtractor = new WordExtractor(fis);//使用HWPF组件中WordExtractor类从Word文档中提取文本或段落
                int i=1;
                for(String words : wordExtractor.getParagraphText()){//获取段落内容
                    System.out.println(words);
                    wordMap.put("DOC文档,第("+i+")段内容",words);
                    i++;
                }
                fis.close();
            }
            if(textFileName.endsWith(".docx")){
                File uFile = new File("tempFile.docx");//创建一个临时文件
                if(!uFile.exists()){
                    uFile.createNewFile();
                }
                FileCopyUtils.copy(file.getBytes(), uFile);//复制文件内容
                OPCPackage opcPackage = POIXMLDocument.openPackage("tempFile.docx");//包含所有POI OOXML文档类的通用功能,打开一个文件包。
                XWPFDocument document = new XWPFDocument(opcPackage);//使用XWPF组件XWPFDocument类获取文档内容
                List<XWPFParagraph> paras = document.getParagraphs();
                int i=1;
                for(XWPFParagraph paragraph : paras){
                    String words = paragraph.getText();
                    System.out.println(words);
                    wordMap.put("DOCX文档,第("+i+")段内容",words);
                    i++;
                }
                uFile.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(wordMap);
        return wordMap;
    }
测试文档的内容如下


  • 分别用poi解析word.docpoi解析word.doc(两个文件内容相同)验证得到我们想要的结果。



  • 写在最后

实际应用中,每个段落可能会有特殊的用途。我们可以添加特殊字符对他们进行归类,按照自己的逻辑进行处理。

猜你喜欢

转载自blog.csdn.net/zwq_zwq_zwq/article/details/80638079
今日推荐