Java之POI操作Excel表-导入导出

感谢:https://www.jianshu.com/p/4f08c27ca0c4的文章。

Maven 配置

    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.16</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.16</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml-schemas</artifactId>
        <version>3.16</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans -->
    <dependency>
        <groupId>org.apache.xmlbeans</groupId>
        <artifactId>xmlbeans</artifactId>
        <version>2.6.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
    <dependency>
        <groupId>dom4j</groupId>
        <artifactId>dom4j</artifactId>
        <version>1.6.1</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>

首先是两个写入数据和导出数据的demo.

新建Excel表写入数据的OutputExcelDemo类

package com.hjl.util;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by huangMP on 2017/8/20.
 * decription :
 */
public class OutputExcelDemo {

    /**
     *  从 工作簿中写入 数据 OutputExcelDemo
     * 07 版本及之前的版本写法
     * @throws IOException
     */
    public void outputExcel() throws IOException {
        // 1. 创建工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();

        // 2. 创建工作类
        HSSFSheet sheet = workbook.createSheet("hello world");

        // 3. 创建行 , 第三行 注意:从0开始
        HSSFRow row = sheet.createRow(2);

        // 4. 创建单元格, 第三行第三列 注意:从0开始
        HSSFCell cell = row.createCell(2);
        cell.setCellValue("Hello World");

        String fileName = "D:\\huangMP\\Desktop\\OutputExcelDemo.xls";
        FileOutputStream fileOutputSteam = new FileOutputStream(fileName);

        workbook.write(fileOutputSteam);
        workbook.close();

        fileOutputSteam.close();
    }
}

读取Excel表的ReadExcelDemo类

package com.hjl.util;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;

/**
 * 从 工作簿中读取 数据 ReadExcelDemo
 * @throws IOException
 */
public class ReadExcelDemo {

    public void readExel() throws IOException {

        String fileName = "D:\\huangMP\\Desktop\\OutputExcelDemo.xls";
        FileInputStream fileInputStream = new FileInputStream(fileName);

        // 1. 创建工作簿
        HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);

        // 2. 创建工作类
        HSSFSheet sheet = workbook.getSheetAt(0);

        // 3. 创建行 , 第三行 注意:从0开始
        HSSFRow row = sheet.getRow(2);

        // 4. 创建单元格, 第三行第三列 注意:从0开始
        HSSFCell cell = row.getCell(2);
        String cellString = cell.getStringCellValue();

        System.out.println("第三行第三列的值为 : " + cellString );

        workbook.close();
        fileInputStream.close();
    }
}

根据以上demo结合数据库操作:
测试表userinfo

/*
SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for userinfo
-- ----------------------------
DROP TABLE IF EXISTS `userinfo`;
CREATE TABLE `userinfo` (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `phone` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `sex` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

-- ----------------------------
-- Records of userinfo
-- ----------------------------
INSERT INTO `userinfo` VALUES ('1', '张三', '1234556', '男');
INSERT INTO `userinfo` VALUES ('2', '五万', '321321', '女');

不做对应业务逻辑处理,可直接调用userMapper

userMapper.java

public interface UserMapper {
    List<UserInfo> select();
    int insertUserInfoList(List<UserInfo> list);
}

userInfoMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hjl.dao.UserMapper">
    <select id="select" resultType="com.hjl.pojo.UserInfo">
    	select * from userinfo
  	</select>
  	
  	<insert id="insertUserInfoList"  parameterType="java.util.List">
    	insert into userinfo(userName,phone,sex) values
      <foreach collection="list" item="userInfo" index="index" separator=",">
          (
          #{userInfo.userName},#{userInfo.phone},#{userInfo.sex}
          )
      </foreach>
    </insert>
</mapper>

1.导出数据库表生成Excel。

package com.hjl.service;

import com.hjl.pojo.UserInfo;
import com.hjl.springbootmybatisdemo.SpringbootMybatisDemoApplication;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

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


@SpringBootTest(classes =SpringbootMybatisDemoApplication.class)
class OutputExcel {

   @Autowired
    private UserMapper userMapper;
    @Test
    void select() throws IOException {
        List<UserInfo> userInfoList=userMapper.select();
        outputExcel(userInfoList);
    }

    /**
     * 导出excel
     *  从 工作簿中写入 数据 OutputExcelDemo
     * 07 版本及之前的版本写法
     * @throws IOException
     */
    public void outputExcel(List<UserInfo> userInfoList) throws IOException {
        // 1. 创建工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();

        // 2. 创建工作类
        HSSFSheet sheet = workbook.createSheet("hello world");

        // 3. 创建行  注意:从0开始
        HSSFRow hssfRow = sheet.createRow(0);//表的标题行
        hssfRow.createCell(0).setCellValue("UserId");//第一列 创建
        hssfRow.createCell(1).setCellValue("UserName");
        hssfRow.createCell(2).setCellValue("phone");
        hssfRow.createCell(3).setCellValue("sex");

        //从1开始
        for (int rowNume=1;rowNume<=userInfoList.size();rowNume++){
            HSSFRow row = sheet.createRow(rowNume);//假设有4个字段
            for (int cellNume=0;cellNume<4;cellNume++){
            // 4. 创建单元格 注意:从0开始
            HSSFCell cell = row.createCell(cellNume);

            switch(cellNume){
                    case 0:
                        cell.setCellValue(userInfoList.get(rowNume-1).getUserId());break;
                    case 1:
                        cell.setCellValue(userInfoList.get(rowNume-1).getUserName());break;
                    case 2:
                        cell.setCellValue(userInfoList.get(rowNume-1).getPhone());break;
                    case 3:
                        cell.setCellValue(userInfoList.get(rowNume-1).getSex());break;
                }
            }
        }
        String fileName = "D:\\OutputExcelDemo.xls";
        FileOutputStream fileOutputSteam = new FileOutputStream(fileName);
        workbook.write(fileOutputSteam);
        workbook.close();
        fileOutputSteam.close();
        System.out.println("导出成功!path:"+fileName);
    }
}

