基础类描述
- ExcelWriter(导出工具类)
- Query(通用查询)
- Consumer(函数参数)
- SpringBeanUtil(获取bean)
代码
ExcelWriter
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.util.ListUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.itxl.common.utils.SpringBeanUtil;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
public class ExcelWriter <T>{
private HttpServletResponse response;
private ServletOutputStream outputStream;
private boolean memory = false;
private boolean multiThread = false;
private String fileName = "file";
private Workbook workbook = new SXSSFWorkbook();
private String curSheetName = "sheet";
private static final String CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
private static final String ENCODE = "UTF-8";
private AtomicInteger curRowIndex;
private Integer total;
private Integer sheetNo = 1;
private static final Integer sheetMaxNum = 1000000;
private List<List<Integer>> widths;
private List<List<Integer>> heights;
private List<List<Integer>> cellStyleIndex;
private List<CellStyle> cellStyles;
private Integer defaultColumnWidth = 20;
private Integer defaultRowHeight = 20;
private List<List<Integer>> cellValueIndex;
private List<String> cellValues;
private List<List<Integer>> mergeInfo;
private List<List<Integer>> dropDownBoxIndex;
private List<List<String>> dropDownBoxDatas;
private List<List<Integer>> chartAnchor;
private List<byte[]> chartBytes;
public ExcelWriter(HttpServletResponse response) {
this.response = response;
}
public ExcelWriter<T> memory(){
workbook = new XSSFWorkbook();
return this;
}
public ExcelWriter<T> setFileName(String fileName){
this.fileName = fileName;
return this;
}
public ExcelWriter<T> initResponse() throws IOException {
response.setContentType(CONTENT_TYPE);
response.setCharacterEncoding(ENCODE);
fileName = URLEncoder.encode(fileName, ENCODE).replaceAll("\\+", "%20");
response.setHeader("fileName",fileName+".xlsx");
this.outputStream = response.getOutputStream();
return this;
}
public ExcelWriter<T> paging(Integer total){
this.total = total;
return this;
}
public ExcelWriter<T> multiThread(Integer total){
this.multiThread = true;
return paging(total);
}
public ExcelWriter<T> setHead(List<String> heads,Integer rowIndex, Integer colIndex){
for (int i = 0; i < heads.size(); i++) {
setCell(heads.get(i),rowIndex,colIndex+i).setHeadStyle(rowIndex,colIndex+i);
}
return this;
}
public ExcelWriter<T> setCell(String value,Integer rowIndex,Integer colIndex){
if (CollUtil.isEmpty(cellValues)){
cellValues = new ArrayList<>();
}
if (CollUtil.isEmpty(cellValueIndex)){
cellValueIndex = new ArrayList<>();
}
cellValues.add(value);
cellValueIndex.add(ListUtils.newArrayList(rowIndex,colIndex));
return this;
}
private ExcelWriter<T> doSetCell(String value,Integer rowIndex,Integer colIndex){
Sheet sheet = getSheet();
Row row = getRow(sheet,rowIndex);
Cell cell = getCell(row, colIndex);
cell.setCellValue(value);
return this;
}
public Sheet getSheet(){
Sheet sheet = workbook.getSheet(curSheetName + sheetNo);
if (sheet == null){
sheet = workbook.createSheet(curSheetName + sheetNo);
}
return sheet;
}
public ExcelWriter<T> setCurSheetName(String sheetName){
this.curSheetName = sheetName;
return this;
}
private Row getRow(Sheet sheet,Integer rowIndex){
Row row = sheet.getRow(rowIndex);
if (row == null){
row = sheet.createRow(rowIndex);
}
return row;
}
private Cell getCell(Row row,Integer colIndex){
Cell cell = row.getCell(colIndex);
if (cell == null){
cell = row.getCell(colIndex);
}
return cell;
}
public CellStyle getBlankCellStyle(){
return workbook.createCellStyle();
}
public ExcelWriter<T> setCellStyle(Integer rowIndex, Integer colIndex, CellStyle cellStyle){
if (CollUtil.isEmpty(cellStyleIndex)){
cellStyleIndex = new ArrayList<>();
}
if (CollUtil.isEmpty(cellStyles)){
cellStyles = new ArrayList<>();
}
cellStyleIndex.add(ListUtils.newArrayList(rowIndex,colIndex));
cellStyles.add(cellStyle);
return this;
}
private ExcelWriter<T> setHeadStyle(Integer rowIndex, Integer colIndex){
CellStyle cellStyle = getBlankCellStyle();
return setCellStyle(rowIndex,colIndex,cellStyle);
}
public ExcelWriter<T> setColumnWidth(Integer col,Integer width){
if (CollUtil.isEmpty(widths)){
widths = new ArrayList<>();
}
widths.add(ListUtils.newArrayList(col,width));
return this;
}
public ExcelWriter<T> setColumnWidth(List<List<Integer>> cols){
if (CollUtil.isEmpty(widths)){
widths = new ArrayList<>();
}
widths.addAll(cols);
return this;
}
public ExcelWriter<T> setRowHeight(List<List<Integer>> rows){
if (CollUtil.isEmpty(heights)){
heights = new ArrayList<>();
}
heights.addAll(rows);
return this;
}
public ExcelWriter<T> setRowHeightAndColumnWidth(List<List<Integer>> axisInfo){
for (List<Integer> axis : axisInfo) {
setRowHeightAndColumnWidth(axis.get(0),axis.get(1),axis.get(2),axis.get(3));
}
return this;
}
public ExcelWriter setRowHeightAndColumnWidth(Integer row,Integer rowHeight,Integer col,Integer colWidth){
return setRowHeight(row, rowHeight).setColumnWidth(col, colWidth);
}
public ExcelWriter<T> setDefaultRowHeight(Integer height){
this.defaultRowHeight = height;
return this;
}
public ExcelWriter<T> setDefaultColumnWidth(Integer width){
this.defaultColumnWidth = width;
return this;
}
public ExcelWriter<T> setDefaultRowHeightAndColumnWidth(Integer height,Integer width){
return setDefaultColumnWidth(width).setDefaultRowHeight(height);
}
public ExcelWriter<T> setRowHeight(Integer rowIndex,Integer height){
heights.add(ListUtils.newArrayList(rowIndex,height));
return this;
}
public ExcelWriter<T> write(Query<List<List<String>>> query,Integer row,Integer col) throws IOException, ExecutionException, InterruptedException {
if (curRowIndex == null){
curRowIndex = new AtomicInteger(row);
}
if (total == null){
write(query.accept(),curRowIndex.get(),col);
return this;
}
int totalPage = PageUtil.totalPage(total, query.getPageSize());
AtomicInteger pageNum = new AtomicInteger(0);
if (!multiThread){
write(query, curRowIndex.get(), col, pageNum,totalPage);
return this;
}
ThreadPoolExecutor poolExecutor = SpringBeanUtil.getBean(ThreadPoolExecutor.class);
List<Future<?>> futures = new ArrayList<>();
for (int i = 0; i < 4; i++) {
Future<?> future =poolExecutor.submit(() -> {
write(query, curRowIndex.get(), col, pageNum,totalPage);
});
futures.add(future);
}
for (Future<?> future : futures) {
future.get();
}
return this;
}
public void write(List<List<String>> data, Integer row, Integer col) throws IOException {
if (curRowIndex == null) {
curRowIndex = new AtomicInteger(row);
}
if (curRowIndex.get() + data.size() > sheetMaxNum){
List<List<String>> left = ListUtil.sub(data, 0, sheetMaxNum - curRowIndex.get());
doWrite(left,curRowIndex.get(), col);
data = ListUtil.sub(data, sheetMaxNum - curRowIndex.get(), data.size());
curRowIndex.set(0);
sheetNo++;
}
doWrite(data,curRowIndex.get(), col);
}
private void write(Query<List<List<String>>> query, Integer row, Integer col, AtomicInteger pageNum,int totalPage) {
while (pageNum.get() < totalPage){
query.setPageNum(pageNum.incrementAndGet());
List<List<String>> accept = query.accept();
try {
write(accept, row+(pageNum.get()-1)*query.getPageSize(), col);
} catch (IOException e) {
throw new RuntimeException(e);
}
query.removePage();
}
}
public ExcelWriter<T> write() throws IOException {
workbook.write(outputStream);
return this;
}
private void doWrite(List<List<String>> data, Integer row, Integer col) throws IOException {
synchronized (outputStream){
for (int i = 0; i < data.size(); i++) {
for (int j = 0; j < data.get(i).size(); j++) {
doSetCell(data.get(i).get(j),row+i,col+j);
}
}
curRowIndex.set(row+data.size());
write();
}
}
private List<List<String>> parseData(List<T> datas,List<String> fields){
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
List<List<String>> res = new ArrayList<>(datas.size());
for (T data : datas) {
JSONObject json = JSONUtil.parseObj(data);
List<String> objects = new ArrayList<>(fields.size());
for (String field : fields) {
Object o = json.get(field);
if (o == null){
o = "";
}else if (o instanceof Date){
o = format.format(o);
}else{
o = o.toString();
}
objects.add(o.toString());
}
res.add(objects);
}
return res;
}
public ExcelWriter<T> builder(){
Sheet sheet = getSheet();
sheet.setDefaultColumnWidth(defaultColumnWidth * 256);
sheet.setDefaultRowHeight(defaultRowHeight.shortValue());
if (widths != null){
for (List<Integer> width : widths) {
sheet.setColumnWidth(width.get(0),width.get(1));
}
}
if (heights != null){
for (List<Integer> height : heights) {
Row row = getRow(sheet, height.get(0));
row.setHeight(height.get(1).shortValue());
}
}
if (cellStyleIndex != null){
for (int i = 0; i < cellStyleIndex.size(); i++) {
List<Integer> index = cellStyleIndex.get(i);
CellStyle cellStyle = cellStyles.get(i);
Cell cell = getCell(getRow(sheet, index.get(0)), index.get(1));
cell.setCellStyle(cellStyle);
}
}
if (cellValueIndex != null){
for (int i = 0; i < cellValueIndex.size(); i++) {
List<Integer> index = cellValueIndex.get(i);
String value = cellValues.get(i);
doSetCell(value,index.get(0),index.get(1));
}
}
if (mergeInfo != null){
for (List<Integer> merge : mergeInfo) {
doMerge(merge.get(0),merge.get(1),merge.get(2),merge.get(3));
}
}
if (dropDownBoxDatas != null){
for (int i = 0; i < dropDownBoxIndex.size(); i++) {
List<Integer> index = dropDownBoxIndex.get(i);
List<String> data = dropDownBoxDatas.get(i);
doSetDropDownBox(data,index.get(0),index.get(1),index.get(2),index.get(3));
}
}
if (chartAnchor != null){
for (int i = 0; i < chartAnchor.size(); i++) {
List<Integer> anchorIndex = chartAnchor.get(i);
byte[] bytes = chartBytes.get(i);
Drawing<?> drawing =sheet.createDrawingPatriarch();
ClientAnchor anchor = drawing.createAnchor(anchorIndex.get(0), anchorIndex.get(1), anchorIndex.get(2), anchorIndex.get(3), anchorIndex.get(4),
anchorIndex.get(5), anchorIndex.get(6), anchorIndex.get(7));
int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
drawing.createPicture(anchor, pictureIdx);
}
}
return this;
}
public ExcelWriter<T> setChart(byte[] bytes,int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2){
if (chartAnchor == null){
chartAnchor = new ArrayList<>();
}
if (chartBytes == null){
chartBytes = new ArrayList<>();
}
chartBytes.add(bytes);
chartAnchor.add(ListUtils.newArrayList(dx1,dy1,dx2,dy2,col1,row1,col2,row2));
return this;
}
private void doMerge(Integer firstRow, Integer lastRow, Integer firstCol, Integer lastCol){
CellRangeAddress address = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
getSheet().addMergedRegion(address);
}
public ExcelWriter<T> merge(Integer firstRow, Integer lastRow, Integer firstCol, Integer lastCol){
if (mergeInfo == null){
mergeInfo = new ArrayList<>();
}
mergeInfo.add(ListUtils.newArrayList(firstRow,lastRow,firstCol,lastCol));
return this;
}
public ExcelWriter<T> merge(List<List<Integer>> mergeInfo){
if (this.mergeInfo == null){
this.mergeInfo = new ArrayList<>();
}
this.mergeInfo.addAll(mergeInfo);
return this;
}
;
public ExcelWriter<T> setDropDownBox(List<String> data,Integer firstRow, Integer lastRow, Integer firstCol, Integer lastCol){
if (dropDownBoxIndex == null){
dropDownBoxIndex = new ArrayList<>();
}
if (dropDownBoxDatas == null){
dropDownBoxDatas = new ArrayList<>();
}
dropDownBoxIndex.add(ListUtils.newArrayList(firstRow,lastRow,firstCol,lastCol));
dropDownBoxDatas.add(data);
return this;
}
public void doSetDropDownBox(List<String> data,Integer firstRow, Integer lastRow, Integer firstCol, Integer lastCol){
Sheet sheet = getSheet();
DataValidationHelper validationHelper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(data.toArray(new String[0]));
CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
DataValidation validation = validationHelper.createValidation(constraint, addressList);
validation.setShowErrorBox(true);
validation.createErrorBox("错误", "您必须选择下拉列表中的选项之一。");
sheet.addValidationData(validation);
}
}
Query
import org.itxl.common.utils.Consumer;
public abstract class Query<T> implements Consumer<T> {
private final ThreadLocal<Integer> local = new ThreadLocal<>();
private Integer pageSize = 10000;
public void setPageNum(Integer pageNum){
local.set(pageNum);
}
public Integer getPageNum(){
return local.get();
}
public void removePage(){
local.remove();
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
if (pageSize == null){
return;
}
this.pageSize = pageSize;
}
@Override
public T accept() {
return andThen();
}
}
Consumer
public interface Consumer<T>{
T andThen();
T accept();
}
SpringBeanUtil
package org.itxl.common.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringBeanUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
public static <T> T getBean(String beanName, Class<T> clazz) {
return applicationContext.getBean(beanName, clazz);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringBeanUtil.applicationContext == null){
SpringBeanUtil.applicationContext = applicationContext;
}
}
}
关于导出工具类ExcelWriter对于图表的的导出方法的使用
- 通过JFreeChart绘制图片,转为byte数据调用方法使用
1.1 JFreeChart使用请查看Java绘图库JFreeChart的详细使用教程(入门级)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类