首先,产品有需求,我们苦逼的程序员就得把需求实现。那么今天咱就把产品提的导出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. Linux下设置目录或文件可读写,但不可以删除权限

    例如:现在/home目录下有 :目录 data 和 文件 test.txt (1)设置/home/test.txt可读写但是不可以删除命令(文件设置): sudo chattr +a /home/te ...

  2. [2002年NOIP普及组] 选数

    已知 n 个整数 x1,x2,-,xn,以及一个整数 k(k<n).从 n 个整数中任选 k 个整数相加,可分别得到一系列的和.例如当 n=4,k=3,4 个整数分别为 3,7,12,19 时, ...

  3. [SQL Server]储存过程中使用临时表循环操作数据

    本文为原创文章,转载请注明出处!我的博客地址:http://www.cnblogs.com/txwd 由于工作原因,到目前为此已有一年多没有写SQL Server的储存过程了,已有些生疏.日前工作中有 ...

  4. log4j2.xml配置全部正确,但是控制台不能输出错误日志

    如果配置文件,确定都没有问题,那么可能是Logger的包引入的不对: private static Logger logger = LogManager.getLogger(TrainControll ...

  5. 日志分析查看—— cat+grep+awk+uniq+sort+wc+join

    有个统计日志信息的需求,下面是使用到的命令 //按 \t 对文件每一行进行切割,正则匹配第二列为32896时,输出第一列:再进行排序并去重,最后统计行数 cat file.log|awk -F '\t ...

  6. 算法学习—————PAM回文自动机

    时隔一年,第一次学习新的算法 原理和AC自动机差不多 基本思想: 两棵树分别代表奇偶 在一个回文串两边同时填上相同字符可以得到另一个回文串,以此构建两棵树 树上维护信息: 节点表示的回文串为当前位置的 ...

  7. Java07 异常

    一.Error 和 Exception 1.什么是异常 实际工作中,遇到的情况不可能是非常完美的.比如:你写的某个模块,用户输入不一定符合你的要求.你的程序要打开某个文件,这个文件可能不存在或者文件格 ...

  8. python_test_5001_Moudle_pandas

    import pandas as pd import numpy as np from lib_001_decorator_log_funcname import decorator_log_func ...

  9. [部署日记]GO在Visual Studio Code初次运行时提示The "gopls" command is not available. Run "go get -v golang.org/x/tools/gopls" to install.

    本以为VSC在商城装上插件后就能拎包入住,F5的时候我当场好家伙 于是无脑Install... Installing github.com/nsf/gocode FAILED Installing g ...

  10. git 问题解决

    1. fatal: the remote end hung up unexpectedly git config --global http.postBuffer 104857600 其他方案: gi ...