参考文献:https://blog.csdn.net/wilson_m/article/details/79021458
1.pom.xml添加依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency>
2.数据表为Topic
3.创建后台ExcelController
@RestController
public class ExcelController {
@Resource
TopicService topicService;
@GetMapping("getExcel")
private void getExcel(HttpServletResponse response)throws IOException {
String fileName="新闻内容.xls";
response.setContentType("application/excel");
response.setHeader("Content-disposition","attachment;filename=" + fileName +";filename*=utf-8''"+ URLEncoder.encode(fileName,"UTF-8"));
// response.flushBuffer();
List<Topic> list=topicService.getTopicList(null);
HSSFWorkbook workbook=new HSSFWorkbook("新闻表");
HSSFSheet sheet=workbook.createSheet();
int rowNum=0;
//添加标题
String[] headers={"标题","版块","作者","创建时间","内容"};
HSSFRow row=sheet.createRow(rowNum);
for (int i =0; i <headers.length;i++){
HSSFCell cell=row.createCell(i);
HSSFRichTextString text=new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
//添加数据
for (Topic topic:list) {
rowNum++;
HSSFRow row1=sheet.createRow(rowNum);
row1.createCell(0).setCellValue(topic.getTitle());
row1.createCell(1).setCellValue(topic.getModuleName());
row1.createCell(2).setCellValue(topic.getUserName());
row1.createCell(3).setCellValue(topic.getCreateTimeS());
row1.createCell(4).setCellValue(topic.getContent());
}
workbook.write(response.getOutputStream());
}
}
4.运行效果
(浏览器:http://localhost:8088/getExcel)
5.小结
文件名出现乱码
将response.setHeader("Content-disposition","attachment;filename=" + fileName );
改为
response.setHeader("Content-disposition","attachment;filename=" + fileName +";filename*=utf-8''"+ URLEncoder.encode(fileName,"UTF-8"));
详情参考:https://blog.csdn.net/hgyu/article/details/80023150
1).设置内容类型
2).设置文件名称
3). 新建一个Excel文件 HSSFWorkbook workbook=new HSSFWorkbook();
4).新建一个工作簿 HSSFSheet sheet=workbook.createSheet();
//添加多个工作簿 HSSFSheet sheet=workbook.createSheet(“sheetName”);
5).新建一行 HSSFRow row=sheet.createRow(rowNum);
6).设置列中数据 row.createCell( index ).setCellValue( data );
7). emmm...... workbook.write(response.getOutputStream());