Java使用EasyExcel動(dòng)態(tài)添加自增序號(hào)列
前言
本文將介紹如何通過使用EasyExcel自定義攔截器實(shí)現(xiàn)在最終的Excel文件中新增一列自增的序號(hào)列,最終的效果如下:

此外,本文所使用的完整代碼示例已上傳到GitHub。
實(shí)現(xiàn)
本文主要是通過自定義一個(gè)繼承AbstractRowWriteHandler的攔截器來實(shí)現(xiàn)在最終導(dǎo)出的結(jié)果中新增序號(hào)列,通過修改源碼中保存頭部標(biāo)題的Map內(nèi)容來給自己添加的序號(hào)列留出位置,先展示最終的代碼:
/**
* 自定義 excel 行處理器, 增加序號(hào)列
*
* @author butterfly
* @date 2020-09-05
*/
@Component
public class AddNoHandler extends AbstractRowWriteHandler {
private boolean init = true;
@Override
public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
Integer rowIndex, Integer relativeRowIndex, Boolean isHead) {
if (init) {
// 修改存儲(chǔ)頭部及對(duì)應(yīng)字段信息的 map, 將其中的內(nèi)容均右移一位, 給新增的序列號(hào)預(yù)留為第一列
ExcelWriteHeadProperty excelWriteHeadProperty = writeSheetHolder.excelWriteHeadProperty();
Map<Integer, Head> headMap = excelWriteHeadProperty.getHeadMap();
Map<Integer, ExcelContentProperty> contentMap = excelWriteHeadProperty.getContentPropertyMap();
int size = headMap.size();
for (int current = size; current > 0; current--) {
int previous = current - 1;
headMap.put(current, headMap.get(previous));
contentMap.put(current, contentMap.get(previous));
}
// 空出第一列
headMap.remove(0);
contentMap.remove(0);
// 只需要修改一次 map 即可, 故使用 init 變量進(jìn)行控制
init = false;
}
}
@Override
public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Integer relativeRowIndex, Boolean isHead) {
// 在行創(chuàng)建完成后添加序號(hào)列
Cell cell = row.createCell(0);
int rowNum = row.getRowNum();
if (rowNum == 0) {
cell.setCellValue(ExcelConstant.TITLE);
} else {
cell.setCellValue(rowNum);
}
}
@Override
public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Integer relativeRowIndex, Boolean isHead) {
if (row.getLastCellNum() > 1) {
// 將自定義新增的序號(hào)列的樣式設(shè)置與默認(rèn)的樣式一致
row.getCell(0).setCellStyle(row.getCell(1).getCellStyle());
}
}
}
afterRowCreate和afterRowDispose方法中的內(nèi)容很好理解,一個(gè)用于控制控制新增序號(hào)列的內(nèi)容,一個(gè)用于控制新增列的樣式。而beforeRowCreate中的內(nèi)容則稍微復(fù)雜,主要用于給新增的序號(hào)列空出位置。同時(shí),由于beforeRowCreate會(huì)在每次創(chuàng)建行時(shí)均會(huì)被調(diào)用,但是原始的存儲(chǔ)頭部信息的Map只需要修改一次,因此這里通過使用init變量控制只會(huì)修改一次。
思路
通過查看com.alibaba.excel.write.executor.ExcelWriteAddExecutor類中的addOneRowOfDataToExcel方法源碼,可以看到在新增行的前后會(huì)分別調(diào)用beforeRowCreate和afterRowCreate方法,并且在一行數(shù)據(jù)添加完成后會(huì)調(diào)用afterRowDispose,這也是上述攔截器生效的原理,源碼如下:
private void addOneRowOfDataToExcel(Object oneRowData, int n, int relativeRowIndex,
Map<Integer, Field> sortedAllFiledMap) {
// 行數(shù)據(jù)為空, 直接返回
if (oneRowData == null) {
return;
}
// 創(chuàng)建數(shù)據(jù)行對(duì)象, 同時(shí)分別在創(chuàng)建行前后調(diào)用攔截器
WriteHandlerUtils.beforeRowCreate(writeContext, n, relativeRowIndex, Boolean.FALSE);
Row row = WorkBookUtil.createRow(writeContext.writeSheetHolder().getSheet(), n);
WriteHandlerUtils.afterRowCreate(writeContext, row, relativeRowIndex, Boolean.FALSE);
// 將實(shí)體數(shù)據(jù)內(nèi)容填充到行中
if (oneRowData instanceof List) {
addBasicTypeToExcel((List) oneRowData, row, relativeRowIndex);
} else {
// 下面會(huì)繼續(xù)查看這個(gè)方法
addJavaObjectToExcel(oneRowData, row, relativeRowIndex, sortedAllFiledMap);
}
// 行創(chuàng)建完成后, 調(diào)用相應(yīng)攔截器
WriteHandlerUtils.afterRowDispose(writeContext, row, relativeRowIndex, Boolean.FALSE);
}
而之所以我們修改headMap和contentMap的內(nèi)容就可以實(shí)現(xiàn)最終效果,只需要繼續(xù)查看該類中addJavaObjectToExcel方法的代碼即可知道原因:
private void addJavaObjectToExcel(Object oneRowData, Row row, int relativeRowIndex,
Map<Integer, Field> sortedAllFiledMap) {
WriteHolder currentWriteHolder = writeContext.currentWriteHolder();
// 將自己的實(shí)體數(shù)據(jù)映射到 beanMap
BeanMap beanMap = BeanMap.create(oneRowData);
Set<String> beanMapHandledSet = new HashSet<String>();
int cellIndex = 0;
// If it's a class it needs to be cast by type
if (HeadKindEnum.CLASS.equals(writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadKind())) {
// 我們修改的就是這里的 headMap 和 contentPropertyMap 內(nèi)容
Map<Integer, Head> headMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadMap();
Map<Integer, ExcelContentProperty> contentPropertyMap =
writeContext.currentWriteHolder().excelWriteHeadProperty().getContentPropertyMap();
// 遍歷所有的列頭, 插入數(shù)據(jù)
for (Map.Entry<Integer, ExcelContentProperty> entry : contentPropertyMap.entrySet()) {
// 獲取 cell 的下標(biāo), 后續(xù)將內(nèi)容插入指定的列
cellIndex = entry.getKey();
ExcelContentProperty excelContentProperty = entry.getValue();
String name = excelContentProperty.getField().getName();
if (!beanMap.containsKey(name)) {
continue;
}
// 控制單元格的內(nèi)容
Head head = headMap.get(cellIndex);
WriteHandlerUtils.beforeCellCreate(writeContext, row, head, cellIndex,
relativeRowIndex, Boolean.FALSE);
Cell cell = WorkBookUtil.createCell(row, cellIndex);
WriteHandlerUtils.afterCellCreate(writeContext, cell, head, relativeRowIndex, Boolean.FALSE);
Object value = beanMap.get(name);
CellData cellData = converterAndSet(currentWriteHolder, excelContentProperty.getField().getType(),
cell, value, excelContentProperty, head, relativeRowIndex);
WriteHandlerUtils.afterCellDispose(writeContext, cellData, cell, head,
relativeRowIndex, Boolean.FALSE);
beanMapHandledSet.add(name);
}
}
// 省略了后面無關(guān)的內(nèi)容
}
其它
通過以上自定義的攔截器,就可以寫一個(gè)簡(jiǎn)單的demo進(jìn)行測(cè)試:
/**
* Excel 下載控制器
*
* @author butterfly
* @date 2021-09-05
*/
@RestController
public class ExcelController {
/**
* 添加序號(hào)列測(cè)試
*
* @param response response
*/
@GetMapping("/col")
public void col(HttpServletResponse response) {
try {
List<Student> students = getStudentList();
EasyExcel.write(response.getOutputStream(), Student.class)
.registerWriteHandler(new AddNoHandler())
.sheet()
.doWrite(students);
} catch (Exception e) {
System.out.println(ExcelConstant.DOWNLOAD_FAILED);
}
}
/**
* 生成學(xué)生列表
*
* @return 學(xué)生列表
*/
private List<Student> getStudentList() {
return Arrays.asList(
new Student("2021090101", "張三", 19),
new Student("2021090102", "李四", 18),
new Student("2021090103", "王二", 20)
);
}
}
然后是前端的測(cè)試代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件下載測(cè)試</title>
<script src="https://cdn.staticfile.org/axios/0.21.2/axios.min.js"></script>
</head>
<body>
<button onclick="col()">添加序號(hào)列測(cè)試</button>
<script>
function col() {
download('http://localhost:8080/col', 'col.xlsx')
}
function download(url, name) {
axios({
url: url,
responseType: 'blob'
}).then((response) => {
const URL = window.URL.createObjectURL(response.data)
const tempLink = document.createElement('a')
tempLink.style.display = 'none'
tempLink.href = URL
tempLink.setAttribute('download', name)
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank')
}
document.body.appendChild(tempLink)
tempLink.click()
document.body.removeChild(tempLink)
window.URL.revokeObjectURL(URL)
})
}
</script>
</body>
</html>

