今天别人突然问我下载生成Excel,我看了一下他的方式,感觉太麻烦了,给他写了个例子,分享一下
下载Excel:
pom.xml文件:
<!-- 读取Excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
主要是需要这几个jar包:
UploadController文件:
@Controller
@RequestMapping("/upload")
public class UploadController {
@Resource
private IUploadService uploadService;
/**
* 导出excel
* @return
* 2018年4月25日上午9:54:53
*/
@RequestMapping("/excel")
public void exportExcel(HttpServletResponse response){
try {
uploadService.exportExcel(response);
} catch (Exception e) {
// TODO: handle exception
}
}
}
service文件:
@Service
public class UploadServiceImpl implements IUploadService{
@Override
public void exportExcel(HttpServletResponse response) throws Exception {
//第一步,创建一个workbook对应一个excel文件
XSSFWorkbook workbook = new XSSFWorkbook();
//第二部,在workbook中创建一个sheet对应excel中的sheet
XSSFSheet sheet = workbook.createSheet("sheet1");
//第三部,在sheet表中添加表头第0行,老版本的poi对sheet的行列有限制
XSSFRow row = sheet.createRow(0);
//第四部,创建单元格,并设置值表头,设置表头居中
XSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(XSSFCellStyle.ALIGN_CENTER);//创建居中格式
XSSFCell cell = row.createCell(0);
cell.setCellValue("标题");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue("内容");
cell.setCellStyle(style);
cell = row.createCell(2);
cell.setCellValue("作者");
cell.setCellStyle(style);
cell = row.createCell(3);
cell.setCellValue("时间");
cell.setCellStyle(style);
cell = row.createCell(4);
cell.setCellValue("点击量");
cell.setCellStyle(style);
cell = row.createCell(5);
cell.setCellValue("是否原文");
cell.setCellStyle(style);
//第五部,写入实体数据
for(int i=0;i<10;i++){
row = sheet.createRow(i+1);//创建单元格
//创建单元格设值
row.createCell(0).setCellValue("1111");
row.createCell(1).setCellValue("2222");
row.createCell(2).setCellValue("3333");
row.createCell(3).setCellValue("4444");
row.createCell(4).setCellValue("5555");
row.createCell(5).setCellValue("6666");
}
//第6步,输出Excel
OutputStream output = response.getOutputStream();
response.reset();
// long filename = System.currentTimeMillis();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
String fileName = df.format(new Date());
response.setHeader("Content-disposition", "attachment; filename = "+fileName+".xlsx");
response.setContentType("application/msexcel");
workbook.write(output);
output.close();
}
}