java 之简单的下载功能

jar包:

       
        
            net.sourceforge.jexcelapi
            jxl
            2.6.12
        

核心代码:

package com.controller;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

@RestController
@RequestMapping("/test")
public class TestController {

	@RequestMapping("/down")
	public void down(HttpServletResponse response){
		List> userList = getAllUserInfo();
		//设置响应信息
		response.setCharacterEncoding("UTF-8");
		
		//重置流
		response.reset();
		
		//响应内容类型
		response.setContentType("application/OCTET-STREAM; charset=UTF-8");
		response.addHeader("pragma", "no-cache");
		
		//设置下载文件的方式及文件名
		response.setHeader("Content-Disposition", "attachment;filename=\"user.xls\"");
		try {
			//创建一个工作簿
			WritableWorkbook workbook = Workbook.createWorkbook(response.getOutputStream());
			//创建一个表单
			WritableSheet sheet = workbook.createSheet("用户信息", 0);
			
			sheet.addCell(new Label(0, 0, "序号"));
			sheet.addCell(new Label(1, 0, "姓名"));
			sheet.addCell(new Label(2, 0, "密码"));
			int i = 0;
			for(Map user : userList){
				//向单元格中添加元素
				sheet.addCell(new Label(0, i+1, i+1+""));
				sheet.addCell(new Label(1, i+1, MapUtils.getString(user, "userName")));
				sheet.addCell(new Label(2, i+1, MapUtils.getString(user, "password")));
				i++;
			}
			
			workbook.write();
			workbook.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private List> getAllUserInfo() {
		List> userList = new ArrayList>();
		Map user = new HashMap();
		user.put("userName", "asd");
		user.put("password", "123");
		userList.add(user);
		Map user1 = new HashMap();
		user1.put("userName", "qwe");
		user1.put("password", "dsb");
		userList.add(user1);
		return userList;
	}
}

 

你可能感兴趣的:(java)