hutool功能很强大,http请求到json处理、excel的导入导出、定时任务、IO、缓存、数据库操作等都提供了简单而方便的api供我们使用,好处是再也不用担心自己去整理常用的工具类了,同时也支持按需引入【但一般项目都是直接一如hutool-all 导致项目引入很多不必要的工具类】。
从2014年首次发布第一版本到现在已经8年了,这款国产工具类确实收获了越来越多的关注,而且社区的热度是可以的,但是比起Apache或者谷歌提供的工具类,更新频率和可靠性也许稍差,但在我看来是可以考虑使用的。
我们要的效果:
所需编写的代码:
- @GetMapping("/exportTemplate")
- public void exportTemplate(HttpServletResponse response) throws IOException {
- String column1Name1 = "时间戳";
- String column1Name2 = "设备名称";
-
- List
headList = new ArrayList<>(); - headList.add(column1Name1);
- headList.add(column1Name2);
-
- //在内存操作,写到浏览器
- ExcelWriter writer= ExcelUtil.getWriter(true);
-
- // 设置表头的宽度
- writer.setColumnWidth(0, 20);
- writer.setColumnWidth(1, 15);
-
- writer.writeHeadRow(headList).write(Collections.emptyList());
- //设置content—type
- response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");
-
- //Content-disposition是MIME协议的扩展,MIME协议指示MIME用户代理如何显示附加的文件。
- response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode("数据集导入模板","UTF-8")+".xlsx");
- ServletOutputStream outputStream= response.getOutputStream();
-
- //将Writer刷新到OutPut
- writer.flush(outputStream,true);
- outputStream.close();
- writer.close();
- }
我们要的效果:
所需编写的代码:
- @GetMapping("/exportTemplate")
- public void exportTemplate(HttpServletResponse response) throws IOException {
- String column1Name1 = "时间戳";
- String column1Name2 = "设备名称";
-
- List
headList = new ArrayList<>(); - headList.add(column1Name1);
- headList.add(column1Name2);
-
- //在内存操作,写到浏览器
- ExcelWriter writer= ExcelUtil.getWriter(true);
-
- // 设置表头的宽度
- writer.setColumnWidth(0, 20);
- writer.addHeaderAlias("timestamp",column1Name1);
- writer.setColumnWidth(1, 15);
- writer.addHeaderAlias("deviceName",column1Name2);
-
- // 默认的,未添加alias的属性也会写出,如果想只写出加了别名的字段,可以调用此方法排除之
- writer.setOnlyAlias(true);
-
- // 表格内容【相比上一节新内容】
- List
excelList = new ArrayList<>(); - CollectDataExcelVo vo1 = new CollectDataExcelVo();
- vo1.setDeviceName("A类设备");
- vo1.setTimestamp(DateUtil.format(new Date()));
- excelList.add(vo1);
- CollectDataExcelVo vo2 = new CollectDataExcelVo();
- vo2.setDeviceName("B类设备");
- vo2.setTimestamp(DateUtil.format(new Date()));
- excelList.add(vo2);
-
- writer.writeHeadRow(headList).write(excelList);
- //设置content—type
- response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");
-
- //Content-disposition是MIME协议的扩展,MIME协议指示MIME用户代理如何显示附加的文件。
- response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode("数据集导入模板","UTF-8")+".xlsx");
- ServletOutputStream outputStream= response.getOutputStream();
-
- //将Writer刷新到OutPut
- writer.flush(outputStream,true);
- outputStream.close();
- writer.close();
- }
- @Data
- public class CollectDataExcelVo {
- /**
- * 时间戳
- */
- @ApiModelProperty(value = "时间戳")
- private String timestamp;
- /**
- * 设备编码
- */
- @ApiModelProperty(value = "设备名称")
- private String deviceName;
- }
我们要的效果:
所需编写的代码:
- @GetMapping("/exportTemplate")
- public void exportTemplate(HttpServletResponse response) throws IOException {
- String column1Name1 = "时间戳";
- String column1Name2 = "设备名称";
-
- List
headList = new ArrayList<>(); - headList.add(column1Name1);
- headList.add(column1Name2);
-
- //在内存操作,写到浏览器
- ExcelWriter writer= ExcelUtil.getWriter(true);
-
- // 设置表头的宽度
- writer.setColumnWidth(0, 20);
- writer.addHeaderAlias("timestamp",column1Name1);
- writer.setColumnWidth(1, 15);
- writer.addHeaderAlias("deviceName",column1Name2);
-
- // 默认的,未添加alias的属性也会写出,如果想只写出加了别名的字段,可以调用此方法排除之
- writer.setOnlyAlias(true);
-
- // 表格下拉框【相比上一节新内容】
- writer.addSelect(1, 1, new String[]{"1#进线","2#进线", "3#进线"});
- writer.writeHeadRow(headList).write(Collections.emptyList());
-
- //设置content—type
- response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");
-
- //Content-disposition是MIME协议的扩展,MIME协议指示MIME用户代理如何显示附加的文件。
- response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode("数据集导入模板","UTF-8")+".xlsx");
- ServletOutputStream outputStream= response.getOutputStream();
-
- //将Writer刷新到OutPut
- writer.flush(outputStream,true);
- outputStream.close();
- writer.close();
- }
EasyExcel是阿里巴巴开源的一个excel处理框架,以使用简单、节省内存著称;能大大减少占用内存的主要原因是在解析Excel时没有将文件数据一次性全部加载到内存中,而是从磁盘上一行行读取数据,逐个解析。
我们要的效果:
所需编写的代码:
pom引入依赖:
- <dependency>
- <groupId>com.alibabagroupId>
- <artifactId>easyexcelartifactId>
- <version>3.0.5version>
- dependency>
- <dependency>
- <groupId>org.apache.poigroupId>
- <artifactId>poi-ooxmlartifactId>
- <version>4.1.2version>
- dependency>
java代码:
- import com.alibaba.excel.annotation.ExcelProperty;
- import com.alibaba.excel.annotation.write.style.ColumnWidth;
- import io.swagger.annotations.ApiModelProperty;
- import lombok.Data;
-
- @Data
- public class CollectDataExcelVo {
- /**
- * 时间戳
- */
- @ExcelProperty(value = "时间戳", index = 0)
- @ColumnWidth(value = 20)
- @ApiModelProperty(value = "时间戳")
- private String timestamp;
- /**
- * 设备名称
- */
- @ExcelProperty(value = "设备名称", index = 1)
- @ColumnWidth(value = 15)
- @ApiModelProperty(value = "设备名称")
- private String deviceName;
- }
- @GetMapping("/exportTemplate")
- public void exportTemplate(HttpServletResponse response) throws IOException {
- // 模拟数据库获取数据
- List
list = data(); -
- response.setCharacterEncoding(StandardCharsets.UTF_8.name());
- response.setHeader("content-Type", "application/vnd.ms-excel");
- response.setHeader("Content-Disposition",
- "attachment;filename=" + URLEncoder.encode("template"+ DateUtils.format(new Date(), "yyyy-MM-dd")+".xlsx", StandardCharsets.UTF_8.name()));
-
- EasyExcel.write(response.getOutputStream(), CollectDataExcelVo.class).sheet().doWrite(list);
- }
-
- private List
data() { - List
list = ListUtils.newArrayList(); - for (int i = 1; i <= 2; i++) {
- CollectDataExcelVo data = new CollectDataExcelVo();
- data.setTimestamp(DateUtil.format(new Date()));
- data.setDeviceName("A类设备"+i);
- list.add(data);
- }
- return list;
- }
将文件从项目工程的 resources/file 目录下导出,所需代码如下:
- import org.apache.poi.util.IOUtils;
-
- @GetMapping("/exportTemplate")
- public void exportTemplate(HttpServletResponse response) {
-
- InputStream inputStream = null;
- OutputStream outputStream = null;
- try {
- String fileName= URLEncoder.encode("template","UTF-8");
- outputStream = response.getOutputStream();
- // 获取springboot resource 路径下的文件
- inputStream = this.getClass().getResourceAsStream("/file/template.xlsx");
- response.setContentType("application/vnd.ms-excel");
- response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
- IOUtils.copy(inputStream, outputStream);
-
- } catch (Exception e) {
- throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.toString());
- } finally {
- closeInput(inputStream);
- flushOutput(outputStream);
-
- }
- }
-
- private void flushOutput(OutputStream outputStream) {
- try {
- outputStream.flush();
- } catch (IOException e) {
- logger.error("释放流异常", e);
- }
- }
-
- private void closeInput(InputStream inputStream) {
- try {
- inputStream.close();
- } catch (IOException e) {
- logger.error("释放流异常", e);
- }
- }
导出后会存在问题 excel文件导出后打不开!! 只需再pom.xml中配置如下即可:
- <plugins>
-
- <plugin>
- <groupId>org.apache.maven.pluginsgroupId>
- <artifactId>maven-resources-pluginartifactId>
- <configuration>
- <encoding>UTF-8encoding>
- <nonFilteredFileExtensions>
- <nonFilteredFileExtension>xlsnonFilteredFileExtension>
- <nonFilteredFileExtension>xlsxnonFilteredFileExtension>
- nonFilteredFileExtensions>
- configuration>
- plugin>
- plugins>
easypoi 也是国产开源的软件,它通过简单的注解和模板语言 (熟悉的表达式语法),就可以实现excel的导入导出功能。
我们要的效果:
所需编写的代码:
pom引入依赖:
-
-
cn.afterturn -
easypoi-base -
4.1.0 -
-
-
cn.afterturn -
easypoi-web -
4.1.0 -
-
-
cn.afterturn -
easypoi-annotation -
4.1.0 -
java代码:
- // 工具类
- public class ExcelUtil {
-
- public static void exportExcel(List> list, Class> pojoClass, String fileName, boolean isCreateHeader, HttpServletResponse response) {
- ExportParams exportParams = new ExportParams();
- exportParams.setCreateHeadRows(isCreateHeader);
- Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
- if (workbook != null) ;
- try {
- response.setCharacterEncoding("UTF-8");
- response.setHeader("content-Type", "application/vnd.ms-excel");
- response.setHeader("Content-Disposition",
- "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
- workbook.write(response.getOutputStream());
- } catch (IOException e) {
- try {
- throw new Exception(e.getMessage());
- } catch (Exception e1) {
- e1.printStackTrace();
- }
- }
- }
-
- }
- import cn.afterturn.easypoi.excel.annotation.Excel;
- import lombok.Data;
- import java.util.Date;
-
- @Data
- public class CollectDataExcelVo {
- /**
- * 时间戳
- */
- @Excel(name = "时间戳",format="yyyy-MM-dd HH:mm:ss", width = 20.0)
- private Date timestamp;
- /**
- * 设备编码
- */
- @Excel(name = "设备名称", width = 20)
- private String deviceName;
- }
-
- @GetMapping("/export")
- @ApiOperation("导出数据")
- public void export(HttpServletResponse response) {
- String fileName = "template"+".xls";
- List
list = data(); - ExcelUtil.exportExcel(list, CollectDataExcelVo.class, fileName, true, response);
- }
============
以上就是博主的excel导出方式总结,如有问题 欢迎在评论区留言