使用以下代码导出数据表中的数据到Excel,本地测试正常。部署到服务器端发现这个文件是存在于服务器端的某一个文件夹中(发现问题),当时测试的时候因为本地就相当于服务器,所以可以找到导出的Excel。所以现在想如何可以让客户端导出数据的时候再从服务器端把生成的Excel下载到本地,使用a标签download属性,下载失败,感觉应该是访问不到服务器端的路径,
求大神指点,或者说给我一个新的做法,换条思路也行。,!!!可以直接下载到本地最好!
html:
<a href="/download?args.....">下载</a>
java:
download(args){
fileoutputstream fileout;
response.write(fileout)// 把文件流写入响应流,伪代码,自己完善
}
谢谢
[HttpGet]
public HttpResponseMessage ExportExcel()
{
//XSSFWorkbook workbook = new XSSFWorkbook();
//XSSFSheet sheet1 = (XSSFSheet)workbook.CreateSheet("费用");
//XSSFRow row1 = (XSSFRow)sheet1.CreateRow(0);
//FileStream fs = new FileStream("", FileMode.Create);
//workbook.Write(fs);
//fs.Close();
Models.NpoiMemoryStream ms = new Models.NpoiMemoryStream();
//MemoryStream ms = new MemoryStream();
ms.AllowClose = false;
//workbook.Write(ms);
ms.Flush();
ms.Seek(0, SeekOrigin.Begin);
ms.AllowClose = true;
// ms.Seek(0, SeekOrigin.Begin);
// ms.Position = 0;
HttpResponseMessage respon = new HttpResponseMessage(HttpStatusCode.OK);
respon.Content = new StreamContent(ms);
//respon.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
respon.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/vnd.ms-excel");
respon.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = System.Web.HttpUtility.UrlEncode("test.xlsx")
};
return respon;
}
@RequestMapping(value = "/sendExcel.xls")//下载Excel
public void sendUploadVoice(HttpServletResponse response,HttpServletRequest request,String pathName,String name) {
//System.out.println(pathName+"\t"+name);
File file = null;
try {
//接收请求
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream");//8进制字节流
//获取文件
name = URLDecoder.decode(name, "UTF-8");
//获取文件输入流 localFileDir是服务端存储文件的路径
file = new File(pathName);
response.setContentLength((int) file.length());
response.setHeader("Accept-Ranges", "bytes");
InputStream in = new BufferedInputStream(new FileInputStream(file), 1024);
OutputStream os = new BufferedOutputStream(response.getOutputStream());
byte[] bytes = new byte[1024];
int i = 0;
while ((i = in.read(bytes)) > 0) {
os.write(bytes, 0, i);
}
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}