一、引入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.4</version> <!-- 版本号根据你的需求调整 -->
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.4</version> <!-- 版本号根据你的需求调整 -->
</dependency>
二、设置setDropDownListValidation方法
// 创建表头
String[] headers = {"客户名称", "调查时间", "评价项目", "得分结果", "评分理由", "与同行业企业相比较而言", "顾客的意见和建议"};
Row headerRow = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
headerRow.createCell(i).setCellValue(headers[i]);
}
private void setDropDownListValidation(Sheet sheet, String[] options, int columnIndex) {
int firstRow = 0; // 默认从第一行开始
int lastRow = sheet.getLastRowNum(); // 获取工作表中的最后一行索引
DataValidationHelper validationHelper = sheet.getDataValidationHelper();
CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, columnIndex, columnIndex);
DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(options);
DataValidation dataValidation = validationHelper.createValidation(constraint, addressList);
sheet.addValidationData(dataValidation);
}
三、实现
// 省略通过service查到List<GetExcelVOs> 数据
// 创建表头
String[] headers = {"姓名", "年龄", "手机号"};
Row headerRow = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
headerRow.createCell(i).setCellValue(headers[i]);
}
int rowNum = 1;
for (GetExcelVO item: GetExcelVOs) {
Row row = sheet.createRow(rowNum++);
// 假设模板对象中有需要的字段,这里用示例数据代替
row.createCell(0).setCellValue(item.getCustomerName());
row.createCell(1).setCellValue(item.getSurveyTime());
row.createCell(2).setCellValue(item.getEvaluationProject());
row.createCell(3).setCellValue(item.getScore());
}
// 设置下拉选项,假设从模板数据中提取需要的选项
if (!templateExcels.isEmpty()) {
setDropDownListValidation(sheet, new String[]{"较好", "一般", "较差"}, 5);
// 在第二列设置下拉选项
}
// 设置响应头
response.setContentType("application/vnd.openxmlformats- officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=template.xlsx");
// 将工作簿写入响应流
workbook.write(response.getOutputStream());
workbook.close();
引入的:
import org.apache.poi.xssf.usermodel.XSSFWorkbook;