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 Datalist {
    //這里不走數據庫,直接模擬數據庫查詢結果
    public List<User> getUsers(int n){
        List<User> list = new ArrayList<User>();
        for (int i = 0; i < n; i++) {
            User user = new User();
            user.setId(i);
            user.setName("xiaoming"+i);
            user.setCash(1000.0+i);
            list.add(user);
        }
        return list;
    }
    
}

BeanToMap.java

public class BeanToMap<T> {
    
    public Map<String,Object> getMap(T entity){
        Field[] fields = entity.getClass().getDeclaredFields();
        Map<String,Object> map = new HashMap<String,Object>();
        for (int i = 0; i < fields.length; i++) {
            String methodName = getMethodName(fields[i].getName());
            try {
                Method method = entity.getClass().getMethod(methodName);
                map.put(fields[i].getName(),method.invoke(entity));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return map;
    }

    public String getMethodName(String fieldName){
        byte[] buffer = fieldName.getBytes();
        buffer[0] = (byte)(buffer[0]-32);
        String name = new String(buffer);
        return "get"+name;
    }
}

PoiExcelExport.java

public class PoiExcelExport<T> {
    // excle導出名稱
    private String fileName;
    // excel 表頭
    private String[] heads;
    // excel 列
    private String[] cols;
    // 設置數值型的列 從0開始計數
    private int[] numerics;
    //list集合
    private List<T> list;
    // 輸出流
    private OutputStream out;
    // 構造函數
    public PoiExcelExport(String fileName, String[] heads, String[] cols, List<T> list, OutputStream out) {
        this.fileName = fileName;
        this.heads = heads;
        this.cols = cols;
        this.list = list;
        this.out = out;
    }

    // 構造函數 帶數字類型
    public PoiExcelExport(String fileName, String[] heads, String[] cols, List<T> list, int[] numerics, OutputStream out) {
        this.fileName = fileName;
        this.heads = heads;
        this.cols = cols;
        this.list = list;
        this.numerics = numerics;
        this.out = out;
    }

    public void exportExcel() {
        HSSFWorkbook hssfworkbook = new HSSFWorkbook(); // 創建一個excel對象
        for (int i = 0; i <= (list.size() / 65535); i++) {
            HSSFSheet hssfsheet = hssfworkbook.createSheet(); // 工作表
            // 工作表名稱
            hssfworkbook.setSheetName(i, fileName.replace(".xls", "") + "(第" + (i + 1) + "頁)");
            int beginRows = 65535 * i;
            int endRows = (list.size() > 65535 * (i + 1)) ? 65535 * (i + 1) - 1 : list.size() - 1;
            HSSFRow hssfrowHead = hssfsheet.createRow(0);
            // 輸出excel 表頭
            if (heads != null && heads.length > 0) {
                for (int h = 0; h < heads.length; h++) {
                    HSSFCell hssfcell = hssfrowHead.createCell(h,Cell.CELL_TYPE_STRING);
                    hssfcell.setCellValue(heads[h]);
                }
            }
            // 要設置數值型 列表
            HSSFCellStyle cellstyle = hssfworkbook.createCellStyle();
            cellstyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("##0"));
            // 是否是數值型
            boolean isnum = false;
            // 輸出excel 數據
            for (int curRow = beginRows; curRow <= endRows; curRow++) {
                // 獲取數據
                BeanToMap<T> btm = new BeanToMap<T>();
                Map<String,Object> hm = btm.getMap(list.get(curRow));
                // 創建excel行 表頭1行 導致數據行數 延后一行
                HSSFRow hssfrow = hssfsheet.createRow(curRow % 65535 + 1);
                // 讀取數據值
                for (int k = 0; k < cols.length; k++) {
                    HSSFCell hssfcell = hssfrow.createCell(k);
                    // hssfcell.setCellValue(hm.get(cols[k])==null?"":hm.get(cols[k]).toString());
                    isnum = false;
                    for (int z = 0; z < numerics.length; z++) {
                        if (numerics[z] == k) {
                            isnum = true;
                            break;
                        }
                    }

                    if (isnum) {
                        if (hm.get(cols[k]) == null || hm.get(cols[k]).equals("")) {

                        } else {
                            hssfcell.setCellStyle(cellstyle);
                            hssfcell.setCellValue(Double.parseDouble(
                                    hm.get(cols[k]) == null ? "" : hm.get(cols[k]).toString().replace(",", "")));
                        }
                    } else {
                        hssfcell.setCellValue(hm.get(cols[k]) == null ? "" : hm.get(cols[k]).toString());
                    }
                }
            }

        }
        // excel生成完畢,寫到輸出流
        try {
            hssfworkbook.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

ServletUtil.java

public class ServletUtil {
    private String fileName;
    private HttpServletRequest req;
    private HttpServletResponse resp;
    public OutputStream getOut(){
        try {
            return resp.getOutputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }
    public ServletUtil(HttpServletResponse resp){
        this.resp = resp;
    }
    public ServletUtil(String fileName,
            HttpServletRequest req,
            HttpServletResponse resp){
        this.fileName = fileName;
        this.req = req;
        this.resp = resp;
    }
    public void poiExcelServlet(){
        resp.setContentType("application/vnd.ms-excel");
        String contentDisposition = "";
        try {
            if (req.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
                contentDisposition = "attachment; filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1")
                        + "\"";// firefox瀏覽器
            } else {
                contentDisposition = "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"";// IE瀏覽器
            }
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        resp.setHeader("Content-Disposition", contentDisposition);
        resp.setCharacterEncoding("UTF-8");
    }
}

UserController.java

@Controller
public class UserController {
    
    @RequestMapping(value = "/outputexcel.do")
    public void showImgCode(HttpServletRequest req, 
             HttpServletResponse resp) {
        String fileName = "springMVC導出excel小練習";
        
        ServletUtil su = new ServletUtil(fileName, req, resp);
        su.poiExcelServlet();
        
        String[] heads = {"id號","姓名","身價(元)"};
        String[] cols = {"id","name","cash"};
        int[] numerics = {2};
        List<User> list = new Datalist().getUsers(70000);//獲取1000條樣例數據
        
        ServletUtil suresp = new ServletUtil(resp);
        PoiExcelExport<User> pee = new PoiExcelExport<User>(fileName, heads, cols, list, numerics, suresp.getOut());
        pee.exportExcel();
    }
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM