java 下载 excel

本文介绍如何正确地实现Excel文件的导出及多文件压缩为Zip的流程,避免内存溢出与文件损坏等问题,并提供了一种解决中文乱码的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

比较好的做法:

response.setContentType("application/-excel");  
response.addHeader("Content-Disposition", new String(("filename=" + filename).getBytes("GBK"), "ISO-8859-1"));
OutputStream os = response.getOutputStream(); 
workbook.write(os);
os.flush();
os.close();


 

容易内存溢出做法:

ByteArrayOutputStream os = new ByteArrayOutputStream();
workbook.write(os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
os.flush();
os.close();
return is;
 

打开excel时发生错误:excel 在 {fileName} 中发现不可读的内容

我写错的写法

@RequestMapping("/download")
	public void download(HttpServletRequest request,
			HttpServletResponse response, String type) throws IOException {
		String fileName = "";
		InputStream is = null;
		if ("03".equals(type)) {
			fileName = "03模板.xls";
			is = request.getSession().getServletContext()
					.getResourceAsStream("/template/sheetImport/03模板.xls");
		} else if ("07".equals(type)) {
			fileName = "07模板.xlsx";
			is = request.getSession().getServletContext()
					.getResourceAsStream("/template/sheetImport/07模板.xlsx");
		}

		response.setContentType("application/vnd.ms-excel");
		response.addHeader("Content-Disposition", new String(
				("filename=" + fileName).getBytes("GBK"), "ISO-8859-1"));
		BufferedOutputStream bos = new BufferedOutputStream(
				response.getOutputStream());
		BufferedInputStream bis = new BufferedInputStream(is);
		byte[] b = new byte[1024];
		while (bis.read(b) != -1) {
			bos.write(b);
		}
		bis.close();
		bos.flush();
		bos.close();
	}


 

 

正确的写法

@RequestMapping("/download")
	public void download(HttpServletRequest request,
			HttpServletResponse response, String type) throws IOException {
		String fileName = "";
		InputStream is = null;
		if ("03".equals(type)) {
			fileName = "03模板.xls";
			is = request.getSession().getServletContext()
					.getResourceAsStream("/template/sheetImport/03模板.xls");
		} else if ("07".equals(type)) {
			fileName = "07模板.xlsx";
			is = request.getSession().getServletContext()
					.getResourceAsStream("/template/sheetImport/07模板.xlsx");
		}

		response.setContentType("application/vnd.ms-excel");
		response.addHeader("Content-Disposition", new String(
				("filename=" + fileName).getBytes("GBK"), "ISO-8859-1"));
		BufferedOutputStream bos = new BufferedOutputStream(
				response.getOutputStream());
		BufferedInputStream bis = new BufferedInputStream(is);
		byte[] b = new byte[1024];
		int i = 0;
		while ((i = bis.read(b)) != -1) {
			bos.write(b, 0, i);
		}
		bis.close();
		bos.flush();
		bos.close();
	}


错误分析

当最后一次读取数据的时候byte数组的长度不足1024,而bos的write方法
 public void write(byte b[]) throws IOException {
	write(b, 0, b.length);
    }
自动取了byte的1024个长度,假如最后一次读取的长度为500,则下载时会把多余的524个空byte下载到excel中,导致excel错误!


 

最后建议把 application/vnd.ms-excel 换成 application/x-download, 否则ie会把文件当成excel2003处理,下载2007的时候就会报错了!


多份excel压缩成zip导出

// 工程引入 apache ant.jar Import org.apache.tools.zip.* 处理jdk默认zip处理出现压缩文件中文乱码
@RequestMapping("/export")
public void export(HttpServletResponse response) throws Exception {
	response.setContentType("application/-excel");  
	response.addHeader("Content-Disposition", new String(("filename=附件.zip").getBytes("GBK"), "ISO-8859-1"));
	OutputStream os = response.getOutputStream(); 

	InputStream in1 = '模板1';
	InputStream in2 = '模板2';
	HSSFWorkbook workbook1 = new HSSFWorkbook(in1);
	// workbook1 处理业务
	HSSFWorkbook workbook2 = new HSSFWorkbook(in2);
	// workbook2 处理业务
	
	ZipOutputStream zip = new ZipOutputStream(os);
	zip.putNextEntry(new ZipEntry("详细.xls"));
	workbook1.write(zip);
	
	zip.putNextEntry(new ZipEntry("统计.xls"));
	workbook2.write(zip);
	
	zip.setEncoding("GBK");
	zip.flush();
	zip.close();
	os.flush();
	os.close();
	in.close();
}


以下是使用Java下载Excel模板的示例代码: ```java import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class ExcelTemplateDownloader { public static void main(String[] args) { String fileUrl = "https://example.com/template.xlsx"; // Excel模板文件的URL String saveDir = "C:/downloads/"; // 文件保存目录 try { downloadFile(fileUrl, saveDir); System.out.println("Excel模板下载成功!"); } catch (IOException e) { System.out.println("Excel模板下载失败!" + e.getMessage()); } } public static void downloadFile(String fileUrl, String saveDir) throws IOException { URL url = new URL(fileUrl); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); byte[] buffer = new byte[1024]; int length; String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1); File file = new File(saveDir); if (!file.exists()) { file.mkdirs(); } FileOutputStream outputStream = new FileOutputStream(saveDir + fileName); while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } outputStream.close(); inputStream.close(); } } ``` 在上面的代码中,我们定义了一个名为 `downloadFile` 的方法,它使用 Java 的 URL 和 URLConnection 类来从指定的 URL 下载 Excel 模板文件,并将其保存到指定的本地目录中。在 `main` 方法中,我们可以使用这个方法来下载我们需要的 Excel 模板文件。注意,我们需要提供 Excel 模板文件的URL和本地保存目录。 你可以根据实际情况修改 `fileUrl` 和 `saveDir` 变量,以便在你的Java应用程序中下载Excel模板文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值