前言:在实际开发中经常需要将数据库的数据导出成excel文件,poi方式则是其中一种较为常用的导出框架。简单读取excel文件在之前的一篇有说明

本项目实现需求:user发出一个导出student信息的请求,直接下载包含所有student信息的excel文件到本机。只贴出关键代码,未贴出的很简单,自行脑补

整体流程(服务器端):接收请求------>取出数据库数据------>将数据存成excel临时文件------>通过响应头让浏览器下载此临时文件------>删除临时文件

项目结构:

1.导入依赖

<!--poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>

2.controller

package com.zjk.excel.controller;

import com.zjk.excel.service.UserServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.*; /**
* @Auther: zjk
* @Date: 2019/9/16
* @Description:
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
UserServiceI userServiceI; @RequestMapping("/export")
public void exportStu(HttpServletResponse response){
//设置默认的下载文件名
String name = "学生信息表.xlsx";
try {
//避免文件名中文乱码,将UTF8打散重组成ISO-8859-1编码方式
name = new String (name.getBytes("UTF8"),"ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//设置响应头的类型
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//让浏览器下载文件,name是上述默认文件下载名
response.addHeader("Content-Disposition","attachment;filename=\"" + name + "\"");
InputStream inputStream=null;
OutputStream outputStream=null;
//在service层中已经将数据存成了excel临时文件,并返回了临时文件的路径
String downloadPath = userServiceI.exportStu();
//根据临时文件的路径创建File对象,FileInputStream读取时需要使用
File file = new File(downloadPath);
try {
//通过FileInputStream读临时文件,ServletOutputStream将临时文件写给浏览器
inputStream = new FileInputStream(file);
outputStream = response.getOutputStream();
int len = -1;
byte[] b = new byte[1024];
while((len = inputStream.read(b)) != -1){
outputStream.write(b);
}
//刷新
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭输入输出流
try {
if(inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
} }
//最后才能,删除临时文件,如果流在使用临时文件,file.delete()是删除不了的
file.delete();
}
}

3.service

package com.zjk.excel.service.impl;

import com.zjk.excel.dao.StudentDao;
import com.zjk.excel.dao.UserDao;
import com.zjk.excel.entity.Student;
import com.zjk.excel.service.UserServiceI;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import java.io.*;
import java.util.List;
import java.util.UUID; /**
* @Auther: zjk
* @Date: 2019/9/16
* @Description:
*/
@Service
public class UserService implements UserServiceI {
  //创建临时文件存放的路径
private String temp="d:\\temp\\excel\\"; @Autowired
UserDao userDao; @Autowired
StudentDao studentDao; @Override
public String exportStu() { List<Student> list = studentDao.queryAllStu();
//创建工作簿
XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
//创建工作表
XSSFSheet sheet = xssfWorkbook.createSheet();
xssfWorkbook.setSheetName(0,"学生信息表");
//创建表头
XSSFRow head = sheet.createRow(0);
String[] heads = {"编号","姓名","年龄","性别","手机号"};
for(int i = 0;i < 5;i++){
XSSFCell cell = head.createCell(i);
cell.setCellValue(heads[i]);
}
for (int i = 1;i <= 4;i++) {
Student student = list.get(i - 1);
//创建行,从第二行开始,所以for循环的i从1开始取
XSSFRow row = sheet.createRow(i);
//创建单元格,并填充数据
XSSFCell cell = row.createCell(0);
cell.setCellValue(student.getS_id());
cell = row.createCell(1);
cell.setCellValue(student.getS_name());
cell = row.createCell(2);
cell.setCellValue(student.getS_age());
cell = row.createCell(3);
cell.setCellValue("男".equals(student.getS_gender().trim())?"男":"女");
cell = row.createCell(4);
cell.setCellValue(student.getS_tel());
}
//创建临时文件的目录
File file = new File(temp);
if(!file.exists()){
file.mkdirs();
}
//临时文件路径/文件名
String downloadPath = file + "\\" +System.currentTimeMillis() + UUID.randomUUID();
OutputStream outputStream = null;
try {
       //使用FileOutputStream将内存中的数据写到本地,生成临时文件
outputStream = new FileOutputStream(downloadPath);
xssfWorkbook.write(outputStream);
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return downloadPath;
}
}

4.效果

WPS打开后:可以说是非常的丑陋了,接下来优化一下

在service中增加如下代码:总体而言还是很麻烦的,创建CellStyle,还要在你想改变样式的cell进行cell.setCellStyle(style1)才可以

*博主用的版本比较新,所以很多地方较旧版本有区别

        //创建styleHead
CellStyle styleHead = xssfWorkbook.createCellStyle();
styleHead.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());//背景色
styleHead.setFillPattern(FillPatternType.SOLID_FOREGROUND);
styleHead.setAlignment(HorizontalAlignment.CENTER);//水平居中
XSSFFont font = xssfWorkbook.createFont();
font.setBold(true);//加粗
font.setFontHeight((short)240);//字体大小
styleHead.setFont(font);
//创建style1
CellStyle style1 = xssfWorkbook.createCellStyle();
style1.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());//背景色
style1.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style1.setAlignment(HorizontalAlignment.CENTER);//水平居中
//创建style2
CellStyle style2 = xssfWorkbook.createCellStyle();
style2.setFillForegroundColor(IndexedColors.LIGHT_TURQUOISE.getIndex());//背景色
style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style2.setAlignment(HorizontalAlignment.CENTER);//水平居中    
     sheet.setColumnWidth(4,3500);//给第5列设置宽度(tel栏)

