springmvc导出excel(POI)

/**
     * 导出excel表格
     */
    @RequestMapping(value = "/doExportData", method = {RequestMethod.POST, RequestMethod.GET})
    public void doExportUserData(HttpServletRequest request, HttpServletResponse response,ModelMap modelMap){
    	String enddate = (String) request.getParameter("enddate");
        //查询数据列表
        List<User> userList =  aService.findByDate(enddate);

    	// 生成提示信息,
        response.setContentType("application/vnd.ms-excel");  

        try{
        	//拼凑文件名称:时间+随机数         String fileName = "" ;
        	String[] date2 = enddate.split("-");
        	for(int i=0;i<date2.length;i++){
        		fileName = fileName+date2[i];
        	}                //方法二:         //String fileName = enddate.replace("-", "");
        	fileName = fileName+Math.round(Math.random()*10000);//添加随机数
            response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xls");
            // 产生工作簿对象
            HSSFWorkbook workbook = new HSSFWorkbook();
            //产生工作表对象
            HSSFSheet sheet = workbook.createSheet("用户列表");  //设置sheet页名称
            HSSFRow row = sheet.createRow(0);
            HSSFCellStyle style = workbook.createCellStyle();
            style.setAlignment(CellStyle.ALIGN_CENTER); // 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("部门名称");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("工号");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("姓名");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("时间");
            cell.setCellStyle(style);

            //循环数据
            for (int i = 0; i < userList.size(); i++){
            	row = sheet.createRow(i + 1);
                User user = userList.get(i);
                //创建单元格,并设置值
                row.createCell(0).setCellValue(user.getDeptName());
                row.createCell(1).setCellValue(user.getUserid());
                row.createCell(2).setCellValue(user.getName());
                row.createCell(3).setCellValue(enddate);
            }
            //文件导出路径,项目中的exportfile文件下
            String path = request.getSession().getServletContext()
    				.getRealPath("/");
            String filePath =path+"exportfile\\"+fileName+".xls";
            OutputStream os = new FileOutputStream(filePath);
            workbook.write(os);
            os.close();   

            //下载文件(只是导出到了相应的文件下面,下载中没有,不添加此方法,在谷歌浏览器中不能直接可以打开文件,提示保存文件名称不一致,打开是空的)
            File templateFile = new File(filePath);
            FileUtil.downloadFile(response, templateFile);
        }catch (Exception e){
        	e.printStackTrace();
        }
    }

FileUtil.java 下载相关的工具类

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;

/**
 * 文件工具类
 */
public class FileUtil {

	/**
	 * 下载文件
	 *
	 * @param response
	 * @param file
	 * @throws Exception
	 */
	public static void downloadFile(HttpServletResponse response, File file)
			throws Exception {

		if (null == response || null == file)
			return;

		InputStream is = null;
		OutputStream os = null;

		if (file.exists()) {
			// 2 文件名称
			String fileName = getFileNameByCompleteFilePath(file.getName());
			// 3 文件大小
			String fileLength = String.valueOf(file.length());
			// 4 下载文件名称
			String realDownLoadFileName = new String(fileName.getBytes(),
					"8859_1");
			// 5 设置响应参数
			response.reset();
			response.setContentType("application/x-msdownload;");
			response.setHeader("Content-disposition", "attachment; filename="
					+ realDownLoadFileName);
			response.setHeader("Content-Length", fileLength);
			response.setHeader("Cache-Control",
					"must-revalidate, post-check=0, pre-check=0");
			response.setHeader("Pragma", "public");
			response.setDateHeader("Expires",
					System.currentTimeMillis() + 1000L);
			try {
				is = new BufferedInputStream(new FileInputStream(file));
				os = new BufferedOutputStream(response.getOutputStream());
				byte[] buffer = new byte[1024];
				while (true) {

					int size = is.read(buffer, 0, 1024);
					if (size == -1) {

						break;
					}
					os.write(buffer, 0, size);
				}

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (is != null) {
						is.close();
					}
				} catch (IOException e) {

					e.printStackTrace();
				}
				try {
					if (os != null) {
						os.close();
					}
				} catch (IOException e) {

					e.printStackTrace();
				}
			}
			response.setStatus(HttpServletResponse.SC_OK);
			try {

				response.flushBuffer();

			} catch (IOException e) {

			}
		} else {
			// System.out.println("下载文件不存在,文件路径: " + file.getAbsolutePath());
			// 如果文件不存在,则创建异常对象并向上抛出
			throw new Exception();
		}
	}

	public static String getFileNameByCompleteFilePath(String path) {

		if (StringUtils.isBlank(path))
			return "";
		// 1 转化路径为本地串
		path = toLocalPath(path);
		// 2 处理
		if (StringUtils.isNotBlank(path)) {
			int index = path.lastIndexOf(File.separator);
			return path = path.substring(index + 1);
		}
		return "";
	}

	public static final String toLocalPath(String pathString) {

		if (StringUtils.isBlank(pathString))
			return "";
		pathString = replace(pathString, "/", File.separator);
		pathString = replace(pathString, "\\", File.separator);
		return pathString;
	}
	public static final String replace(String line, String oldString,
			String newString) {

		// 递归算法
		int i = 0;
		if ((i = line.indexOf(oldString, i)) >= 0) {
			char[] line2 = line.toCharArray();
			char[] newString2 = newString.toCharArray();
			int oLength = oldString.length();
			StringBuffer buf = new StringBuffer(line2.length);
			buf.append(line2, 0, i).append(newString2);
			i += oLength;
			int j = i;
			while ((i = line.indexOf(oldString, i)) > 0) {
				buf.append(line2, j, i - j).append(newString2);
				i += oLength;
				j = i;
			}
			buf.append(line2, j, line2.length - j);
			return buf.toString();
		}
		return line;
	}

}

  