2.读取Excel表的数据存入数据库。

package com.hjl.service;


import com.hjl.dao.UserMapper;
import com.hjl.pojo.UserInfo;
import com.hjl.springbootmybatisdemo.SpringbootMybatisDemoApplication;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

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

@SpringBootTest(classes = SpringbootMybatisDemoApplication.class)
public class ReadExcel {
    @Autowired
    private UserMapper userMapper;

    @Test
    void select() throws IOException {
        String fileName="D:\\OutputExcelDemo.xls";
        List<UserInfo> list=readExels(fileName);//读取excel表数据
        int num=userMapper.insertUserInfoList(list);//批量插入数据
        System.out.println("成功:"+num +",失败:"+(list.size()-num));
    }

    /**
     * 从 工作簿中读取 数据 ReadExcelDemo
     * @throws IOException
     */
    public static List<UserInfo> readExels(String fileName) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(fileName);
        HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
        HSSFSheet sheet = workbook.getSheetAt(0);
        List<UserInfo> list= new ArrayList<>();
        HSSFRow row=null;
        HSSFCell cell=null;
        //3.遍历行row 从第1行开始 0是表的标题行
        for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
            //获取每一行
            row = sheet.getRow(rowNum);
            if (row == null) {
                continue;
            }
            UserInfo userInfo = new UserInfo();
            //4.遍历列cell
            for (int cellNum = 0; cellNum < row.getLastCellNum(); cellNum++) {
                //获取每一列
                cell = row.getCell(cellNum);
                if (cell == null){
                    continue;
                }
                cell.setCellType(CellType.STRING);//设置单元格类型为String
                String str=cell.getStringCellValue();
                switch(cellNum){
                    case 0:
                        userInfo.setUserId(Integer.parseInt(str));break;
                    case 1:
                        userInfo.setUserName(str);break;
                    case 2:
                        userInfo.setPhone(str);break;
                    case 3:
                        userInfo.setSex(str);break;
                }
            }
            if (StringUtils.isBlank(userInfo.getUserName())) {
                continue;
            }
            list.add(userInfo);
        }
        workbook.close();
        fileInputStream.close();
        return  list;
    }
}

扩展批量插入、更新、删除:https://www.jianshu.com/p/041bec8ae6d3

批量更新
userMapper.java添加

    int UpdateUserInfo(List<UserInfo> list);

userInfoMapper.xml添加

 <update id="UpdateUserInfo" parameterType="java.util.List" >
        update userinfo
          <trim prefix="set" suffixOverrides=",">
              <trim prefix="USERNAME=case" suffix="end,">
                  <foreach collection="list" item="i" index="index">
                      <if test="i.userName!=null">
                          when userId=#{i.userId} then #{i.userName}
                      </if>
                  </foreach>
              </trim>

              <trim prefix="PHONE=case" suffix="end,">
                  <foreach collection="list" item="i" index="index">
                      <if test="i.phone!=null">
                          when userId=#{i.userId} then #{i.phone}
                      </if>
                  </foreach>
              </trim>

              <trim prefix="SEX=case" suffix="end,">
                  <foreach collection="list" item="i" index="index">
                      <if test="i.sex!=null">
                          when userId=#{i.userId} then #{i.sex}
                      </if>
                  </foreach>
              </trim>
          </trim>
          where
          <foreach collection="list" item="i" separator="or" index="index">
              userId=#{i.userId}
          </foreach>
    </update>

更新

	@Autowired
    private UserMapper userMapper;	
    
 	@Test
    void updateUserInfo() throws IOException {
        String fileName="D:\\OutputExcelDemo.xls";
        List<UserInfo> list=readExels(fileName);//读取excel表数据
        int num=userMapper.UpdateUserInfo(list);//批量更新数据
        System.out.println("成功:"+num +",失败:"+(list.size()-num));
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值