Java Excel导出, 导入 支持2007 xlsx, 2003 xls (org.apache.poi, poi-ooxml)基本用法(一) 亲测

28 篇文章 0 订阅
10 篇文章 0 订阅

1. Maven包


      <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.10-FINAL</version>
      </dependency>
      <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.10-FINAL</version>
      </dependency>
      

2. 数据库 test 和数据表 user及相关测试数据


CREATE DATABASE `test` DEFAULT CHARSET utf8;
CREATE TABLE `user` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `age` int(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES (1, '工作人员1', 21);
INSERT INTO `user` VALUES (2, '工作人员2', 22);
INSERT INTO `user` VALUES (3, '工作人员3', 23);

3. User.java(Entity)与 user数据表字段对应


import java.io.Serializable;

public class User implements Serializable {
    private static final long serialVersionUID = 8755803182642361875L;

    private Long id;

    private Long age;

    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getAge() {
        return age;
    }

    public void setAge(Long age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

4. DAO(Data Access Object)数据访问接口 UserDao.java和实现类 UserDaoImpl.java


/**
* User的数据访问接口 UserDao.java
*/
import com.test.web2.entity.User;
import java.util.List;

public interface UserDao {
    List<User> getList();
}

/**
* 实现类 UserDaoImpl.java
*/
import com.test.web2.dao.UserDao;
import com.test.web2.entity.User;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private SqlSession sqlSession;

    static final String MAPPER = "com.test.web2.UserMapper.";

    @Override
    public List<User> getList() {
        return sqlSession.selectList(MAPPER + "getList");
    }

}

5. UserMapper.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.test.web2.UserMapper">

	<select id="getList" resultType="com.test.web2.entity.User">
		SELECT `id`,`age`,`name` FROM `user` ORDER BY `id` ASC
	</select>

</mapper>

6. ExcelUtil.java相关工具类


import org.apache.poi.hssf.usermodel.*;

public class ExcelUtil {
    public static HSSFWorkbook getHSSFWorkbook(String sheetName, String []title, String [][] values, HSSFWorkbook wb) {
        if (wb == null) {
            wb = new HSSFWorkbook();
        }

        HSSFSheet sheet = wb.createSheet(sheetName);

        HSSFRow row = sheet.createRow(0);

        HSSFCellStyle style = wb.createCellStyle();

        HSSFCell cell;

        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        int tcount = title.length;
        for (int i = 0;i < tcount;i++) {
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }

        int vcount1 = values.length;
        for (int i = 0;i < vcount1;i++) {
            row = sheet.createRow(i + 1);
            int vcount2 = values[i].length;
            for (int j = 0;j < vcount2;j++) {
                row.createCell(j).setCellValue(values[i][j]);
            }
        }

        return wb;
    }

}

7. UserController.java(入口)


import com.test.web2.dao.UserDao;
import com.test.web2.entity.User;
import com.test.web2.util.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Controller
public class UserController {
    @Autowired
    private UserDao userDao;

    @RequestMapping("/exportUsers")
    public void exportUsers(HttpServletResponse response) {
        /**
         * 获取用户列表
         * */
        final List<User> listData = userDao.getList();

        /** Excel SheetName名称*/
        final String sheetName = "用户明细表";

        /** Excel标题*/
        final String[] title = {"编号", "称呼", "年龄"};

        /** 今天日期(用于文件名)*/
        final String date = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now());

        /** Excel文件名*/
        final String fileName = sheetName + "-" + date + ".xls";

        /** 数据行数*/
        final Integer dataCount = listData.size();
        final String[][] content = new String[dataCount][3];

        for (int i = 0; i < dataCount; i++) {
            final User user = listData.get(i);
            content[i][0] = user.getId().toString();
            content[i][1] = user.getName();
            content[i][2] = user.getAge().toString();
        }

        /** 创建HSSFWorkbook*/
        final HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        /** 响应到客户端*/
        try {
            this.setResponseHeader(fileName, response);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送响应流方法
     * */
    public void setResponseHeader(String fileName, final HttpServletResponse response) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}

调用导出 Excel接口


http://127.0.0.1:8080/exportUsers

在这里插入图片描述
在这里插入图片描述

如果您觉得有帮助,欢迎点赞哦 ~ 谢谢!!

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值