SpringBoot的POI(Word、Excel文档的读写)

SpringBoot的POI(Word、Excel文档的读写)

项目目录

SpringBoot的POI(Word、Excel文档的读写)_第1张图片

1.新建SpringBoot项目

1.1导入环境依赖


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.12.RELEASEversion>
        <relativePath/> 
    parent>
    <groupId>com.qfgroupId>
    <artifactId>days73spt_poiartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>days73spt_poiname>
    <description>Demo project for Spring Bootdescription>
    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>poi-ooxmlartifactId>
            <version>3.17version>
        dependency>
        <dependency>
            <groupId>org.apache.poigroupId>
            <artifactId>ooxml-schemasartifactId>
            <version>1.1version>
        dependency>

        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>1.1.1version>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-jpaartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.49version>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.16.16version>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombokgroupId>
                            <artifactId>lombokartifactId>
                        exclude>
                    excludes>
                configuration>
            plugin>
        plugins>
    build>

project>

1.2配置文件

#DB Configuration:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
#JPA Configuration:
spring.jpa.database=MySQL
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy

server.port=9999

#Mybatis Configuration:
spring.datasource.druid.url=jdbc:mysql://localhost:3306/springboot?characterEncoding=utf-8&useSSL=false
spring.datasource.druid.username=root
spring.datasource.druid.password=root
spring.datasource.druid.driver-class-name=com.mysql.jdbc.Driver
pagehelper.auto-dialect=mysql
mybatis.type-aliases-package=com.qfedu.pojo
mybatis.mapper-locations=classpath:mapper/*Mapper.xml

2.Word的读写

2.1写操作

package com.word;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

@Service
public class WriteDoc {

    public void exportDoc(){
        //创建Word对象
        XWPFDocument xwpfDocument = new XWPFDocument ();
        //创建一个段落对象
        XWPFParagraph titleParagraph = xwpfDocument.createParagraph ();
        //创建文本对象
        XWPFRun titleParagraphRun = titleParagraph.createRun ();
        titleParagraphRun.setBold (true);
        titleParagraphRun.setText ("这是一个POI操作Word的测试00000000");
        titleParagraphRun.setColor ("FF0000");
        titleParagraphRun.setText ("红色的字?");
        String fileName = "POI操作Word.doc";
        try {
            OutputStream outputStream = new FileOutputStream (fileName);
            //执行写出到本地
            xwpfDocument.write (outputStream);
            xwpfDocument.close ();
        } catch (FileNotFoundException e) {
            e.printStackTrace ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }
}

2.2读操作

package com.word;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class ReadDoc {
    public void importDoc(){
        String fileName = "POI操作Word.doc";
        try {
            InputStream inputStream = new FileInputStream (fileName);
            XWPFDocument xwpfDocument = new XWPFDocument (inputStream);
            List<XWPFParagraph> paragraphs = xwpfDocument.getParagraphs ();
            for (XWPFParagraph paras:paragraphs){
                System.out.println (paras.getText ());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }
}

2.3 controller层调用

在浏览器上测试

package com.controller;

import com.word.ReadDoc;
import com.word.WriteDoc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class WordController {
    @Autowired
    private ReadDoc readDoc;
    @Autowired
    private WriteDoc writeDoc;

    @RequestMapping("/writeWord")
    public String writeWord(){
        writeDoc.exportDoc ();
        return "成功";
    }

    @RequestMapping("/readWord")
    public String readWord(){
        readDoc.importDoc ();
        return "成功";
    }
}

3.Excel的读写

3.1 写操作

通过jpa将数据存到数据库中

pojo实体类(表头属性)

package com.pojo;

import lombok.Data;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Data
@Entity
@Table(name = "user_info")
public class User {
    @Id
    @Column(name = "user_id")
    private Integer userId;
    private String via;
    @Column(name = "user_name")
    private String userName;
    @Column(name = "user_password")
    private String userPassword;
    private String phone;
    private String address;
    @Column(name = "user_email")
    private String userEmail;
    private Double balance;
    @Column(name = "pay_pwd")
    private String payPwd;
}

dao层

package com.dao;

import com.pojo.User;
import org.springframework.data.jpa.repository.JpaRepository;


public interface UserRepository extends JpaRepository<User,Integer> {
}

service层

package com.service;

import com.pojo.User;

import java.util.List;

public interface UserService {
    List<User> selectAllUser();
}
package com.service.serviceImpl;

import com.dao.UserRepository;
import com.pojo.User;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    public List<User> selectAllUser(){
        return userRepository.findAll ();
    }
}

WriteXLS.java

package comu.excel;

import com.pojo.User;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

@Service
public class WriteXLS {
    public void exportExcel(List<User> list) {
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook ();
        HSSFSheet sheet = hssfWorkbook.createSheet ();
        HSSFRow titleRow = sheet.createRow (0);
        titleRow.createCell (0).setCellValue ("用户编号");
        titleRow.createCell (1).setCellValue ("用户头像");
        titleRow.createCell (2).setCellValue ("用户姓名");
        titleRow.createCell (3).setCellValue ("用户密码");
        titleRow.createCell (4).setCellValue ("用户手机");
        titleRow.createCell (5).setCellValue ("用户地址");
        titleRow.createCell (6).setCellValue ("用户邮箱");
        titleRow.createCell (7).setCellValue ("用户余额");
        titleRow.createCell (8).setCellValue ("用户支付密码");
        for (User user : list) {
            //获取当前最大的行
            int lastRowNum = sheet.getLastRowNum ();
            //新创建一行操作
            HSSFRow dataRow = sheet.createRow (lastRowNum + 1);
            dataRow.createCell (0).setCellValue (user.getUserId ());
            dataRow.createCell (1).setCellValue (user.getVia ()==null?"":user.getVia ());
            dataRow.createCell (2).setCellValue (user.getUserName ()==null?"":user.getUserName ());
            dataRow.createCell (3).setCellValue (user.getUserPassword ()==null?"":user.getUserPassword ());
            dataRow.createCell (4).setCellValue (user.getPhone ()==null?"":user.getPhone ());
            dataRow.createCell (5).setCellValue (user.getAddress ()==null?"":user.getAddress ());
            dataRow.createCell (6).setCellValue (user.getUserEmail ()==null?"":user.getUserEmail ());
            dataRow.createCell (7).setCellValue (user.getBalance ()==null?0:user.getBalance ());
            dataRow.createCell (8).setCellValue (user.getPayPwd ()==null?"":user.getPayPwd ());
        }
        String fileName = "用户.xls";
        try {
            FileOutputStream fileOut = new FileOutputStream (fileName);
            hssfWorkbook.write (fileOut);
            hssfWorkbook.close ();
        } catch (FileNotFoundException e) {
            e.printStackTrace ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
    }
}

3.2读操作

ReadXLS.java

package com.excel;

import com.pojo.User;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class ReadXLS {
    public List<User> importXLS(){
        ArrayList<User> list = new ArrayList<> ();
        try {
            String fileName = "用户.xls";
            InputStream inputStream = new FileInputStream (fileName);
            HSSFWorkbook workbook = new HSSFWorkbook (inputStream);
            HSSFSheet sheetAt = workbook.getSheetAt (0);
            for(Row row:sheetAt){
                if (row.getRowNum ()==0){
                    continue;
                }
                Integer userId =(int) row.getCell (0).getNumericCellValue ();
                String via = row.getCell (1).getStringCellValue ();
                String userName = row.getCell (2).getStringCellValue ();
                String userPassword = row.getCell (3).getStringCellValue ();
                String phone = row.getCell (4).getStringCellValue ();
                String address = row.getCell (5).getStringCellValue ();
                String userEmail = row.getCell (6).getStringCellValue ();
                Double balance = row.getCell (7).getNumericCellValue ();
                String payPwd = row.getCell (8).getStringCellValue ();
                User user = new User ();
                user.setUserId (userId);
                user.setVia (via);
                user.setUserName (userName);
                user.setUserPassword (userPassword);
                user.setPhone (phone);
                user.setAddress (address);
                user.setUserEmail (userEmail);
                user.setBalance (balance);
                user.setPayPwd (payPwd);
                list.add (user);
            }
            workbook.close ();
        } catch (IOException e) {
            e.printStackTrace ();
        }
        return list;
    }
}

3.3测试

controller层

package com.controller;

import com.excel.ReadXLS;
import com.excel.WriteXLS;
import com.pojo.User;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class ExcelController {
    @Autowired
    private ReadXLS readXLS;
    @Autowired
    private WriteXLS writeXLS;
    @Autowired
    private UserService userService;

    @RequestMapping("/writeExcel")
    public String WriteExcel(){
        List<User> userList = userService.selectAllUser ();
        System.out.println (userList);
        writeXLS.exportExcel (userList);
        return "成功";
    }

    @RequestMapping("/readExcel")
    public String ReadExcel(){
        List<User> userList = readXLS.importXLS ();
        System.out.println (userList);
        return "成功";
    }
}

测试结果

SpringBoot的POI(Word、Excel文档的读写)_第2张图片

你可能感兴趣的:(Javaweb学习笔记,spring,boot,word,excel)