时间: 2024-10-18 16:12:53

springmvc导出excel(POI)的相关文章

springmvc导出excel并弹出下载框

加入对应的jar包,包括springmvc,poi的, spring jar包在此不列举出来,主要是poi包,如下图所示 下载地址:http://download.csdn.net/download/huawei2010_2011_2012/5034041,或者搜poi3.9 实体类: public class Project { private Integer id; private String name; private String technology;//所用技术 private S

springmvc 导出excel

1.pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <

Java中导入导出Excel -- POI技术

一.介绍: 当前B/S模式已成为应用开发的主流,而在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用Excel打开(电信系统.银行系统).或者是:我们已经习惯用Excel打印.这样在我们实际的开发中,很多时候需要实现导入.导出Excel的应用. 目前,比较常用的实现Java导入.导出Excel的技术有两种Jakarta POI和Java Excel 下面我就分别讲解一下如何使用这两个技术实现导入.导出Excel 二.使用Jakarta POI导入.导出Excel Jakarta PO

JAVA导出EXCEL——POI(转)

一.所需JAR包 下载地址:http://pan.baidu.com/s/1eSOZF7G 密码:7277 二.导出类 package ExcelExport; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; im

Springmvc导出Excel(maven)

一.导入依赖 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-

springMVC导出excel并提供下载

一般创建HSSFWorkbook的过程写在业务层,这里放在controller中是因为目的是下载 @Controller public class PoiController { //返回一个ResponseEntity类型 @RequestMapping("poidownloadtest.html") public ResponseEntity<byte[]> poiDownloadTest() throws UnsupportedEncodingException{ /

SpringMVC导出Excel

import java.math.BigDecimal; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRespons

springMVC框架+POI组件导出Excel

目的:访问url(http://localhost:8080/POIOutputExcel/outputexcel.do)实现excel导出,效果图如下: 文件目录(配置文件就不多说了,跟前面的随笔一样一样的) User.java public class User { private Integer id; private String name; private Double cash; //此处省略getter/setter方法 } Datalist.java public class D

poi合并单元格同时导出excel

poi合并单元格同时导出excel POI进行跨行需要用到对象HSSFSheet对象,现在就当我们程序已经定义了一个HSSFSheet对象sheet. 跨第1行第1个到第2个单元格的操作为 sheet.addMergedRegion(new Region(0,(short)0,0,(short)1)); 跨第1行第1个到第2行第1个单元格的操作为 sheet.addMergedRegion(new Region(0,(short)0,1,(short)0)); 重点注意事项: 1.单元格CELL