1. 程式人生 > >JAVA:Excel匯入匯出詳解(3)--匯出

JAVA:Excel匯入匯出詳解(3)--匯出

Excel匯出

一、設定查詢條件

  1. 注意:無法通過Ajax下載

  2. jsp程式碼

    <form class="col-sm-2" action="/manage/order/download" method="post" onsubmit="checkForm()">
        <input type="submit" class="btn btn-success btn-sm " value="Excel匯出">
        <input id="mainorderNum1" name="mainorderNum" value="" style="display: none"></input>
        <input id="phone1" name="phone" value="" style="display: none"></input>
        <input id="deliveryState1" name="deliveryState" value="" style="display: none"></input>
        <input id="orderType1" name="orderType" value="" style="display: none"></input>
        <input id="orderState1" name="orderState" value="" style="display: none"></input>
        <input id="startTime1" name="startTime" value="" style="display: none"></input>
        <input id="endTime1" name="endTime" value="" style="display: none"></input>
        <input id="goodsId1" name="goodsId" value="" style="display: none"></input>
    </form>
    
  3. js程式碼

二、資料庫中查詢相應的資料

  1. 注意
  2. 程式碼
    /**
     * 下載檔案
     *
     * @param
     * @return
     */
    @RequestMapping(value = "download", method = RequestMethod.POST)
    public void downloadExp(HttpServletRequest request, HttpServletResponse response) {
        // 判斷檔案是否為空
        String flag = "02";//上傳標誌
        int resmsg = 0;
        DdOrderVo ddOrderVo = new DdOrderVo();
        //獲取查詢引數
        String mainorderNum = request.getParameter("mainorderNum");
        String phone = request.getParameter("phone");
        String deliveryState = request.getParameter("deliveryState");
        String orderType = request.getParameter("orderType");
        String orderState = request.getParameter("orderState");
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        String goodsId = request.getParameter("goodsId");
        try {

            if (mainorderNum != null && mainorderNum != "") {
                ddOrderVo.setMainorderNum(Long.parseLong(mainorderNum));
            }
            ddOrderVo.setPhone(phone);


            if (orderState != null && orderState != "") {
                ddOrderVo.setOrderState(Integer.parseInt(orderState));
            }
            if (goodsId != null && goodsId != "") {
                ddOrderVo.setGoodsId(Long.parseLong(goodsId));
            }
            if (orderType != null && orderType != "") {
                ddOrderVo.setOrderType(Integer.parseInt(orderType));
            }
            if (deliveryState != null && deliveryState != "") {
                ddOrderVo.setDeliveryState(Integer.parseInt(deliveryState));
            }
            if (startTime != null && startTime != "") {
                ddOrderVo.setStartTime(Timestamp.valueOf(startTime));
            }
            if (endTime != null && endTime != "") {
                ddOrderVo.setEndTime(Timestamp.valueOf(endTime));
            }

            Page<DdOrderVo> page = new Page<>();
            page.setPageSize(99999);
            page.setPageNum(1);
            Page<DdOrderVo> list = ddOrderService.findByPage(ddOrderVo, page);
            List<ExcelSheetPO> excelSheets = new ArrayList<>();
            ExcelSheetPO excelSheetPO = new ExcelSheetPO();
            List<List<Object>> datalist = new ArrayList<>();
//            List<String> firstline = new ArrayList<>();
            String[] firstline = new String[7];
            firstline[0] = "主訂單號";//mainorderNum
            firstline[1] = "買家姓名";//addressee
            firstline[2] = "買家電話";//phone
            firstline[3] = "買家地址";//province city district address
            firstline[4] = "訂單商品";//goodsName	goodsNum
            firstline[5] = "快遞型別";//expressType
            firstline[6] = "面單號";//slogisticCode
//            datalist.add(firstline);
            for (DdOrderVo d : list.getResults()) {
                List<Object> line = new ArrayList<>();
                line.add(0, d.getMainorderNum());//mainorderNum
                line.add(1, d.getAddressee());//addressee
                line.add(2, d.getPhone());//phone
                line.add(3, d.getProvince() + d.getCity() + d.getDistrict() + d.getAddress());//province city district address
                //獲得訂單商品
                DdOrderGoodsVo ddOrderGoodsVo = new DdOrderGoodsVo();
                ddOrderGoodsVo.setOrderNum(d.getOrderNum());
                List<DdOrderGoodsVo> glist = ddOrderGoodsService.find(ddOrderGoodsVo);
                String gString = "";
                for (DdOrderGoodsVo g : glist) {
                    gString += g.getGoodsName() + "(" + g.getGoodsNum() + ")";
                }
                line.add(4, gString);//goodsName	goodsNum
                line.add(5, d.getExpressType());//expressType"快遞型別"
                line.add(6, d.getSlogisticCode());//slogisticCode"面單號"
                datalist.add(line);
                resmsg++;
            }
            excelSheetPO.setHeaders(firstline);
            excelSheetPO.setTitle("訂單列表");
            excelSheetPO.setDataList(datalist);
            String realPath = request.getRealPath("");
            String filePath = realPath + "/excelOut.xls";
//            String filePath = "C://Users/Administrator/Desktop/excelOut.xls";
            excelSheets.add(excelSheetPO);
            createWorkbookAtDisk(V2003, excelSheets, filePath);
            try {
                filePath = realPath;
                String downloadName = "order.xls";
                String fileName = "/excelOut.xls";
                FileUtil.downloadFile(filePath, downloadName, fileName, request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
            flag = "01";//上傳成功

        } catch (Exception e) {
            flag = "03";//上傳出錯
            e.printStackTrace();
        }
    }

三、將資料寫入Excel

  1. 注意
    分別呼叫以下方法將查詢到的資料寫到excel中
    excelSheetPO.setHeaders(firstline);
    excelSheetPO.setTitle(“訂單列表”);
    excelSheetPO.setDataList(datalist);
  2. 程式碼
            List<ExcelSheetPO> excelSheets = new ArrayList<>();
            ExcelSheetPO excelSheetPO = new ExcelSheetPO();
            List<List<Object>> datalist = new ArrayList<>();
//            List<String> firstline = new ArrayList<>();
            String[] firstline = new String[7];
            firstline[0] = "主訂單號";//mainorderNum
            firstline[1] = "買家姓名";//addressee
            firstline[2] = "買家電話";//phone
            firstline[3] = "買家地址";//province city district address
            firstline[4] = "訂單商品";//goodsName	goodsNum
            firstline[5] = "快遞型別";//expressType
            firstline[6] = "面單號";//slogisticCode
//            datalist.add(firstline);
            for (DdOrderVo d : list.getResults()) {
                List<Object> line = new ArrayList<>();
                line.add(0, d.getMainorderNum());//mainorderNum
                line.add(1, d.getAddressee());//addressee
                line.add(2, d.getPhone());//phone
                line.add(3, d.getProvince() + d.getCity() + d.getDistrict() + d.getAddress());//province city district address
                //獲得訂單商品
                DdOrderGoodsVo ddOrderGoodsVo = new DdOrderGoodsVo();
                ddOrderGoodsVo.setOrderNum(d.getOrderNum());
                List<DdOrderGoodsVo> glist = ddOrderGoodsService.find(ddOrderGoodsVo);
                String gString = "";
                for (DdOrderGoodsVo g : glist) {
                    gString += g.getGoodsName() + "(" + g.getGoodsNum() + ")";
                }
                line.add(4, gString);//goodsName	goodsNum
                line.add(5, d.getExpressType());//expressType"快遞型別"
                line.add(6, d.getSlogisticCode());//slogisticCode"面單號"
                datalist.add(line);
                resmsg++;
            }
            excelSheetPO.setHeaders(firstline);
            excelSheetPO.setTitle("訂單列表");
            excelSheetPO.setDataList(datalist);
            String realPath = request.getRealPath("");
            String filePath = realPath + "/excelOut.xls";
//            String filePath = "C://Users/Administrator/Desktop/excelOut.xls";
            excelSheets.add(excelSheetPO);
            createWorkbookAtDisk(V2003, excelSheets, filePath);
                        try {
                filePath = realPath;
                String downloadName = "order.xls";
                String fileName = "/excelOut.xls";
                FileUtil.downloadFile(filePath, downloadName, fileName, request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
  1. 程式碼

四、將Excel下載至本地

  1. 注意
  2. 程式碼
	/**
	 * 下載檔案,是向頁面輸出流,不返回流
	 * @param filePath 檔案伺服器儲存目錄
	 * @param downloadName 下載檔案儲存的檔名
	 * @param fileName 伺服器儲存檔名
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("static-access")
	public static void downloadFile(String filePath,String downloadName,String fileName,HttpServletRequest request,HttpServletResponse response) throws Exception{

		fileName = new java.net.URLDecoder().decode(fileName, "utf-8");
		downloadName = new java.net.URLDecoder().decode(downloadName, "utf-8");
		String path = filePath+fileName;

		response.setContentType("application/octet-stream;charset=UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + new String((downloadName).getBytes("GBK"), "iso8859-1"));
		try {
			//以流的形式下載檔案
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();

			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

  1. 程式碼