java读取内容生成Excel文档

今天别人突然问我下载生成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();
}
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值