依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
代码:
工具类组件:
@Component
public class ExcelUtil {
public static void executeExcel() throws IOException {
List<String> titleList = new ArrayList<>();
titleList.add("语文");
titleList.add("数学");
titleList.add("英语");
titleList.add("政治");
titleList.add("历史");
titleList.add("地理");
titleList.add("物理");
titleList.add("通用技术");
List<String> classList = new ArrayList<>();
classList.add("赵杰");
classList.add("王武振");
classList.add("赵思睿");
classList.add("李薇薇");
classList.add("李杰");
classList.add("李诺");
classList.add("裴德云");
classList.add("张善若");
classList.add("张雯雯");
classList.add("张忠明");
//工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("本班学生成绩表");
sheet.setDefaultColumnWidth(titleList.size());
//表头
HSSFRow headRow = sheet.createRow(0);
headRow.setHeight((short) 450);
HSSFCell tempCell = headRow.createCell(0);
HSSFRichTextString tempText = new HSSFRichTextString("姓名");
tempCell.setCellValue(tempText);
for (int i = 0; i < (titleList.size()); i++) {
String title = titleList.get(i);
//创建单元格
HSSFCell cell = headRow.createCell(i + 1);
//创建内容对象
HSSFRichTextString text = new HSSFRichTextString(title);
//将内容对象的文字内容写入到单元格中
cell.setCellValue(text);
}
for (int i = 0; i < classList.size(); i++) {
HSSFRow row = sheet.createRow(i + 1);
for (int j = 0; j < (titleList.size() + 1); j++) {
// Write into cell title.
if(j == 0){
String s = classList.get(i);
HSSFCell cell = row.createCell(j);
HSSFRichTextString text = new HSSFRichTextString(s);
cell.setCellValue(text);
} else {
// Write into cell content.
Random randomNumber = new Random();
String s = String.valueOf(randomNumber.nextInt(100));
HSSFCell cell = row.createCell(j);
HSSFRichTextString text = new HSSFRichTextString(s);
cell.setCellValue(text);
}
}
}
//获取response
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
//八进制输出流
response.setContentType("application/octet-stream");
//这后面可以设置导出Excel的名称,此例中名为student.xls
response.setHeader("Content-Disposition", "attachment;filename=student.xls");
//刷新缓冲
response.flushBuffer();
//workbook将Excel写入到response的输出流中,供页面下载
workbook.write(response.getOutputStream());
}
}
Controller层:
直接写即可。需要指出的是,如果是以GET请求发出文件会通过浏览器自动下载。
@RestController
public class ExcelController {
@Resource
private ExcelUtil excelUtil;
@RequestMapping(value = "/ef/bro")
public void excelController() throws IOException {
excelUtil.executeExcel();
}
}