參考文獻: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.數(shù)據(jù)表為Topic
3.創(chuàng)建后臺ExcelController
@RestController
public class ExcelController {
@Resource
? ? TopicService topicService;
@GetMapping("getExcel")
private void getExcel(HttpServletResponse response)throws IOException {
String fileName="新聞內(nèi)容.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={"標題","版塊","作者","創(chuàng)建時間","內(nèi)容"};
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);
}
//添加數(shù)據(jù)
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.小結(jié)
文件名出現(xiàn)亂碼
將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).設(shè)置內(nèi)容類型
2).設(shè)置文件名稱
3).?新建一個Excel文件? ? ? ? ? ? ? ? ? ?? HSSFWorkbook workbook=new HSSFWorkbook();
4).新建一個工作簿? ? ? ? ? ? ? ? ? ? ? ? ? HSSFSheet sheet=workbook.createSheet();
//添加多個工作簿? ? ? ? ? ? ?? ???????????????HSSFSheet sheet=workbook.createSheet(“sheetName”);
5).新建一行?? ?????????????????????????????????HSSFRow row=sheet.createRow(rowNum);
6).設(shè)置列中數(shù)據(jù)?? ??????????????????????????row.createCell(? index ).setCellValue( data );
7).??emmm......? ??????????????????????????????workbook.write(response.getOutputStream());