1. 程式人生 > >註解式開發利用反射呼叫物件屬性並上傳

註解式開發利用反射呼叫物件屬性並上傳

 public void customExport(HttpServletRequest request,String titles, String columns, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, IOException {
        // 根據欄位列表查詢使用者集合
        List<User> users = userService.queryUesrByColumns(columns);

        Workbook workbook = new HSSFWorkbook();

        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setDataFormat(workbook.getCreationHelper().createDataFormat().getFormat("yyyy-MM-dd"));

        Sheet sheet = workbook.createSheet("使用者資訊");
        Row row = sheet.createRow(0);
        // 將使用者資訊匯出到Excel表格中
        // Excel=標題行+資料行
        String[] title = titles.split(",");
        for (int i = 0; i < title.length; i++) {
            Cell cell = row.createCell(i);
            cell.setCellValue(title[i]);
        }

        // [id,name,age,birthday]
        // get+Cname = get方法名
        String[] column = columns.split(",");

        // 資料行
        for (int i = 1; i <= users.size(); i++) {
            row = sheet.createRow(i);

            User user = users.get(i - 1);
            Class<? extends User> c = user.getClass();

            for (int j = 0; j < column.length; j++) {

                Cell cell = row.createCell(j);

                // id ---> Id
                String cName = column[j];
                String getMethodName = "get" + cName.substring(0, 1).toUpperCase() + cName.substring(1, cName.length());

                Method method = c.getMethod(getMethodName, null);
                // get方法對應的返回值
                Object obj = method.invoke(user, null);
                if (obj == null) {
                    continue;
                }
                if (obj instanceof Date) {
                    cell.setCellStyle(cellStyle);
                    cell.setCellValue((Date) obj);
                } else {
                    cell.setCellValue(obj.toString());
                }
            }
        }



        String realPath = request.getSession().getServletContext().getRealPath("//userexl");
        workbook.write(new FileOutputStream(realPath+"\\test5.xls"));
        workbook.close();
        FileInputStream fileInputStream = new FileInputStream(new File(realPath, "test5.xls"));
        response.setContentType("application/x-msdownload;");
        response.setHeader("Content-disposition", "attachment; filename=" + new String("test5.xls".getBytes("utf-8"), "ISO8859-1"));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[2048];
        int len;
        while (true){
            len = fileInputStream.read(b);
            if(len==-1) break;;
            outputStream.write(b,0,len);
        }
        outputStream.close();
        fileInputStream.close();
    }