java 导出excel

1.导出excel工具类

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelUtil {
    private static ExcelUtil instance;
    public static ExcelUtil getInstance() {
        if (instance == null) {
            instance = new ExcelUtil();
        }
        return instance;
    }
    /**
     * 执行excel导出
     * @param tmpPath(模板路径)
     * @param dataMap(数据)
     * @return
     */
    public String doExportExcel(String tmpPath,Map<String,Object> dataMap){
        String destFileName = System.getProperty("java.io.tmpdir")+"/"+ System.currentTimeMillis() + ".xls";
        XLSTransformer transformer = new XLSTransformer();
        OutputStream out = null;
        try {
//             File sourcefile = new File("E:\\云盘同步\\项目管理\\博尔信\\boerxin任务计划\\工作台\\资金测算\\customerDkInfo.xls");
//             FileInputStream is = new FileInputStream(sourcefile);

                HSSFWorkbook wb = (HSSFWorkbook) transformer.transformXLS(this.getClass().getClassLoader().getResourceAsStream(tmpPath),dataMap);
//                HSSFWorkbook wb = (HSSFWorkbook) transformer.transformXLS(is,dataMap);
            out = new BufferedOutputStream(new FileOutputStream(destFileName));
            if(out!=null){
                wb.write(out);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(out!=null){
                    out.close();
                } 
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return destFileName;
    }
}


2.打印页面代码(QueryPrinter.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    import="java.net.URLEncoder,
    java.io.*,org.apache.commons.io.IOUtils,java.util.*"%>

<%

                String destFileName = request.getParameter("destFileName");
                String fileName = request.getParameter("fileName");
                response.setContentType("application/vnd.ms-excel; charset=utf-8");
                response.setHeader("Content-disposition", "attachment;filename="+java.net.URLEncoder.encode(fileName,"UTF-8"));
                
                File file = new File(destFileName);
                FileInputStream fis = new FileInputStream(file);
                OutputStream output=response.getOutputStream();
                try {
                    IOUtils.copy(fis,output);
                } catch (IOException e) {
                    e.printStackTrace();
                }catch(Exception ex){
                    ex.printStackTrace();
                }
                finally{
                    fis.close();                    
                    output.close();    
                    file.delete();
                    out.clear();
                    out=null;
                }
%>

 

3.前端页面代码

exportExcel : function() {
        var me =this;
        var conditions = me.spRptCollectionToolBar.getConditions();   
        conditions=conditions?conditions:{};
        var myMask = new Ext.LoadMask({
            msg : "正在执行,请稍候......",
            target : me
            });
            myMask.show();
        $.ajax({  
            url :'spRptCollectionController/exportExcel.do',        
            type : "POST",  
            datatype:"json",  
            data : conditions,  
            success : function(data, stats) {  
                var resultFlag = data.resultFlag;
                if("fail"==resultFlag){
                    Ext.toastWarn(data.msg);
                    myMask.hide();
                }else{

//打印界面代码
                    var url = "resources/JspUtil/QueryPrinter.jsp?fileName="+encodeURI("业务指标执行情况表(一).xls")+"&destFileName="+encodeURI(data.msg);
                    location.href = url;
                    myMask.hide(); 
                }
                
                return false;
            },  
            error : function(data) {  
                Ext.toastWarn('导出失败!');
                myMask.hide();
                return false;
            }  
        });         
    },

4.controller 代码

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

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pearlsoft.report2.common.MaxDataDate;
import com.pearlsoft.report2.spRptCollection.service.SpRptCollectionService;
import com.pearlsoft.report2.spRptCollection.vo.SpRptCollectionVo;
import com.pearlsoft.system.common.utils.DateUtils;
import com.pearlsoft.system.common.utils.ResultCallback;


@Controller
@RequestMapping({"/spRptCollectionController"})
public class SpRptCollectionController  {
    
    protected final transient Log log = LogFactory.getLog(getClass());
    @Resource
    private SpRptCollectionService spRptCollectionService;     
    /**
     * 导出数据
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportExcel.do", produces = "application/json; charset=utf-8")
    @ResponseBody
    public ResultCallback exportExcel(SpRptCollectionVo spRptCollectionVo,HttpServletRequest request, HttpServletResponse response) {
        return spRptCollectionService.exportExcel(spRptCollectionVo,response);
    }
}

 

5.service代码

@Service("spRptCollectionService")
public class SpRptCollectionService extends CommonService {
    protected final transient Log log = LogFactory.getLog(getClass());
    @Resource
    private BeanMapperDozerImpl beanMapperDozerImpl;
    @Resource
    private PmsDeptService pmsDeptService;

    /**
     * 分页查询
     * 
     * @param criteria
     * @param start
     * @param limit
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<SpRptCollectionVo> findSpRptCollections(SpRptCollectionVo spRptCollectionVo) {
  
        return new ArrayList<SpRptCollectionVo>();
    }

    /**
     * 导出excel数据
     * 
     * @param personDepRankVo
     * @param response
     */
    public ResultCallback exportExcel(SpRptCollectionVo spRptCollectionVo,HttpServletResponse response) {
        ExcelUtil excelUtil = ExcelUtil.getInstance();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        // 查询数据
        List<SpRptCollectionVo> voList = new ArrayList<SpRptCollectionVo>();
        List<SpRptCollectionVo> rpts = this.findSpRptCollections(spRptCollectionVo);
        if (rpts != null && rpts.size() > 0) {
            for (SpRptCollectionVo vo : rpts) {
//                vo.setDataDate(DateUtils.getDateStr2Rod(vo.getDataDate()));
                voList.add(vo);
            }
        }

//导出数据
        dataMap.put("detailList", voList);

//导出模版路径和参数
        String filePath = excelUtil.doExportExcel("/exceltemplate/report/spRptCollection.xls", dataMap);
        return ResultCallback.success(filePath);

    }
}

6.excel模版(xxx.xls)

遍历循环数据:

<jx:forEach items="${detailList}" var="resultMap">
${resultMap.dataDate}
</jx:forEach>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值