hutool工具 导出excel
前言
本周接到导出数据到excel的任务,第一次写还是很感兴趣的,写完感觉很简单
需求场景:根据时间段统计每天系统中引用数据量及点击量
中间*号列可选
废话不多说直接上步骤
一、pandas是什么?
示例:pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
二、步骤
1.依赖导入
<!-- 基本依赖包 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version></version>
</dependency>
<!-- Excel包 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version></version>
</dependency>
代码如下(示例):
//这里仅展示行写入代码
//对于大量数据输出,采用ExcelWriter容易引起内存溢出,此处使用BigExcelWriter
BigExcelWriter excelWriter = new BigExcelWriter();
//记录表头数据
List<String> headers = CollUtil.newArrayList();
//记录末行数据
List<Object> lastColumn = CollUtil.newArrayList();
//---标题---
excelWriter.merge(0, 0, 0, 3, "数据导出" + startingDate + "日到" + endDate + "日", true);
//---第一行---
headers.add("日期");
excelWriter.writeRow(headers);
//从第二行写入
excelWriter.setCurrentRow(1);
excelWriter.writeRow(row2);
lastColumn.add("合计");
excelWriter.writeRow(lastColumn);
//设置表头高度
excelWriter.setRowHeight(0, 25);
//Excel-将excel内容导出
try {
String fileName = URLEncoder.encode("统计" + startingDate + "日到" + endDate + "日" + ".xlsx", StandardCharsets.UTF_8.name());
response.setContentType("application/x-download");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
excelWriter.flush(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("文件写入失败!");
}
//关闭流
excelWriter.close();
一些样式设计:
// 设置样式
// 定义单元格背景色
StyleSet style = writer.getStyleSet();
CellStyle headCellStyle = style.getHeadCellStyle();
// 第二个参数表示是否也设置头部单元格背景
style.setBackgroundColor(IndexedColors.WHITE, true);
//设置内容字体
Font font = writer.createFont();
//设置字体
font.setFontName("宋体");
//加粗
font.setBold(true);
//设置标题字体大小
font.setFontHeightInPoints((short) 14);
headCellStyle.setFont(font);
writer.setStyleSet(style);
//设置表头高度
excelWriter.setRowHeight(0, 25);
//需要强转SXSSFSheet 不然没有trackAllColumnsForAutoSizing方法
SXSSFSheet sheet = (SXSSFSheet) excelWriter.getSheet();
//跟踪所有用于自动调整大小的列
sheet.trackAllColumnsForAutoSizing();
//设置所有列为自动宽度
excelWriter.autoSizeColumnAll();
每日鸡汤
懒又有目标,才是真的惨!