优化后:

总结一下:

poi的简单使用还是不难的,说白了就数据库一个表对应一个sheet,表的一行对应一个row,表某一行的一个数据对应一个cell,嗯,就是这么简单。

  说到调样式就非常头疼了,而且新版本的较之前改动比较大,百度出来的东西很多都没法用,勉强捣鼓了一些出来。

  最后给自己打打气-——世上无难事,只要肯登攀!

注意事项:

  不要使用post请求,应该用get请求

最后推荐一个中文poi文档:

https://www.cnblogs.com/fqfanqi/p/6172223.html

springboot2.1.8使用poi导出数据生成excel(.xlsx)文件的更多相关文章

  1. Java操作Jxl实现导出数据生成Excel表格数据文件

    实现:前台用的框架是Easyui+Bootstrap结合使用,需要引入相应的Js.Css文件.页面:Jsp.拦截请求:Servlet.逻辑处理:ClassBean.数据库:SQLserver. 注意: ...

  2. 使用poi导出数据到excel

    一.首先是导入poi所需要的jar包,我是用的是maven,添加jar包依赖 <dependency> <groupId>org.apache.poi</groupId& ...

  3. java利用poi导出数据到excel

    背景: 上一篇写到利用jtds连接数据库获取对应的数据,本篇写怎样用poi将数据到处到excel中,此程序为Application 正文: 第三方poi jar包:poi驱动包下载 代码片段: /** ...

  4. 导出数据生成Excel(MVC)

    /// <summary> /// 生成Excel /// </summary> /// <returns></returns> public File ...

  5. 生成Excel.xlsx文件 iOS

    使用到的三方库 https://github.com/jmcnamara/libxlsxwriter cocoapods导入 pod 'libxlsxwriter', '~> 0.8.3' 1. ...

  6. Java导出数据生成Excel表格

    事先准备: 工具类: package com.wazn.learn.util.export; import java.sql.Connection; import java.sql.DriverMan ...

  7. spring boot 使用POI导出数据到Excel表格

    在spring boot 的项目经常碰到将数据导出到Excel表格的需求,而POI技术则对于java操作Excel表格提供了API,POI中对于多种类型的文档都提供了操作的接口,但是其对于Excel表 ...

  8. Python导出数据生成excel报表

    #_*_coding:utf-8_*_ import MySQLdb import xlwt from datetime import datetime def get_data(sql): # 创建 ...

  9. Java导出数据为EXCEL的两种方式JXL和POI

    JXL和POI导出数据方式的比较 POI支持excel2003和2007,而jxl只支持excel2003. 下面为测试代码: public class TestCondition { /** * 生 ...

随机推荐

  1. LeetCode 988. Smallest String Starting From Leaf

    原题链接在这里:https://leetcode.com/problems/smallest-string-starting-from-leaf/ 题目: Given the root of a bi ...

  2. LOJ P10018 数的划分 题解

    每日一题 day52 打卡 Analysis 这道题直接搜索会TLE到**,但我们发现有很多没有用的状态可以删去,比如 1,1,5; 1,5,1; 5,1,1; 所以很容易想到一个优化:按不下降的顺序 ...

  3. vue 首页导航+左侧菜单

    1. Mock.js 前后端分离开发开发过程当中,经常会遇到以下几个尴尬的场景: 1. 老大,接口文档还没输出,我的好多活干不下去啊! 2. 后端小哥,接口写好了没,我要测试啊! 前后端分离之后,前端 ...

  4. CSS行内块元素(内联元素)

    一.典型代表 input img 二.特点: 在一行上显示 可以设置宽高 <style type="text/css"> img{ width: 300px; /* 顶 ...

  5. 18-ESP8266 SDK开发基础入门篇--TCP 服务器 RTOS版,串口透传,TCP客户端控制LED

    https://www.cnblogs.com/yangfengwu/p/11112015.html 先规定一下协议 aa 55 02 01 F1 4C 控制LED点亮  F1 4C为CRC高位和低位 ...

  6. JavaScript中字符串多行编辑

    常用写法: var str = 'w3c' +'标准' +'方式.' 升级版:var str = ['w3c','标准','方式.'].join('');终极版:var str = 'w3c\标准\方 ...

  7. Spring重定向

    1.使用HttpServletResponse的sendRedirect()方法. 示例: @PostMapping("/user/product/id") public void ...

  8. JSP的工作原理

    jsp的本质就是一个servlet,jsp在第一次被访问时会被Web容器翻译成servlet index.jsp -> index_jsp.java -> 编译成index_jsp.cla ...

  9. 团队作业-Alpha(2/4)

    队名:软工9组 组长博客:https://www.cnblogs.com/cmlei/ 作业博客:http://edu.cnblogs.com/campus/fzu/SoftwareEngineeri ...

  10. phpstudy5.6 No input file specified的解决方法

    一.问题描述 5.6就提示这个错误,切换5.5就可以 二.原因分析 原因1:提示:“No input file specified.”原因在于使用的PHP5.6是fast_cgi模式,而在某些情况下, ...