Java poi 导出Excel并下载到客户端,具体内容如下
Maven配置,包含了其他文件格式的依赖,就全贴出来了
org.apache.poi poi-excelant3.12 org.apache.poi poi-scratchpad3.12 org.apache.poi poi-ooxml3.8 org.apache.poi poi-ooxml-schemas3.8
Service层
@Override
public void export(Long sblsh, String excelName, OutputStream out) {
try {
// 第一步,创建一个webbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
//生成一个表格
HSSFSheet sheet = wb.createSheet(excelName);
// 第三步,在sheet中添加表头第0行
HSSFRow row = sheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
HSSFCell cell = row.createCell(0);
cell.setCellStyle(style);
Byte kjzz = qyjbxxMapper.getKjzz(sblsh);
List record = this.selectBySblsh(sblsh);
this.insertData(wb, sheet, row, record, out);
}
} catch (Exception e) {
logger.info(e.getMessage());
}
}
private void insertData(HSSFWorkbook wb,HSSFSheet sheet,HSSFRow row,List record,
OutputStream out){
try {
row = sheet.createRow(1);
for(int i=0;i
Controller
@RequestMapping("/export")
public void export(Long sblsh, HttpServletRequest request, HttpServletResponse response){
response.setContentType("octets/stream");
String excelName = "文件名";
try {
response.addHeader("Content-Disposition", "attachment;filename="+new String(excelName.getBytes("gb2312"), "ISO8859-1" )+".xls");
OutputStream out = response.getOutputStream();
aService.export(sblsh,excelName ,out);
} catch (Exception e) {
e.printStackTrace();
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



