SSM framework implements SQL data export to Excel
Ideas
- First add an export button to the front-end page, and then interact with the back-end controller.
- Then write the export function method in the corresponding controller.
- Method body:
- Add the HttpServletResponse server response object in the method parameter, and throw an exception class IOException.
- Then create the Excel file, sheet page, and header row.
- Then get the list object traversed by the pojo class corresponding to the download table.
- Finally, set the name of the Excel file saved by the client during download.
Code
Here is an example of the data table and pojo named home
public class ExcelController {
@Autowired
HomeServiceImpl homeService;
@RequestMapping("/home")
public void excel_home(HttpServletResponse response )throws IOException {
//设置字符集
response.setCharacterEncoding("UTF-8");
List<Home> homeList=homeService.queryAllHome();
//创建excel文件
HSSFWorkbook wb = new HSSFWorkbook();
//创建sheet页
HSSFSheet sheet = wb.createSheet("房间信息");
//创建标题行
HSSFRow titleRow = sheet.createRow(0);
titleRow.createCell(0).setCellValue("编号");
titleRow.createCell(1).setCellValue("房间号");
titleRow.createCell(2).setCellValue("房间类型");
titleRow.createCell(3).setCellValue("价格");
titleRow.createCell(4).setCellValue("状态");
titleRow.createCell(5).setCellValue("描述");
//获取需要下载表对应的pojo类
for(Home home:homeList){
HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()+1);
dataRow.createCell(0).setCellValue(home.getId());
dataRow.createCell(1).setCellValue(home.getNum());
dataRow.createCell(2).setCellValue(home.getH_Type());
dataRow.createCell(3).setCellValue(home.getPrice());
dataRow.createCell(4).setCellValue(home.getState());
dataRow.createCell(5).setCellValue(home.getText());
}
// 设置下载时客户端Excel的名称
response.setContentType("application/octet-stream;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename="
+ new String("房间信息表".getBytes(),"iso-8859-1") + ".xls");
//创建一个流
OutputStream ouputStream = response.getOutputStream();
//写入数据
wb.write(ouputStream);
ouputStream.flush();
//关闭流
ouputStream.close();
}