目录
业务场景:
实现方式1:
实现方式2:
实现方式3:
业务场景:
做东西之前我们要先搞明白它的业务场景:
比如我们想让客户通过excel表格,导入数据,那么可以让客户下载我们给他提供的样板,填写后在进行上传
实现方式有三种哈:
实现方式1:
我们想将存放在某个地方的模板,通过访问接口下过来
https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png
代码:
@GetMapping("/download")
public void download(String url, HttpServletResponse response) throws IOException;
@Override
public void download(String url, HttpServletResponse response) throws IOException {
FileInputStream in = null;
OutputStream out = null;
try {
//获取文件名
String filename = url.substring(url.lastIndexOf("/")+1);
filename = new String(filename.getBytes("iso8859-1"),"UTF-8");
String downloadpath = url;
//如果文件不存在
/*if(!file.exists()){
return false;
}*/
//设置响应头,控制浏览器下载该文件
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
//读取要下载的文件,保存到文件输入流
in= new FileInputStream(downloadpath);
//创建输出流
out= response.getOutputStream();
//缓存区
byte buffer[] = new byte[1024];
int len = 0;
//循环将输入流中的内容读取到缓冲区中
while((len = in.read(buffer)) > 0){
out.write(buffer, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭
in.close();
out.close();
}
}
postman测试:
发送的时候选择 Send and Download 哈,然后就会出现弹框了,你也可以将下载的内容地址换成你本地电脑上的,文件表格也是可以的哈,这里不在演示了
http://localhost:8092/download?url=https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png
实现方式2:
我们通过在代码设置你想要的格式,我这里设置的格式如下所示
代码:
pom文件添加
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
java代码:
@RequestMapping("/downloadExcel")
public void downloadExcel(HttpServletResponse response, HttpServletRequest request);
@Override
public void downloadExcel(HttpServletResponse response, HttpServletRequest request) {
String [] excelHeader = {"姓名","手机号(必填)","渠道名","产品名","手机操作系统(IOS/安卓)","是否是XX数据"};
List<Object> list = new ArrayList<>();
Object[] obj1 = {"张三","173*****311","a1","A","IOS","是"};
Object[] obj2 = {"李四","138*****742","a2","B","安卓","否"};
list.add(obj1);
list.add(obj2);
FileExport.exportExcel(excelHeader, list, "XXX模板", response, request);
}
工具类:
public class FileExport {
private static final Logger logger = LoggerFactory.getLogger(FileExport.class);
/** CSV文件列分隔符 */
private static final String CSV_COLUMN_SEPARATOR = ",";
private static final String CSV_COLUM_TABLE = "\t";
/** CSV文件列分隔符 */
private static final String CSV_RN = "\r\n";
/**
* 导出Excel文件
*
* @param excelHeader
* 导出文件中表格头
* @param list
* 导出的内容
* @param response
* HttpServletResponse对象,用来获得输出流向客户端写导出的文件
* @param sheetName
* Excel的sheet名称,加上时间戳作为导出文件的名称
*/
public static void exportExcel(String [] excelHeader, List<Object> list, String sheetName, HttpServletResponse response, HttpServletRequest request) {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sheetName);
HSSFRow row = sheet.createRow((int) 0);
/******设置单元格是否显示网格线******/
sheet.setDisplayGridlines(true);
/******设置头单元格样式******/
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
Font fontHeader = wb.createFont();
fontHeader.setBold(true);
fontHeader.setFontHeight((short) 240);
style.setFont(fontHeader);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
/******设置头内容******/
for (int i = 0; i < excelHeader.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(" " +excelHeader[i] + " ");
cell.setCellStyle(style);
}
/******设置内容单元格样式******/
HSSFCellStyle styleCell = wb.createCellStyle();
Font fontCell = wb.createFont();
fontCell.setColor(HSSFColor.BLACK.index);
styleCell.setAlignment(HorizontalAlignment.CENTER);
styleCell.setFont(fontCell);
styleCell.setBorderBottom(BorderStyle.THIN);
styleCell.setBorderLeft(BorderStyle.THIN);
styleCell.setBorderRight(BorderStyle.THIN);
styleCell.setBorderTop(BorderStyle.THIN);
/******设置单元格内容******/
for (int i = 0; i < list.size(); i++) {
row = sheet.createRow(i + 1);
/******设置行高******/
row.setHeightInPoints(20);
Object[] obj = (Object[]) list.get(i);
for (int j = 0; j < excelHeader.length; j++) {
styleCell.setWrapText(false);
HSSFCell cell = row.createCell(j);
if (obj[j] != null){
cell.setCellValue(obj[j].toString());
}else{
cell.setCellValue("");
}
//if(obj[j].toString().length()>20)
// styleCell.setWrapText(true);
cell.setCellStyle(styleCell);
sheet.autoSizeColumn(j);
}
}
OutputStream ouputStream = null;
try {
String encoding = "UTF-8";
/** 获取浏览器相关的信息 */
String userAgent = request.getHeader("user-agent");
/** 判断是否为msie浏览器 */
if (userAgent.toLowerCase().indexOf("msie") != -1){
encoding = "gbk";
}
response.setCharacterEncoding(encoding);
response.setContentType("application/vnd.ms-excel");
String fileName = sheetName;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHMMSS");
fileName += (dateFormat.format(new Date())).toString()+".xls";
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, encoding));
ouputStream = response.getOutputStream();
wb.write(ouputStream);
ouputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(ouputStream!=null) {
ouputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 导出CSV文件
* @param dataList 集合数据
* @param colNames 表头部数据
* @param mapKey 查找的对应数据
*/
public static boolean doExport(List<Map<String, Object>> dataList, String colNames, String mapKey, OutputStream os) {
try {
StringBuffer buf = new StringBuffer();
String[] colNamesArr = null;
String[] mapKeyArr = null;
colNamesArr = colNames.split(",");
mapKeyArr = mapKey.split(",");
/******完成数据csv文件的封装******/
/******输出列头******/
for (int i = 0; i < colNamesArr.length; i++) {
buf.append(colNamesArr[i]).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_RN);
if (null != dataList) {
/******输出数据******/
for (int i = 0; i < dataList.size(); i++) {
for (int j = 0; j < mapKeyArr.length; j++) {
buf.append(dataList.get(i).get(mapKeyArr[j])).append(CSV_COLUM_TABLE).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_RN);
}
}
/******写出响应******/
os.write(buf.toString().getBytes("GBK"));
os.flush();
return true;
} catch (Exception e) {
logger.error("doExport错误...", e);
}
return false;
}
/**
* 设置响应格式
* @param fileName
* @param response
* @throws UnsupportedEncodingException
*/
public static void responseSetProperties(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
/******设置文件后缀******/
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String fn = fileName + sdf.format(new Date()).toString() + ".csv";
/******读取字符编码******/
String utf = "UTF-8";
/******设置响应******/
response.setContentType("application/ms-txt.numberformat:@");
response.setCharacterEncoding(utf);
response.setHeader("Pragma", "public");
response.setHeader("Cache-Control", "max-age=30");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf));
}
}
实现方式3:
从项目resouce路径下载
文件位置
代码:
@RequestMapping("/downloadExcels")
public void downloadExcels(HttpServletResponse response,HttpServletRequest request);
@Resource
private ResourceLoader resourceLoader;
@Override
public void downloadExcels(HttpServletResponse response, HttpServletRequest request) {
InputStream inputStream = null;
ServletOutputStream servletOutputStream = null;
try {
String filename = "人员信息导入模板.xlsx";
String path = "template/202106291306142.xlsx";
org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:"+path);
response.setContentType("application/vnd.ms-excel");
response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.addHeader("charset", "utf-8");
response.addHeader("Pragma", "no-cache");
String encodeName = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
response.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\"; filename*=utf-8''" + encodeName);
inputStream = resource.getInputStream();
servletOutputStream = response.getOutputStream();
IOUtils.copy(inputStream, servletOutputStream);
response.flushBuffer();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (servletOutputStream != null) {
servletOutputStream.close();
servletOutputStream = null;
}
if (inputStream != null) {
inputStream.close();
inputStream = null;
}
// 召唤jvm的垃圾回收器
System.gc();
} catch (Exception e) {
e.printStackTrace();
}
}
}
浏览器访问就能下载了哈。