首先,产品有需求,我们苦逼的程序员就得把需求实现。那么今天咱就把产品提的导出Excel的需求给他搞定。他的需求是这样的,很简单的Excel导出。样式如图所示:

其实我们项目中的ExcelUtils工具类不适应这种动态的问题和题干的导出。稍后我会吧此工具类的发放粘贴到文档中供大家参考和学习。那么项目中的不适应,我就自己手写最原始的进行导出,废话不多说开搞~

首先我们是从别的服务获取到数据,那么这个数据是个List集合。

代码如下

`@ApiOperation(value = "查看答卷数据--->导出功能")

@GetMapping("/{questionId}/export")

public void export(@PathVariable("questionId") String questionId, AnswerExportQueryModel queryModel, HttpServletResponse response) throws IOException {

  //aggregateResultDto  自定义的返回值  里面包含header头 和List<?> 泛型,在这里不做解释。

AggregateResultDto aggregateResultDto = questionnaireManager.exportAnswerById(questionId, queryModel);
List<AnswerListResource> list = (List<AnswerListResource>) aggregateResultDto.getList();
//获取到List集合中的数据,接下来咱们进行手写导出Excel。
//说明一下: 导出的Excel的格式有两种 一个是xlsx 一个是 xls。需要自己创建不同的WorkBook实现类,在这里我踩坑了望大家不要再次踩坑。
//1 正常导出xlsx格式 //创建工作薄的时候,用Workbook workbook = new XSSFWorkbook(); 这样可以正常导出xlsx格式 ` response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.addHeader("Content-Disposition", "attachment;filename=fileName" + ".xlsx");`
//2 正常导出xls格式 Workbook workbook = new HSSFWorkbook(); ` response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment;filename=fileName"+".xls");` //3 如果创建xlsx工作薄的时候,用 Workbook workbook = new HSSFWorkbook(); 生成的excel将无法打开,并有如下提示:
![](https://img2020.cnblogs.com/blog/2494928/202110/2494928-20211013164248296-1390307100.png) //创建HSSFWorkbook对象(excel的文档对象)
Workbook wb = new XSSFWorkbook();
//建立新的sheet对象(excel的表单)
Sheet sheet = wb.createSheet("问卷答案数据");
//在sheet里创建第1行 (标题)
Row rowTitle = sheet.createRow(0);
//创建单元格并设置单元格内容
rowTitle.createCell(0).setCellValue("大鹏号");
rowTitle.createCell(1).setCellValue("学管师");
rowTitle.createCell(2).setCellValue("联系方式");
rowTitle.createCell(3).setCellValue("用户昵称");
rowTitle.createCell(4).setCellValue("提交时间");
rowTitle.createCell(5).setCellValue("你的性别");
rowTitle.createCell(6).setCellValue("您的出生日期"); for (int i = 0; i < list.size(); i++) {
AnswerListResource answerListExportResource = list.get(i);
int rownum = i + 1;
//在sheet里创建数据行
Row rowData = sheet.createRow(rownum);
// 固定列
rowData.createCell(0).setCellValue(answerListExportResource.getDpAccount());
rowData.createCell(1).setCellValue(answerListExportResource.getTeacherName());
rowData.createCell(2).setCellValue(answerListExportResource.getLearnManagerStudentPhone());
rowData.createCell(3).setCellValue(answerListExportResource.getNickName());
rowData.createCell(4).setCellValue(answerListExportResource.getSubTime());
rowData.createCell(5).setCellValue(getSexType(answerListExportResource.getGender()));
rowData.createCell(6).setCellValue(answerListExportResource.getBirthday()); // 设置动态列
List<AnswerListResource.Question> questions = answerListExportResource.getQuestions();
Map<String, AnswerListResource.Question> questionMap = questions.stream().collect(Collectors.toMap(AnswerListResource.Question::getQuestion, Function.identity(), (key1, key2) -> key2));
questions.stream().forEach(question -> {
AnswerListResource.Question questionTemp = questionMap.get(question.getQuestion());
if (questionTemp.getQuestion().equals(question.getQuestion())) {
// 第一次循环时 创建出 列的标题(问卷的问题列)
if (rownum == 1) {
rowTitle.createCell(rowTitle.getLastCellNum()).setCellValue(question.getQuestion());
}
// 设置答案
rowData.createCell(rowData.getLastCellNum()).setCellValue(question.getAnswer());
}
});
}
// 下载
ExcelUtils.downLoadExcel("问卷答案导出",response,wb);

}`

附:ExcelUtils 代码

`public class ExcelUtils {

/**
* excel 导出
*
* @param list 数据
* @param title 标题
* @param sheetName sheet名称
* @param pojoClass pojo类型
* @param fileName 文件名称
* @param isCreateHeader 是否创建表头
* @param response
*/
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
boolean isCreateHeader, HttpServletResponse response) throws IOException {
ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF);
exportParams.setCreateHeadRows(isCreateHeader);
defaultExport(list, pojoClass, fileName, response, exportParams);
} /**
* excel 导出
*
* @param list 数据
* @param title 标题
* @param sheetName sheet名称
* @param pojoClass pojo类型
* @param fileName 文件名称
* @param response
*/
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName,
HttpServletResponse response) throws IOException {
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF));
} /**
* excel 导出
*
* @param list 数据
* @param pojoClass pojo类型
* @param fileName 文件名称
* @param response
* @param exportParams 导出参数
*/
public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, ExportParams exportParams,
HttpServletResponse response) throws IOException {
defaultExport(list, pojoClass, fileName, response, exportParams);
}
/**
* excel 导出
*
* @param list 数据
* @param pojoClass pojo类型
* @param fileName 文件名称
* @param response
*/
public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response) throws IOException {
defaultExport(list, pojoClass, fileName, response, new ExportParams());
} /**
* excel 导出
*
* @param list 数据
* @param fileName 文件名称
* @param response
*/
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response)
throws IOException {
defaultExport(list, fileName, response);
} /**
* 默认的 excel 导出
*
* @param list 数据
* @param pojoClass pojo类型
* @param fileName 文件名称
* @param response
* @param exportParams 导出参数
*/
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response,
ExportParams exportParams) throws IOException {
exportParams.setType(ExcelType.XSSF);
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
downLoadExcel(fileName, response, workbook);
} /**
* 默认的 excel 导出
*
* @param list 数据
* @param fileName 文件名称
* @param response
*/
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response)
throws IOException {
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
downLoadExcel(fileName, response, workbook);
} /**
* 下载
*
* @param fileName 文件名称
* @param response
* @param workbook excel数据
*/
public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook)
throws IOException {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename="
+ URLEncoder.encode(fileName + "." + ExcelTypeEnum.XLSX.getValue(), "UTF-8"));
workbook.write(response.getOutputStream());
} catch (Exception e) {
throw new IOException(e.getMessage());
}
} /**
* excel 导入
*
* @param filePath excel文件路径
* @param titleRows 标题行
* @param headerRows 表头行
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(String filePath, Integer titleRows, Integer headerRows, Class<T> pojoClass)
throws IOException {
if (StringUtils.isBlank(filePath)) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
params.setNeedSave(true);
params.setSaveUrl("/excel/");
try {
return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
} catch (NoSuchElementException e) {
throw new IOException("模板不能为空");
} catch (Exception e) {
throw new IOException(e.getMessage());
}
} /**
* excel 导入
*
* @param file excel文件
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass) throws IOException {
return importExcel(file, 1, 1, pojoClass);
} public static <T> List<T> importExcelNoTitle(MultipartFile file, Class<T> pojoClass) throws IOException {
return importExcel(file,0,1,pojoClass);
} /**
* excel 导入
*
* @param file excel文件
* @param titleRows 标题行
* @param headerRows 表头行
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)
throws IOException {
return importExcel(file, titleRows, headerRows, false, pojoClass);
} /**
* excel 导入
*
* @param file 上传的文件
* @param titleRows 标题行
* @param headerRows 表头行
* @param needVerfiy 是否检验excel内容
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, boolean needVerfiy,
Class<T> pojoClass) throws IOException {
if (file == null) {
return null;
}
try {
return importExcel(file.getInputStream(), titleRows, headerRows, needVerfiy, pojoClass);
} catch (Exception e) {
throw new BusinessException(e.getMessage());
}
} /**
* excel 导入
*
* @param inputStream 文件输入流
* @param titleRows 标题行
* @param headerRows 表头行
* @param needVerify 是否检验excel内容
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(InputStream inputStream, Integer titleRows, Integer headerRows,
boolean needVerify, Class<T> pojoClass) throws IOException {
if (inputStream == null) {
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
params.setSaveUrl("/excel/");
params.setNeedSave(true);
params.setNeedVerfiy(needVerify);
try {
return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
} catch (NoSuchElementException e) {
throw new IOException("excel文件不能为空");
} catch (Exception e) {
throw new IOException(e.getMessage());
}
} /**
* Excel 类型枚举
*/
enum ExcelTypeEnum {
XLS("xls"), XLSX("xlsx");
private String value; ExcelTypeEnum(String value) {
this.value = value;
} public String getValue() {
return value;
} public void setValue(String value) {
this.value = value;
}
}

}`

使用easypoi 最原始的代码进行导出Excel的更多相关文章

  1. RDLC - 后台代码直接导出Excel/PDF/Word格式

    最近做报表功能,用到了.net的报表组件rdlc. 其中有个功能就是后台代码直接输出Excel/PDF/Word格式的文件,网上看了些资源,做个总结: 参考地址 我直接贴出代码: //自动导出exce ...

  2. EasyOffice-.NetCore一行代码导入导出Excel,生成Word

    简介 Excel和Word操作在开发过程中经常需要使用,这类工作不涉及到核心业务,但又往往不可缺少.以往的开发方式在业务代码中直接引入NPOI.Aspose或者其他第三方库,工作繁琐,耗时多,扩展性差 ...

  3. Java代码导入导出 Excel 表格最简单的方法

    import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStrea ...

  4. asp.net 同时执行js事件和代码事件 导出 excel

     onclick="return bnQuery_onclick()" onserverclick="bnQuery_ServerClick"   public ...

  5. asp.net导出excel示例代码

    asp.net导出excel的简单方法. excel的操作,最常用的就是导出和导入. 本例使用NPOI实现. 代码:/// <summary> );             ;       ...

  6. ASP.NET MVC导出excel(数据量大,非常耗时的,异步导出)

    要在ASP.NET MVC站点上做excel导出功能,但是要导出的excel文件比较大,有几十M,所以导出比较费时,为了不影响对界面的其它操作,我就采用异步的方式,后台开辟一个线程将excel导出到指 ...

  7. 导出Excel和Excel生成dt

    引用ExcelLibrary.dll(qq网盘上有源代码) //导出excel,“”文件名为空时,弹出提示框 ExcelLibrary.DataSetHelper.CreateWorkbook(&qu ...

  8. PHP从数据库导出EXCEL文件

    参考博客链接:http://www.cnblogs.com/huangcong/p/3687665.html 我的程序代码 原生导出Excel文件 <?phpheader('Content-ty ...

  9. MVC学习笔记---MVC导出excel(数据量大,非常耗时的,异步导出)

    要在ASP.NET MVC站点上做excel导出功能,但是要导出的excel文件比较大,有几十M,所以导出比较费时,为了不影响对界面的其它操作,我就采用异步的方式,后台开辟一个线程将excel导出到指 ...

  10. ASP.NET MVC导出excel

    ASP.NET MVC导出excel 要在ASP.NET MVC站点上做excel导出功能,但是要导出的excel文件比较大,有几十M,所以导出比较费时,为了不影响对界面的其它操作,我就采用异步的方式 ...

随机推荐

  1. HCIA-基础实验FIN-综合网络部署考核

    HCIA-基础实验FIN-综合网络部署考核 虽然我选择通过自学hcia并跳过hcia培训直接学习hcip, 但是这个基础实验课程的考核总归还是处理掉比较好, 趁现在能挤出时间(笑). 1 实验需求 1 ...

  2. Python_基础_Print_转义字符和原字符

    转义字符和原字符 print('hello\nworld') #转义功能的首字母 n-->newline的首字母表示换行 print('hello\tworld') #\t即表示一个制表位 pr ...

  3. 「postOI」Colouring Game

    题意 有 \(n\) 个格子排成一行,一开始每个格子上涂了蓝色或红色. Alice 和 Bob 用这些格子做游戏.Alice 先手,两人轮流操作: Alice 操作时,选择两个相邻的格子,其中至少要有 ...

  4. 第二周集训队比赛wp

    Web1 直接截包改get为Host: Web2: 不一样的猪圈 普通的猪圈变种 NormalPwn 用IDA查看发现main下面有一个危险函数点进去发现/bin/sh 进main空格发现找cmman ...

  5. (一)用go实现单链表

    本篇,我们用go简单的实现单链表这种数据结构. 1.节点定义 type Node struct{ data int next *Node } 2.节点的添加 // 尾插法插入节点 func (p *N ...

  6. linux 的防火墙 ufw、firwalld、iptables 、

    防火墙综述 linux 防火墙,常用的包括三种:ufw . firewalld 和 iptables.学习难度依次递增. ufw 因为原生的 iptable 配置麻烦,学习成本较高. ufw全称 Un ...

  7. vue资料链接

    vue 官方api:https://cn.vuejs.org/ vue资源精选:http://vue.awesometiny.com/ vue GitHub地址:https://github.com/ ...

  8. axios响应拦截器无法显示响应头问题

    Access-Control-Expose-Headers 响应报头.跨域 公开响应头 问题现象: 前端无法获取响应头 Response Header 原因 问题原因:跨域问题 启用跨域请求(CORS ...

  9. windows 安装mysql-8.0.13(zip安装)

    安装环境说明 系统版本:windows10 mysql版本:mysql-8.0.13-winx64.zip 下载地址:http://mirrors.163.com/mysql/Downloads/My ...

  10. es 集群并设置密码

    1. 生成证书 bin/elasticsearch-certutil cert -out config/elastic-certificates.p12 -pass ""2. el ...