總結(jié)
以上便是實(shí)現(xiàn)動(dòng)態(tài)添加自增序號(hào)列的一種思路,除此之外還可以通過在實(shí)體中添加序號(hào)這一個(gè)字段,然后修改列表的數(shù)據(jù),或者只需要在afterRowCreate中設(shè)置序號(hào)數(shù)據(jù)即可,而不需要再修改頭部Map的數(shù)據(jù)。還有一種通過自定義模板,然后通過填充模板來實(shí)現(xiàn)同樣的效果,可以參考https://www.yuque.com/easyexcel/doc/fill,但是這兩種方法都需要對(duì)原有數(shù)據(jù)有所修改,或者需要增加定義模板的操作,這里不再介紹。
到此這篇關(guān)于Java使用EasyExcel動(dòng)態(tài)添加自增序號(hào)列的文章就介紹到這了,更多相關(guān)Java EasyExcel動(dòng)態(tài)添加自增序號(hào)列內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解java之redis篇(spring-data-redis整合)
本篇文章主要介紹了java之redis篇,主要詳細(xì)的介紹了spring-data-redis整合,有興趣的可以了解一下。2017-01-01
Apache?Commons?Imaging處理圖像實(shí)例深究
這篇文章主要為大家介紹了Apache?Commons?Imaging處理圖像的實(shí)例探索深究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
Java中mkdir()和mkdirs()的區(qū)別及說明
這篇文章主要介紹了Java中mkdir()和mkdirs()的區(qū)別及說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11
java.util.NoSuchElementException原因及兩種解決方法
本文主要介紹了java.util.NoSuchElementException原因及兩種解決方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
Java BigDecimal和double示例及相關(guān)問題解析
這篇文章主要介紹了Java BigDecimal和double示例及相關(guān)問題解析,簡(jiǎn)單介紹了BigDecimal類的相關(guān)內(nèi)容,分享了兩則相關(guān)實(shí)例,對(duì)問題進(jìn)行了分析,具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11
Struts2 通過ognl表達(dá)式實(shí)現(xiàn)投影
這篇文章主要介紹了Struts2 通過ognl表達(dá)式實(shí)現(xiàn)投影,具有一定參考價(jià)值,需要的朋友可以了解下。2017-09-09

