java 导出excel 和zip

1.jsp页面点击导出 按钮

	<a class="button btn-circle " href="javascript:;" onclick="amazomReportHandle.exportAmazonReport();">
						<i class="fa fa-cloud-download"></i>
						<span class="hidden-480"><spring:message code="i18n.report.batch.download" text="批量下载"/></span>
					</a>

2.js导出方法

exportAmazonReport: function(id){
			if(id=="" || id == undefined){
				id = searchAmazomReportTable.selected();
			}
			if(id==""|| id == undefined){
				g.info("i18n.module.global.prompt.msg.selectdata");
				return ;
			}
			var ids="";
			if(typeof(id)  == "string"){
				ids = id;
			}else{
				for(var i=0;i<id.length;i++){
					ids+=id[i]+",";
				}
			}
			$.ajax({
				type : "POST",
				url : "/amazonReport/fileDownloadLog",
				data :{id:ids},
				dataType : "json",
				success : function(data) {
					console.log(111111);
					if (data.code == "SUCCESS") {
						var url = data.result.reportUrl;
						console.log(url);
						window.location.href = url;
					} else {
						g.warning("i18n.order.upload.msg.7");//文件不存在
					}
				}
			});
		}

3.导出后台代码

@RequestMapping(value = "/fileDownload/{ids}", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
	public void fileDownload(@PathVariable("ids") String ids, HttpServletRequest request, HttpServletResponse response) {

		User user = this.getLoginUser();
		try {
			// filePath=URLDecoder.decode(filePath, "UTF-8");

			List<Long> idsList = new ArrayList<>();
			for (String id : ids.split(",")) {
				if(StringUtils.isNotEmpty(id)){
					idsList.add(Long.valueOf(id));
				}
			}

			List<AmazonReportRequestInfo> reportRequestInfolist = amazonReportService.findAmazonReportRequestInfoByIds(idsList);
			if(CollectionUtils.isNotEmpty(reportRequestInfolist)){
				if(reportRequestInfolist.size() == 1){
					//单个文件下载
					AmazonReportRequestInfo  amazonReportRequestInfo = reportRequestInfolist.get(0);
					String reportUrl = amazonReportRequestInfo.getReportUrl().replace("/", FILE_SEPARATOR).replace("\\", FILE_SEPARATOR);
					String fileName = reportUrl.substring(reportUrl.lastIndexOf(FILE_SEPARATOR)+1);

					if ("FF".equals(getBrowser(request))) {
						// 针对火狐浏览器处理方式不一样了
						FileDownload.filesaleDownload(request, response, reportUrl, fileName);
					} else {
						FileDownload.fileDownload(request,response,  reportUrl, fileName);
					}
					exportLogService.insertAmazonReportLog(amazonReportRequestInfo,user,fileName,"success");

				}else{
					//批量下载
					String webRootPath = request.getSession().getServletContext().getRealPath("/tempDir/"+String.valueOf(System.currentTimeMillis()));
					webRootPath = webRootPath.replace("/", FILE_SEPARATOR).replace("\\", FILE_SEPARATOR);
					File filePath = new File(webRootPath);
					if (!filePath.exists()){
						filePath.mkdirs();
					}
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
					Date nowTime = new Date();

					String zipFileName = "";
					Shop shop = shopService.findById(reportRequestInfolist.get(0).getShopId(),user);
					if(shop != null){
						zipFileName = webRootPath +  FILE_SEPARATOR + shop.getName()+"-" + sdf.format(nowTime.getTime())+".zip";
					}else{
						zipFileName = webRootPath +  FILE_SEPARATOR + sdf.format(nowTime.getTime())+".zip";
					}


					File fileZip = new File(zipFileName);
					if (!fileZip.exists()){
						fileZip.createNewFile();
					}
					List<File> files = new ArrayList<File>();

					for (AmazonReportRequestInfo amazonReportRequestInfo : reportRequestInfolist) {

						File file = new File(amazonReportRequestInfo.getReportUrl());
						if(file.exists()) {
							files.add(file);
							String reportUrl = amazonReportRequestInfo.getReportUrl().replace("/", FILE_SEPARATOR).replace("\\", FILE_SEPARATOR);
							String fileName = reportUrl.substring(reportUrl.lastIndexOf(FILE_SEPARATOR)+1);
							exportLogService.insertAmazonReportLog(amazonReportRequestInfo,user,fileName,"success");
						}
					}

					FileOutputStream fous = new FileOutputStream(fileZip);
					ZipOutputStream zipOut = new ZipOutputStream(fous);
					FileDownload.zipFile(files,zipOut);
					zipOut.close();
					fous.close();
					if ("FF".equals(getBrowser(request))) {
						// 针对火狐浏览器处理方式不一样了
						FileDownload.filesaleDownload(request, response, fileZip.getAbsolutePath(), fileZip.getName());
					} else {
						FileDownload.fileDownload(request,response,  fileZip.getAbsolutePath(), fileZip.getName());
					}
					FileUtils.delFiles(filePath);

				}

			}
		} catch (Exception e) {
			logger.error("反馈管理下载附件error:", e);
			e.printStackTrace();
		}
	}
package com.ym.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.alibaba.druid.util.Base64;

public class FileDownload {
	
	private final static Logger logger = Logger.getLogger(FileDownload.class);

	/**
	 * @param response
	 * @param filePath 文件完整路径(包括文件名和扩展名)
	 * @param fileName 下载后看到的文件名
	 * @return 文件名
	 */
	public static void fileDownload(final HttpServletRequest request, final HttpServletResponse response, String filePath, String fileName) throws Exception {
		try {
//			byte[] data = toByteArray2(filePath);
//			String agent = (String)request.getHeader("USER-AGENT");
//			String downloadFileName = fileName;
//	        if(agent != null && agent.toLowerCase().indexOf("firefox") > 0){
//	            downloadFileName = "=?UTF-8?B?" + (new String(Base64.byteArrayToBase64(fileName.getBytes("UTF-8")))) + "?=";    
//	        }
//	        else{
//	            downloadFileName =  java.net.URLEncoder.encode(fileName, "UTF-8");
//	        }
//			fileName = URLEncoder.encode(fileName, "UTF-8");
//			fileName = fileName.replaceAll("\\+",  "%20" );
			response.reset();
			File downFile = new File(filePath);
			if(downFile.exists()) {
				response.addHeader("Content-Length", "" + downFile.length());
			}
			response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("GBK"), "ISO8859-1") + "\"");
			response.setContentType("application/octet-stream;charset=UTF-8");
			OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
			outByteData(downFile, outputStream);
			outputStream.flush();
			outputStream.close();
			response.flushBuffer();
		} catch(Exception e) {
			System.out.println("加载文件失败->"+filePath);
		}
	}
	
	public static void filesaleDownload(final HttpServletRequest request, final HttpServletResponse response, String filePath, String fileName) throws Exception {

//		byte[] data = toByteArray2(filePath);
//		fileName = new String(fileName.getBytes("GBK"), "ISO8859-1");  
//		String agent = (String)request.getHeader("USER-AGENT");
//		if(agent != null && agent.toLowerCase().indexOf("firefox") > 0){
//			fileName = "=?UTF-8?B?" + (new String(Base64.byteArrayToBase64(fileName.getBytes("UTF-8")))) + "?=";    
//        }
//        else{
//        	fileName =  java.net.URLEncoder.encode(fileName, "UTF-8");
//        }
		response.reset();
		response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("GBK"), "ISO8859-1") + "\"");
		response.setContentType("application/octet-stream;charset=UTF-8");
		File downFile = new File(filePath);
		if(downFile.exists()) {
			response.addHeader("Content-Length", "" + downFile.length());
		}
		OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
		outByteData(downFile, outputStream);
		outputStream.close();
		response.flushBuffer();
	}
	
	public static void outImage(final HttpServletRequest request, final HttpServletResponse response, String filePath) throws Exception {
		response.reset();
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		File downFile = new File(filePath);
		if(downFile.exists()) {
//			response.setContentType("image/"+downFile.getName().substring(downFile.getName().lastIndexOf(".") + 1));
			response.addHeader("Content-Length", "" + downFile.length());
			String contentType = null;  
	        try {
	        	Path path = Paths.get(filePath);  
	            contentType = Files.probeContentType(path);  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        }
			response.setContentType(contentType);
		}
		OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
		outByteData(downFile, outputStream);
		outputStream.close();
		response.flushBuffer();

	}
	
	public static int outByteData(File downFile, OutputStream out) throws IOException {
		if (!downFile.exists()) {
			throw new FileNotFoundException(downFile.getAbsolutePath());
		}
		int length = 0;
		FileInputStream fs = null;
		try {
			fs = new FileInputStream(downFile);
			byte[] data = new byte[20480];
			int len = -1;
			while ((len = fs.read(data)) > -1) {
				out.write(data, 0, len);
				out.flush();
				length += len;
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				fs.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return length;
	}

	/**
	 * 读取到字节数组2
	 * 
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
//	public static byte[] toByteArray2(String filePath) throws IOException {
//
//		File f = new File(filePath);
//		if (!f.exists()) {
//			throw new FileNotFoundException(filePath);
//		}
//
//		FileChannel channel = null;
//		FileInputStream fs = null;
//		try {
//			fs = new FileInputStream(f);
//			channel = fs.getChannel();
//			ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
//			while ((channel.read(byteBuffer)) > 0) {
//			}
//			return byteBuffer.array();
//		} catch (IOException e) {
//			e.printStackTrace();
//			throw e;
//		} finally {
//			try {
//				channel.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//			try {
//				fs.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//	}

//	public static byte[] toByteArray2(File f) throws IOException {
//		if (f == null || !f.exists()) {
//			throw new FileNotFoundException();
//		}
//
//		FileChannel channel = null;
//		FileInputStream fs = null;
//		try {
//			fs = new FileInputStream(f);
//			channel = fs.getChannel();
//			ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
//			while ((channel.read(byteBuffer)) > 0) {
//			}
//			return byteBuffer.array();
//		} catch (IOException e) {
//			e.printStackTrace();
//			throw e;
//		} finally {
//			try {
//				channel.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//			try {
//				fs.close();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//	}
	
	
	 /**
     * 读取文本流
     */
    public static List<String> getText(String filePath) throws IOException {
    	BufferedReader bis = null;
    	BufferedInputStream inStream = null;
    	List<String> lines = new ArrayList<String>();
    	try{
    		//获得文件及其编码,并且用buffer包装
    		File file = new File(filePath);
    		inStream = new BufferedInputStream(new FileInputStream(file));
    		//标记初始位
    		inStream.mark(0);
    		String code = codeString(inStream);
    		//使流复位
    		inStream.reset();
    		bis = new BufferedReader(new InputStreamReader(inStream, code));
    		
    		//读取字符串
    		String str = null;
    		while((str = bis.readLine()) != null) {
    			lines.add(str + "\r\n");
    		}
    	}catch (Exception e) {
    		e.printStackTrace();
		}finally {
			//关闭流
			if(bis != null) {
				bis.close();
			}
			if(inStream != null) {
				inStream.close();
			}
		}
        return lines;
    }

	public static String getClasspath() {
		String path = (String.valueOf(Thread.currentThread().getContextClassLoader())).replaceAll("file:/", "").replaceAll("%20", " ").trim();
		if (path.indexOf(":") != 1) {
			path = File.separator + path;
		}
		return path;
	}
	
	
	/**
	 * 判断文件的编码格式
	 * @param fileName :file
	 * @return 文件编码格式
	 * @throws Exception
	 */
	private static String codeString(BufferedInputStream bin) throws Exception{
		int p = (bin.read() << 8) + bin.read();
		String code = null;
		
		switch (p) {
			case 0xefbb:
				code = "UTF-8";
				break;
			case 0xfffe:
				code = "Unicode";
				break;
			case 0xfeff:
				code = "UTF-16BE";
				break;
			default:
				code = "GBK";
		}
		return code;
	}
	
	/***
	 * 文件删除</br>
	 * 注意:如果不是异步导出,生成文件后,没有再使用,请调用次方法删除临时文件
	 * @param filePath
	 */
	public static void fileRemove(String filePath) {
		if (StringUtils.isEmpty(filePath)) {
			return ;
		}
		try {
			File file = new File(filePath);
			if (file.exists() && !file.isDirectory()) {
				file.delete();
			}
		} catch (Exception e) {
			logger.error(MessageFormat.format("删除导出文件异常,地址:{0}", filePath), e);
			e.printStackTrace();
		}
	}

	/**
	 * 获取所有需要压缩的文件
	 * @param files
	 * @param outputStream
	 */
	public static void zipFile(List files, ZipOutputStream outputStream) {
		int size = files.size();
		for(int i = 0; i < size; i++) {
			File file = (File) files.get(i);
			zipFile(file, outputStream);
		}
	}

	/**
	 * 将文件压缩
	 * @param inputFile
	 * @param ouputStream
	 */
	public static void zipFile(File inputFile, ZipOutputStream ouputStream) {
		try {
			if(inputFile.exists()) {
				if (inputFile.isFile()) {
					FileInputStream inputStream = new FileInputStream(inputFile);
					BufferedInputStream bins = new BufferedInputStream(inputStream, 512);

					ZipEntry entry = new ZipEntry(inputFile.getName());
					ouputStream.putNextEntry(entry);

					int nNumber;
					byte[] buffer = new byte[512];
					while ((nNumber = bins.read(buffer)) != -1) {
						ouputStream.write(buffer, 0, nNumber);
					}
					bins.close();
					inputStream.close();
				} else {
					try {
						File[] files = inputFile.listFiles();
						for (int i = 0; i < files.length; i++) {
							zipFile(files[i], ouputStream);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>