java使用esayExcel

文章目录

导出

依赖

xml 复制代码
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>easyexcel</artifactId>
  <version>2.2.4</version>
</dependency>

后端代码

controller

java 复制代码
@RequestMapping("/exportDemo")
public void exportDemo(@RequestBody Map<String, String> params,
 HttpServletResponse response) {
  testService.exportDemo(params, response);
}

service

java 复制代码
public void exportDemo(Map<String, String> params,
 HttpServletResponse response) {
  List<Map<String, Object>> dataList = getDataList(params);
  try {
    response.reset();
    response.setHeader("Content-type", "application/octet-stream");
    response.setHeader("Content-Disposition", "attachment;filename=" +
        URLEncoder.encode("表名称-" +
         DateUtils.format(new Date(),
          "yyyyMMddHHmmss") + ".xls", "utf-8"));

    // 表内容样式
    WriteCellStyle writeCellStyleContent = new WriteCellStyle();
    //垂直居中,水平居中
    writeCellStyleContent .setVerticalAlignment(VerticalAlignment.CENTER);
    writeCellStyleContent .setHorizontalAlignment(HorizontalAlignment.CENTER);
    writeCellStyleContent .setBorderLeft(BorderStyle.THIN);
    writeCellStyleContent .setBorderTop(BorderStyle.THIN);
    writeCellStyleContent .setBorderRight(BorderStyle.THIN);
    writeCellStyleContent .setBorderBottom(BorderStyle.THIN);
    //设置 自动换行
    writeCellStyleContent .setWrapped(true);
    
    WriteFont writeFont = new WriteFont();
    writeFont.setFontHeightInPoints((short) 12);
    writeFont.setFontName("宋体");
    writeCellStyleContent.setWriteFont(writeFont);
    //表头样式
    WriteCellStyle writeCellStyleHead = new WriteCellStyle();
    writeFont = new WriteFont();
    writeFont.setFontHeightInPoints((short) 12);
    writeFont.setBold(true);
    writeFont.setFontName("宋体");
    writeCellStyleHead.setWriteFont(writeFont);

    ExcelWriter writer = EasyExcel.write(response.getOutputStream()).build();

    List<List<String>> head = new ArrayList<List<String>>() {{
      add(new ArrayList<String>() {{
        add("单位单位单位");
      }});
      add(new ArrayList<String>() {{
        add("语文");
        add("已");
      }});
      add(new ArrayList<String>() {{
        add("数学");
        add("未");
      }});
      add(new ArrayList<String>() {{
        add("时间");
      }});
    }};
    WriteSheet ajSheet1 = EasyExcel.writerSheet(0, "sheetName")
        .head(head)
        .registerWriteHandler(new ExcelWidthStyleStrategy())
        .registerWriteHandler(
          new HorizontalCellStyleStrategy(
            writeCellStyleHead,writeCellStyleContent
          )
         )
        .build();
    writer.write(getData(dataList), ajSheet1);

    writer.finish();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

单元格宽度配置类

java 复制代码
package com.utils;

import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelWidthStyleStrategy extends AbstractColumnWidthStyleStrategy {
    private Map<Integer, Map<Integer,Integer>> CACHE = new HashMap<>();

    @Override
    protected void setColumnWidth(WriteSheetHolder writeSheetHolder,
     List<CellData> list, Cell cell, Head head,
     Integer integer, Boolean aBoolean) {
        boolean needSetWidth = aBoolean || !CollectionUtils.isEmpty(list);
        int columnIndex = cell.getColumnIndex();
        if (needSetWidth) {
            Map<Integer, Integer> maxColumnWidthMap
             = CACHE.get(writeSheetHolder.getSheetNo());
            if (maxColumnWidthMap == null) {
                maxColumnWidthMap = new HashMap<>();
                CACHE.put(writeSheetHolder.getSheetNo(),maxColumnWidthMap);
            }
            Integer columnWidth = dataLength(list, cell, aBoolean);
            if (columnWidth >=0) {
                if (columnWidth > 150) {
                    columnWidth = 150;
                }
                Integer maxColumnWidth = maxColumnWidthMap.get(columnIndex);
                if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
                    maxColumnWidthMap.put(columnIndex,columnWidth);
                    writeSheetHolder
                    .getSheet()
                    .setColumnWidth(columnIndex,columnWidth * 500);
                }
            }
        }
    }
    
    private Integer dataLength (List<CellData> cellDataList,
      Cell cell,Boolean isHead) {
        if (isHead) {
            int bytesLength = cell.getStringCellValue()
            .getBytes().length;
            if (bytesLength < 10) {
                return bytesLength;
            } else {
                int stringLength = cell.getStringCellValue().length();
                Double v = (bytesLength + stringLength) * 0.5;
                return v.intValue();
            }
        } else {
            CellData cellData = cellDataList.get(0);
            CellDataTypeEnum type = cellData.getType();
            if (type == null) {
                return -1;
            } else {
                switch (type) {
                    case STRING:
                        int bytesLength = cellData.getStringValue()
                        .getBytes().length;
                        if (bytesLength < 10) {
                            return bytesLength;
                        } else {
                            int stringLength = cellData.getStringValue().length();
                            Double v = (bytesLength + stringLength) * 0.3;
                            return v.intValue();
                        }
                    case BOOLEAN:
                        return cellData.getBooleanValue()
                        .toString().getBytes().length;
                    case NUMBER:
                        return cellData.getNumberValue()
                        .toString().getBytes().length;
                    default:
                        return -1;
                }
            }
        }
    }
}

util

java 复制代码
private List<Map<String, Object>>
 getDataList(Map<String, String> params) {
  List<Map<String, Object>> reuslt = new ArrayList<>();
  Map<String, Object> map = new HashMap<>();
  map.put("dw","测试单位");
  map.put("y","10");
  map.put("w","800");
  map.put("sj","2023-07-01 12:12:00");
  reuslt.add(map);
  return reuslt;
}

private List<List<String>>
 getData(List<Map<String, Object>> dataList) {
  List<List<String>> result = new ArrayList<>();
  for (Map<String, Object> map : dataList) {
    List<String> list = new ArrayList<>();
    list.add(map.get("dw").toString());
    list.add(map.get("y").toString());
    list.add(map.get("w").toString());
    list.add(map.get("sj").toString());
    result.add(list);
  }
  return result;
}

前端代码

javascript 复制代码
exportXlsx () {
  this.$axios({
  method: 'post',
  url: '/test/exportDemo',
  responseType: 'blob',
  data: {
    ...this.params
  }
  }).then(response => {
  let filename = response.headers['content-disposition']
  const blob = new Blob([response.data])
  var downloadElement = document.createElement('a')
  var href = window.URL.createObjectURL(blob)
  downloadElement.href = href
  downloadElement.download = decodeURIComponent(filename.split('filename=')[1])
  document.body.appendChild(downloadElement)
  downloadElement.click()
  document.body.removeChild(downloadElement)
  window.URL.revokeObjectURL(href)
  }).catch(reject => {})
}
相关推荐
程序猿麦小七3 分钟前
基于springboot的景区网页设计与实现
java·spring boot·后端·旅游·景区
敲敲敲-敲代码4 分钟前
游戏设计:推箱子【easyx图形界面/c语言】
c语言·开发语言·游戏
weisian1519 分钟前
认证鉴权框架SpringSecurity-2--重点组件和过滤器链篇
java·安全
蓝田~11 分钟前
SpringBoot-自定义注解,拦截器
java·spring boot·后端
ROC_bird..12 分钟前
STL - vector的使用和模拟实现
开发语言·c++
.生产的驴13 分钟前
SpringCloud Gateway网关路由配置 接口统一 登录验证 权限校验 路由属性
java·spring boot·后端·spring·spring cloud·gateway·rabbitmq
MavenTalk18 分钟前
Move开发语言在区块链的开发与应用
开发语言·python·rust·区块链·solidity·move
v'sir27 分钟前
POI word转pdf乱码问题处理
java·spring boot·后端·pdf·word
提高记忆力35 分钟前
SpringBoot整合FreeMarker生成word表格文件
java·spring
JDS_DIJ36 分钟前
RabbitMQ
java·rabbitmq·java-rabbitmq