前言
项目中需要在导出的模板中新增三级联动的功能,类似省市区的联动。在网上找了一些方法,都不能直接使用,需要进行修改。本文主要分享一下,改后的代码,可以直接使用。
代码
public class CascadeWriteHandler implements SheetWriteHandler {
private static char[] alphabet = new char[]{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
//省
private List<String> provinceList;
//市
Map<String, List<String>> cityMap;
//区
Map<String, List<String>> areaMap;
//省列位置
private int provinceIndex;
//市列位置
private intcityIndex;
//区列位置
private int areaIndex;
public CascadeWriteHandler(List<String> provinceList, Map<String, List<String>> cityMap, Map<String, List<String>> areaMap, int provinceIndex, int intcityIndex, int areaIndex) {
this.provinceList= provinceList;
this.cityMap= cityMap;
this.areaMap= areaMap;
this.provinceIndex= provinceIndex;
this.intcityIndex= intcityIndex;
this.areaIndex= areaIndex;
}
@Override
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
//获取工作簿
Sheet sheet = writeSheetHolder.getSheet();
Workbook book = writeWorkbookHolder.getWorkbook();
//创建一个专门用来存放地区信息的隐藏sheet页
//因此不能在现实页之前创建,否则无法隐藏。
Sheet hideSheet = book.createSheet("site");
book.setSheetHidden(book.getSheetIndex(hideSheet), true);
// 将具体的数据写入到每一行中,行开头为父级区域,后面是子区域。
int rowId = 0;
Row proviRow = hideSheet.createRow(rowId++);
proviRow.createCell(0).setCellValue("大类列表");
for (int i = 0; i < provinceIndex.size(); i++) {
Cell proviCell = proviRow.createCell(i + 1);
proviCell.setCellValue(provinceIndex.get(i));
}
Iterator<String> keyIterator = cityMap.keySet().iterator();
while (keyIterator.hasNext()