从java里导出数据成excel到web,下载

项目的所用的框架:spring+springmvc+mybatis
导入依赖.直接复制到pom.xml


<dependency>  
    <groupId>org.apache.poi</groupId>  
    <artifactId>poi</artifactId>  
    <version>3.8</version>  
    <exclusions>  
        <exclusion>  
            <artifactId>commons-codec</artifactId>  
            <groupId>commons-codec</groupId>  
        </exclusion>  
    </exclusions>  
</dependency>  
<dependency>  
    <groupId>org.apache.poi</groupId>  
    <artifactId>poi-ooxml</artifactId>  
    <version>3.8</version>  
</dependency>

前端的主要代码

<button class="btn btn-primary btn-lg" id="export">下载报表</button>
.
.
.
$(function(){
			//$("#deviceExport").on("click",doImport)
			$("#export").on("click",doImport)
			
			
		})

		function doImport(){
			if(!confirm("是否开始下载"))return;
			location.href="export";
		}

DAO Service,代码省略.

package com.cy.pj.goods.util;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelUtil {
	 public static HSSFWorkbook getHSSFWorkbook(String sheetName,String []title,String [][]values, HSSFWorkbook wb){
		 
	        // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
	        if(wb == null){
	            wb = new HSSFWorkbook();
	        }
	 
	        // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
	        HSSFSheet sheet = wb.createSheet(sheetName);
	 
	        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
	        HSSFRow row = sheet.createRow(0);
	 
	        // 第四步,创建单元格,并设置值表头 设置表头居中
	        HSSFCellStyle style = wb.createCellStyle();
	        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
	 
	        //声明列对象
	        HSSFCell cell = null;
	 
	        //创建标题
	        for(int i=0;i<title.length;i++){
	            cell = row.createCell(i);
	            cell.setCellValue(title[i]);
	            cell.setCellStyle(style);
	        }
	 
	        //创建内容
	        for(int i=0;i<values.length;i++){
	            row = sheet.createRow(i + 1);
	            for(int j=0;j<values[i].length;j++){
	                //将内容按顺序赋给对应的列对象
	                row.createCell(j).setCellValue(values[i][j]);
	            }
	        }
	        return wb;
	    }

}

controller代码

package com.cy.pj.goods.controller;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

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

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cy.pj.goods.entity.Good;
import com.cy.pj.goods.util.ExcelUtil;
import com.cy.pj.service.GoodsService;

@Controller
@RequestMapping("/")
public class GoodsController {
	@Autowired
	private GoodsService goodsService;
	// 访问html页面
	@RequestMapping("index")
	public String doGoodsUI(Model model) {
		List<Good> list = goodsService.findObject();
		model.addAttribute("list", list);
		return "goods";
	}

	
	}
	@RequestMapping("export")
	@ResponseBody
	public void export(HttpServletRequest request,HttpServletResponse response) 
			throws Exception {
		//获取数据
		List<Good> list = goodsService.findObject();
		//excel标题
		String[] title = {"id","name","remark","createdTime"};

		//excel文件名
		String fileName = "商品信息表"+System.currentTimeMillis()+".xls";

		//sheet名
		String sheetName = "商品信息表";
		String[][] content = new String[list.size()+1][title.length];
		for (int i = 0; i < list.size(); i++) {
			Good obj = list.get(i);
			content[i][0] = obj.getId()+"";
			content[i][1] = obj.getName();
			content[i][2] = obj.getRemark();
			content[i][3] = obj.getCreatedTime().toString();
		}

		//创建HSSFWorkbook
		HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

		//响应到客户端
		try {
			this.setResponseHeader(response,fileName);
			OutputStream os = response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	//发送响应流方法
	public void setResponseHeader(HttpServletResponse response, String fileName) {
	    try {
	        try {
	            fileName = new String(fileName.getBytes(),"ISO8859-1");
	        } catch (UnsupportedEncodingException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	        }
	        response.setContentType("application/octet-stream;charset=ISO8859-1");
	        response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
	        response.addHeader("Pargam", "no-cache");
	        response.addHeader("Cache-Control", "no-cache");
	    } catch (Exception ex) {
	        ex.printStackTrace();
	    }
	}
	
}


整个导出的流程大致就这样,细节隐藏了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值