91名师指路-头部
91名师指路

easyexcel(二十一):导出excel自定义列宽

由于某些原因,现在不支持支付宝支付,如需要购买源码请加博主微信进行购买,微信号:13248254750

一:引入pom

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.3.1</version>
</dependency>


二:easyexcel导出excel自定义列宽

/**
* 功能:easyexcel导出excel自定义列宽
* 来源:https://91mszl.com
* @Author: zxb
* @Date: 2023-12-09 11:38:26
*/
@GetMapping("/download")
public void download(HttpServletResponse response) throws IOException {
String fileName = System.currentTimeMillis() + ".xlsx";
response.reset();
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
OutputStream os=response.getOutputStream();

List<UserInfo> dataList=new ArrayList<>();
UserInfo u1=new UserInfo();
u1.setName("张无忌");
u1.setAge(18);
u1.setAddress("上海市青浦区虹桥国际机场1号");

UserInfo u2=new UserInfo();
u2.setName("赵敏");
u2.setAge(20);
u2.setAddress("上海市黄浦区东方明珠大厦100号");

dataList.add(u1);
dataList.add(u2);

List<List<String>> headList=new ArrayList<>();
headList.add(Lists.newArrayList("姓名"));
headList.add(Lists.newArrayList("年龄"));
headList.add(Lists.newArrayList("地址"));

EasyExcel.write(os).head(headList).sheet("用户信息").registerWriteHandler(new CustomColumnWidth()).doWrite(dataList);
}


三:自定义列宽策略

package com.gaia.business.common.utils;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import java.util.List;

public class CustomColumnWidth extends AbstractColumnWidthStyleStrategy {

@Override
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
if (isHead && cell.getRowIndex() == 0) { // isHead=true表示为表头,如果表头只有1行这里设置为0
int columnWidth = cell.getStringCellValue().getBytes().length;
int cellIndex = cell.getColumnIndex();
switch (cellIndex) {
case 2:
columnWidth = 50;
break;
default:
columnWidth = 12;
break;
}

if (columnWidth > 255) {
columnWidth = 255;
}
writeSheetHolder.getSheet().setColumnWidth(cellIndex, columnWidth * 256);
}
}


}


四:最终效果





2023-12-09 19:16:35     阅读(511)

名师出品,必属精品    https://www.91mszl.com

联系博主    
用户登录遮罩层
x

账号登录

91名师指路-底部