POI 實現Excel 導出案例分析

無論使用poi還是使用jxl導出excel都需要用到流
一種是outputstrean,另一種fileoutputstream
第一種:

如果想要彈出保存的提示框必須加入下列三句
response.setContentType("application/vnd.ms-excel; charset=utf-8");
response.setHeader("Content-Disposition","attachment;filename="+filename);
response.setCharacterEncoding("utf-8");
OutputStream os=response.getOutputStream();
在使用第一種的時候,我用的ajax請求。導致excel無法導出,最後我直接請求可以導出(document.location.href="${pageContext.request.contextPath}/tran/export.do?")
原因是:ajax也用到了response.getWriter()方法 要將 數據結果回傳,這裏 我雖然 放棄了 回傳的寫入流writer 參數, 但是ajax還是會默認的去掉用,把流已經佔用了,當然返回不了任何東西了。
第二種:
action中使用FileOutputStream fos=new FileOutputStream(file);
此時可以使用ajax請求,在導出成功後返回文件路徑,在頁面中使用window.open(path);即可打開導出的excel文件

wKiom1lnIAbADwAhAAD7xqMY0tE808.png-wh_50

jsp頁面:

     function exportExcel(){
         var ids = [];
         var rows = $('#dbgrid').datagrid('getSelections');
         if (rows.length < 1) {
             $.messager.alert('提示', '<br>請選中您要導出的記錄!', 'info');
             return;
         }
         for (var i = 0; i < rows.length; i++) {
             ids.push(rows[i][getId()]);
         }
         //console.log("---ids---"+ids.join(","))
         location.href = "${path}/admin/export/export.do?ids="+ids.join(",");
     } 


Action:


package com.shangyu.action.dsz;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.shangyu.common.util.SpringContextHelper;
import com.shangyu.entity.dsz.DispatchOrder;
import com.shangyu.entity.dsz.DispatchParam;
import com.shangyu.service.dsz.DispatchOrderService;
import com.shangyu.service.dsz.DispatchParamService;
import com.shangyu.service.system.SysUserService;

/**
 * @desc 導出Excel
 * @author hykang
 *
 */

@Controller
@RequestMapping("/admin/export")
public class ExportController {

    @Resource
    private DispatchOrderService dispatchOrderService;
    @Resource
    private DispatchParamService dispatchParamService;
    @Resource
    private SysUserService sysUserService;
    
    @SuppressWarnings("deprecation")
    @RequestMapping("export.do")
    public void exportList(HttpServletRequest req,HttpServletResponse response) throws Exception{
        String ids = req.getParameter("ids");
        String[] str=ids.split(",");
        String[] ids1=new String[str.length];
        List<DispatchOrder> orderlist = new ArrayList<>();
        for(int i=0;i<str.length;i++){
            ids1[i]=str[i];
            DispatchOrder entity = dispatchOrderService.getById(ids1[i]);
            orderlist.add(entity);
        }
        
        HSSFWorkbook wb=new HSSFWorkbook();
        HSSFSheet sheet=wb.createSheet("派工單數據彙總");
        HSSFRow row=sheet.createRow(0);
        //創建單元格,並設置值表頭 設置表頭居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);    // 創建一個居中格式
        //style.setWrapText(true);//允許自動換行
        
        //表頭
        String[] headers={"派工單編號","部門名稱","負責人","創建時間","派工時間","合計工時"};
         //填充表頭
        for (short i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        
        for (int i = 0; i < orderlist.size(); i++) {
            row = sheet.createRow(i + 1);
            row.setHeightInPoints(18); //設置行高
            
            DispatchOrder record = orderlist.get(i);
            String createtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(record.getCreateTime());
            String disptchtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(record.getDispatchTime());
            
            row.createCell(0).setCellValue(record.getDispatchCode());
            sheet.setColumnWidth(0, (record.getDispatchCode().getBytes().length + 4)*256);
            
            if(org.apache.commons.lang3.StringUtils.isNotEmpty(getName(record.getDeptName()) )){
                row.createCell(1).setCellValue(getName(record.getDeptName()));
                sheet.setColumnWidth(0, (record.getDispatchCode().getBytes().length + 4)*256);
            }
            if(org.apache.commons.lang3.StringUtils.isNotEmpty(getName(record.getManager()))){
                row.createCell(2).setCellValue(getName(record.getManager()));
                sheet.setColumnWidth(1, (getName(record.getDeptName()).getBytes().length + 4)*256);
            }
            row.createCell(3).setCellValue(createtime);
            sheet.setColumnWidth(3, (createtime.getBytes().length + 4)*256);
            
            row.createCell(4).setCellValue(disptchtime);
            sheet.setColumnWidth(4, (disptchtime.getBytes().length + 4)*256);
            
            if(org.apache.commons.lang3.StringUtils.isNotEmpty(String.valueOf(record.getTotalWork()))){
                row.createCell(5).setCellValue(String.valueOf(record.getTotalWork()));
            }
            
        }
          
        //sheet.setDefaultColumnWidth(18); //爲全部列的列寬設置默認值
        String filename=new SimpleDateFormat("yyyy年MM月dd日 HH時mm分ss秒").format(new Date())+".xls";
        //response.reset();//一般情況可以不寫
        //response.setHeader("Content-disposition", "attachment;filename="+toUtf8String(fileName));//字符串轉碼
        response.setHeader("Content-Disposition", "attachment;filename="
                +new String(filename.getBytes("utf-8"),"iso8859-1"));
        response.setHeader("Connection", "close");
        response.setHeader("Content-Type", "application/vnd.ms-excel");
        wb.write(response.getOutputStream());

     }
    
    public static String toUtf8String(String s){
        StringBuffer sb = new StringBuffer();
          for (int i=0;i<s.length();i++){
             char c = s.charAt(i);
             if (c >= 0 && c <= 255){sb.append(c);}
           else{
           byte[] b;
            try { b = Character.toString(c).getBytes("utf-8");}
            catch (Exception ex) {
                System.out.println(ex);
                     b = new byte[0];
            }
               for (int j = 0; j < b.length; j++) {
                int k = b[j];
                 if (k < 0) k += 256;
                 sb.append("%" + Integer.toHexString(k).toUpperCase());
                 }
        }
     }
     return sb.toString();
   }
    
    public static String getName(String id){
        String name = "";
        DispatchParamService dispatchParamService = SpringContextHelper.getBean(DispatchParamService.class);
        try {
            DispatchParam param = dispatchParamService.getById(id);
            name = param.getParamName();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return name;
    }
    
}


參考文檔:

Springmvc和poi3.9導出excel並彈出下載框

利用POI 導出EXCEL,彈出保存框




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章