//此处使用的是layui,jquery
<button type="button" class="layui-btn layui-btn-normal layui-btn-radius" id="exportExcel">导出</button>
$(document).on('click',"#exportExcel",function(){
// var loading = layer.msg('导出中请稍后...', {icon: 16, shade: 0.3, time:0});//遮罩层开启
window.open("../plan/exportPlanExcel");
// layer.close(loading);//遮罩层关闭
});
//后台,一个公共类
package com.example.demo.job.util;
import org.apache.poi.hssf.usermodel.*;
public class ExcelUtil {
/**
* 导出Excel
* @param sheetName sheet名称
* @param title 标题
* @param values 内容,可以修改为list 或者 map
* @param wb HSSFWorkbook对象
* @return
*/
public static HSSFWorkbook getHSSFWorkbook(String sheetName, String []title, String [][]values, HSSFWorkbook wb){
// 第一步,创建一个HSSFWorkbook,对应一个Excel文件
if(wb == null){
wb = new HSSFWorkbook();
}
// 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet(sheetName);
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
HSSFRow row = sheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
//声明列对象
HSSFCell cell = null;
//创建标题
for(int i=0;i<title.length;i++){
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
}
//创建内容
for(int i=0;i<values.length;i++){
row = sheet.createRow(i + 1);
for(int j=0;j<values[i].length;j++){
//将内容按顺序赋给对应的列对象
row.createCell(j).setCellValue(values[i][j]);
}
}
return wb;
}
}
//controller调用代码
/**
* 导出
*/
@RequestMapping(value = "exportPlanExcel", method = RequestMethod.GET)
@ResponseBody
public void exportPlanExcel(HttpServletRequest request, HttpServletResponse response){
Map<String,Object> map = new HashMap<>();
//准备数据
List<Map<String,Object>> list=cellinfoMapper.selectDataByPage();
String title = "序号,城市,数量"; //
String key = "city,cellNum"; //
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
String fileNameTime = "D://方案详情"+sdf.format(new Date())+".xlsx";
// String code = BeanUtils.generateExcel(list,title,key,fileNameTime,response);
sendExcel(list,title,key,response);
}
public void sendExcel(List<Map<String,Object>> list,String title,String key, HttpServletResponse response){
DecimalFormat df = new DecimalFormat("#.00");
//map.get(key)中的key
String[] keys = key.split(",");
//excel标题
String[] titles = title.split(",");
//excel文件名
String fileName = "方案详情"+System.currentTimeMillis()+".xls";
//sheet名
String sheetName = "方案详情";
// 将数据转换成String [][] 二维数组(具体情况根据自身需求定)
String [][] content = new String[list.size()][titles.length];
int id=1;
int i=0;
for (Map<String,Object> map: list) {
content[i][0] = String.valueOf(id);
content[i][1] = String.valueOf(map.get(keys[0]));
content[i][2] = String.valueOf(map.get(keys[1]));
id++;
i++;
}
//创建HSSFWorkbook
HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, titles, content, null);
//响应到客户端
this.setResponseHeader(response, fileName);
OutputStream os = null;
try {
os = response.getOutputStream();
wb.write(os);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//发送响应流方法
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("application/octet-stream;charset=ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
}
}
//这里还有个下载的,复制来的,没验证.先留着,,前端也跟上边一样,一个按钮,一个点击事件,里边有个window.open("路径")或者window.location.href("路径")之类的方法
@RequestMapping("/download")
public void download(String content, HttpServletResponse response) {
try {
// 要下载的文件的路径。
File file = new File(content);
// 取得文件名。
String filename = file.getName();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(content));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
=======================================================================
<!--引入poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.0.0</version>
</dependency>
// 创建一个xlsx
XSSFWorkbook xk = new XSSFWorkbook();
// 创建sheetname第一页页名
XSSFSheet sheet = xk.createSheet("测试");
// 字体样式
XSSFFont xssfFont = xk.createFont();
xssfFont.setBold(true);
xssfFont.setFontName("楷体");
xssfFont.setFontHeight(11);
// 表头样式
XSSFCellStyle headStyle = xk.createCellStyle();
// 继承字体样式
headStyle.setFont(xssfFont);
// 竖向居中,横向居中
headStyle.setVerticalAlignment(VerticalAlignment.CENTER);
headStyle.setAlignment(HorizontalAlignment.CENTER);
// 设置标题一行的单元格的填充颜色为灰色
headStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headStyle.setWrapText(true); // 设置自动换行
headStyle.setHidden(true); // 高度自动
// 创建第一行标题
XSSFRow row1 = sheet.createRow(0);
// 设置宽度
sheet.setDefaultColumnWidth(30);
// 第一行第一列
XSSFCell Cell1 = row1.createCell(0);
Cell1.setCellValue("姓名");
Cell1.setCellStyle(headStyle);
// 第二列
XSSFCell Cell2 = row1.createCell(1);
Cell2.setCellValue("班级");
Cell2.setCellStyle(headStyle);
// 第三列
XSSFCell Cell3 = row1.createCell(2);
Cell3.setCellValue("年龄");
Cell3.setCellStyle(headStyle);
// 第四列
XSSFCell Cell4 = row1.createCell(3);
Cell4.setCellValue("性别");
Cell4.setCellStyle(headStyle);
// 创建第二行内容
XSSFRow row2 = sheet.createRow(1);
XSSFCell Cell11 = row2.createCell(0);
Cell11.setCellValue("小明");
XSSFCell Cell22 = row2.createCell(1);
Cell22.setCellValue("终极一班");
XSSFCell Cell33 = row2.createCell(2);
Cell33.setCellValue("33");
XSSFCell Cell44 = row2.createCell(3);
Cell44.setCellValue("男");
// 每次创建一行一列都需要调用方法可自己加工成工具类使用时只需要赋值即可
try {
// 附件名称和格式
response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("学生信息.xlsx","UTF-8"));
response.setContentType("application/vnd.ms-excel");
// 转为二进制流进行吐出
ServletOutputStream os = response.getOutputStream();
xk.write(os);
os.flush();
os.close();
} catch (Exception e) {
log.error("Excel error", e);
}
————————————————
版权声明:本文为CSDN博主「惊呆我了」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_42683274/article/details/115575144
测试可用