poi对数据导出&文件下载 ----- 笔记

本文介绍如何使用POI库实现Excel数据的读取与写入,包括样式设置及与数据库的交互,并展示了文件下载功能的具体实现。

一、文件下载

需求

  1. 页面显示超链接
  2. 点击超链接后弹出下载提示框
  3. 完成图片文件下载

思路分析

  1. 超链接指向的资源如果能够被浏览器解析,则在浏览器中展示,如果不能解析,则弹出下载提示 框。不满足需求
  2. 任何资源都必须弹出下载提示框
  3. 使用响应头设置资源的打开方式和类型:
    * content-disposition:attachment;filename=xxx
    * content-type

效果图
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
步骤分析
**1. webapp\download.html下载页面

<a href="/downloadServlet?filename=3.jpg">图片3</a>

2.后端servlet接口/cn.hfnu.download.DownloadServlet

		//1. 获取请求参数,文件名称  filename
        String filename = request.getParameter("filename");

        //2. 使用字节输入流加载文件进内存
        //找到文件服务器路径
        ServletContext context = this.getServletContext();
        String realPath = context.getRealPath("/img/" + filename);

        //使用字节输入流关联源文件
        InputStream is = new FileInputStream(realPath);

        //3. 设置response的响应头
        //设置响应头类型  content-type
        String mimeType = context.getMimeType(filename);
        response.setHeader("content-type", mimeType);
        //设置响应头打开方式 content-disposition
        response.setHeader("content-disposition", "attachment;filename"+filename);

        //4. 用输出流关联目标文件
        ServletOutputStream sos = response.getOutputStream();
        byte[] buffer = new byte[1024 * 8];
        int len;
        while ((len = is.read(buffer)) != -1){
            sos.write(buffer, 0, len);
        }

        //5. 释放资源
        sos.close();
        is.close();
  • servlet的配置路径访问前端页面:@WebServlet(“/downloadServlet”)
问题:
		文件名是中文的问题
			1. 获取客户端使用的浏览器版本信息
			2. 根据不同的版本信息,设置filename的编码方式不同
		//解决中文文件名
        //获取user-agent请求头
        String agent = request.getHeader("user-agent");

        //使用工具类方法编码文件名
        filename = DownLoadUtils.getFileName(agent, filename);
        response.setHeader("content-disposition", "attachment;filename"+filename);

二、从excel读取数据到数据库

引言

  • 通过poi关联输入输出流对excel表的内容进行读取和写入

需求

1. 准备xlsx文件
2. 通过poi读取excel表的内容
3. 通过poi关联输出流向excel中写入内容

思路分析

4. 获取工作簿对象
5. 获取工作表
6. 获取每一行数据
7. 遍历行,获取单元格
8. 释放资源

pom.xml引入poi依赖包

		<!--引入poi的依赖-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.15</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>

JDBCTemplate数据源/druid.properties

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/poidb?useUnicode=true&characterEncoding=UTF-8&characterSetResults=utf-8&userSSL=false&serverTimezone=GMT%2B8
username=root
password=root
# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大等待时间
maxWait=3000

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

核心代码

	@Test
    public void test() throws IOException {
        //1. 获取工作簿
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook("E:\\1.xlsx");

        //2. 获取工作表
        XSSFSheet sheet = xssfWorkbook.getSheetAt(0);

		//增强for循环
        //3. 获取行
        /*for (Row row : sheet) {
            //获取单元格
            for (Cell cell : row) {
                String value = cell.getStringCellValue();
                System.out.println("========单元格=======>"+value);
            }
        }*/
        //for i 循环
        int lastRowNum = sheet.getLastRowNum(); //结束索引
        for (int i = 0; i <= lastRowNum; i++) {
            XSSFRow row = sheet.getRow(i);
            if (row != null){
                short lastCellNum = row.getLastCellNum();
                for (int j = 0; j <= lastCellNum; j++) {
                    XSSFCell cell = row.getCell(j);
                    if (cell != null){
                        String value = cell.getStringCellValue();
                        System.out.println("========单元格=======>"+value);
                    }
                }
            }
        }
        //4. 释放资源
        xssfWorkbook.close();
        System.out.println("=======读取成功=========");
    }
@Test
    public void test() throws IOException {
        //1. 创建工作簿
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook();

        //2. 创建工作表
        XSSFSheet sheet = xssfWorkbook.createSheet("商品信息表");

        //3. 创建行
        XSSFRow row = sheet.createRow(2);
        //创建单元格
        row.createCell(0).setCellValue("爱满天下");
        row.createCell(1).setCellValue("知行合一");
        row.createCell(2).setCellValue("合师校训");

        //3. 创建行
        XSSFRow row1 = sheet.createRow(3);
        //创建单元格
        row1.createCell(0).setCellValue("爱满天下");
        row1.createCell(1).setCellValue("知行合一");
        row1.createCell(2).setCellValue("合师校训");

        //创建字节输出流关联目标文件
        OutputStream os = new FileOutputStream("E:\\1.xlsx");
        xssfWorkbook.write(os);
        os.flush();
        //释放资源
        os.close();
        xssfWorkbook.close();
        System.out.println("=======写入成功=========");

    }

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

	public static List<Product> read(String path) throws IOException {
        List<Product> productList = new ArrayList<>();
        //1. 获取工作簿
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(path);    //"E:\\1.xlsx"

        //2. 获取工作表
        XSSFSheet sheet = xssfWorkbook.getSheetAt(0);

        int lastRowNum = sheet.getLastRowNum();

        for (int i = 1; i <= lastRowNum; i++) {
            XSSFRow row = sheet.getRow(i);
            if (row != null) {
                List<String> list = new ArrayList<>();
                short lastCellNum = row.getLastCellNum();
                for (int j = 0; j <= lastCellNum; j++) {
                    XSSFCell cell = row.getCell(j);
                    if (cell != null) {
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        String value = cell.getStringCellValue();
                        if (value != null && !"".equals(value)) {
                            list.add(value);
                        }
                    }
                }
                if (list.size() > 0) {
                    Product product = new Product(Integer.parseInt(list.get(0)), list.get(1), Double.parseDouble(list.get(2)), Integer.parseInt(list.get(3)));
                    productList.add(product);
                }
            }
        }
        return productList;

    }

