import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.pl.dcloud.framework.DownLoadUtil;
import com.pl.dcloud.service.ResourceTypeService;
import com.pl.dcloud.xmlParse.JSONToExcel2;
import com.pl.dcloud.xmlParse.XmltoExcelUtil;
/**
*
* @author Created by dx-ycw on 2017/5/18
*
*/
@Controller
@RequestMapping(value="/download",produces="text/plain;charset=UTF-8")
public class DownloadController extends ControllerImpl{
@Resource
private ResourceTypeService resourceTypeService;
@ResponseBody
@RequestMapping(value="/jsonBOM",produces="text/plain;charset=UTF-8")
public String downLoadJSONToExcel2(HttpServletRequest request,
HttpServletResponse response) throws Exception{
String path = "E:\\test\\20170605";
String fileName = "data.xls";
String filePath = path + "\\" + fileName;
JSONToExcel2 jsonExcel = new JSONToExcel2();
String josnStr = jsonExcel.readJSONData("E:\\test\\20170605\\3.json");
List<Map> list = jsonExcel.getExcelMapData(josnStr,resourceTypeService.getAllList());
jsonExcel.writeToExcel(list,filePath);
//下载
DownLoadUtil.downLoadFile(filePath, response, fileName, "xls");
return "下载成功"+filePath;
}
}
package com.pl.dcloud.framework;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import javax.servlet.http.HttpServletResponse;
public class DownLoadUtil {
public static boolean downLoadFile(String filePath, HttpServletResponse response, String fileName, String fileType) throws Exception {
File file = new File(filePath); //根据文件路径获得File文件
//设置文件类型(这样设置就不止是下Excel文件了,可以是多个文件类型)
if("pdf".equals(fileType)){
response.setContentType("application/pdf;charset=GBK");
}else if("xls".equals(fileType)){
response.setContentType("application/msexcel;charset=GBK");
}else if("doc".equals(fileType)){
response.setContentType("application/msword;charset=GBK");
}
//文件名
response.setHeader("Content-Disposition", "attachment;filename=\""
+ new String(fileName.getBytes(), "ISO8859-1") + "\"");
response.setContentLength((int) file.length());
byte[] buffer = new byte[4096];// 缓冲区
BufferedOutputStream output = null;
BufferedInputStream input = null;
try {
output = new BufferedOutputStream(response.getOutputStream());
input = new BufferedInputStream(new FileInputStream(file));
int n = -1;
//遍历,开始下载
while ((n = input.read(buffer, 0, 4096)) > -1) {
output.write(buffer, 0, n);
}
output.flush(); //不可少
response.flushBuffer();//不可少
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭流,不可少
if (input != null)
input.close();
if (output != null)
output.close();
}
return false;
}
}