三、从数据库写入到excel文件

效果图
在这里插入图片描述
在这里插入图片描述
核心代码

public static void write(List<Product> productList, String path) throws IOException {
        //1. 创建新的工作簿
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook();

        //2. 创建工作表
        XSSFSheet sheet = xssfWorkbook.createSheet("美彤商品");

        //修改单元格的样式
        XSSFCellStyle cellStyle = xssfWorkbook.createCellStyle();
        //设置工作簿的背景
        cellStyle.setFillForegroundColor(IndexedColors.PINK.getIndex());
        //设置颜色填充规则
        cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        //设置字体样式
        XSSFFont font = xssfWorkbook.createFont();
        font.setFontName("楷体");
        font.setColor(IndexedColors.BLUE.getIndex());
        cellStyle.setFont(font);

        //3. 创建行
        XSSFRow row = sheet.createRow(0);
        /*row.createCell(0).setCellValue("商品编号");
        row.createCell(1).setCellValue("商品名称");
        row.createCell(2).setCellValue("商品价格(单位:元/斤)");
        row.createCell(3).setCellValue("商品库存");*/

        XSSFCell cell = row.createCell(0);
        cell.setCellValue("商品编号");
        cell.setCellStyle(cellStyle);

        XSSFCell cell1 = row.createCell(1);
        cell1.setCellValue("商品名称");
        cell1.setCellStyle(cellStyle);

        XSSFCell cell2 = row.createCell(2);
        cell2.setCellValue("商品价格(单位:元/斤)");
        cell2.setCellStyle(cellStyle);

        XSSFCell cell3 = row.createCell(3);
        cell3.setCellValue("商品库存");
        cell3.setCellStyle(cellStyle);

        for (int i = 0; i < productList.size(); i++) {
            XSSFRow row1 = sheet.createRow(i + 1);
            row1.createCell(0).setCellValue(productList.get(i).getPid());
            row1.createCell(1).setCellValue(productList.get(i).getPname());
            row1.createCell(2).setCellValue(productList.get(i).getPrice());
            row1.createCell(3).setCellValue(productList.get(i).getPstock());
        }

        //创建字节输出流关联目标文件    E:\\hsp002.xlsx
        OutputStream os = new FileOutputStream(path);
        xssfWorkbook.write(os);

        os.flush();
        //释放资源
        os.close();
        xssfWorkbook.close();
    }

四、poi操作excel表的样式设置

核心代码

		//修改单元格的样式
        XSSFCellStyle cellStyle = xssfWorkbook.createCellStyle();
        //设置工作簿的背景
        cellStyle.setFillForegroundColor(IndexedColors.PINK.getIndex());
        //设置颜色填充规则
        cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
        //设置字体样式
        XSSFFont font = xssfWorkbook.createFont();
        font.setFontName("楷体");
        font.setColor(IndexedColors.BLUE.getIndex());
        cellStyle.setFont(font);
        //3. 创建行
        XSSFRow row = sheet.createRow(0);
        /*row.createCell(0).setCellValue("商品编号");
        row.createCell(1).setCellValue("商品名称");
        row.createCell(2).setCellValue("商品价格(单位:元/斤)");
        row.createCell(3).setCellValue("商品库存");*/

        XSSFCell cell = row.createCell(0);
        cell.setCellValue("商品编号");
        cell.setCellStyle(cellStyle);

        XSSFCell cell1 = row.createCell(1);
        cell1.setCellValue("商品名称");
        cell1.setCellStyle(cellStyle);

        XSSFCell cell2 = row.createCell(2);
        cell2.setCellValue("商品价格(单位:元/斤)");
        cell2.setCellStyle(cellStyle);

        XSSFCell cell3 = row.createCell(3);
        cell3.setCellValue("商品库存");
        cell3.setCellStyle(cellStyle);

以上内容是我对poi对excel表格的内容进行读取和存入并完成和数据库的交互,以及结合文件下载前置知识,后续我将根据这篇内容完成前端页面的通过文件下载对excel表数据分数量导出。敬请期待!如果你在看,点击下方“在看”,点个赞,你会变好看。我们的目标是和人民日报站一起。
想要了解更多细节,可自取下方源码学习
链接:
https://pan.baidu.com/s/1ljKMo7DzF3ehMa1smHqiMA?pwd=qrn4
提取码:qrn4
学习过程中有啥问题,可在评论区留言,相互学习~~~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Husp0707

你的小小点赞、关注是我的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值