java方式實現保存Excel格式數據


在瀏覽器中下載查詢到的數據庫數據,全部保存到SXSSFWorkbook(工作簿)中的`Sheet sheet = xswb.createSheet();`(工作表)

方式一:通過JDBCUtils的方式導出

(優點:

1、可以不用一個個去設置excel表格的頭行字段

2、可以適用於查詢不通的表,不用處理各個表字段不同的問題

 

 

 

  1. 前端發送請求到servlet,把需要的查詢條件(參數)傳遞到后台(此步驟省略...)

  2. 接收參數,通過jdbc的方法(jdbc連接數據庫步驟省略...)查詢數據庫數據,`getMetaData()`直接操作數據庫便捷,但效率可能較低

  3. 通過response對象獲得輸出流,將SXSSFWorkbook寫入到瀏覽器

    	//jdbc方式查詢數據保存到excel
    	public EiInfo downData(EiInfo inInfo) {
    		String sql = convertToSQL(date_PRC1, date_PRC2, type);
    		String sheetName = convertToSheetName(type);
    		HttpServletResponse response =(HttpServletResponse) inInfo.get("response");
    		SXSSFWorkbook xswb;
    		try {
    			// 創建xlsx
    			xswb = createXlsx(sql, sheetName);
    			
    			// 生成文件
    			response.setContentType("application/vnd.ms-excel");
    			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(sheetName, "utf-8"));
    			OutputStream outputStream;
    			outputStream = response.getOutputStream();
    			xswb.write(outputStream);
    			outputStream.flush();
    			outputStream.close();
    		} catch (Exception e) {
    			e.printStackTrace();
    			inInfo.set("status", false);
    			inInfo.set("msg", "導出失敗!");
    			return inInfo;
    		}
    		return inInfo;
    	}
    

      

/*
* 傳入sql語句,和需要的命名
* 返回工作簿對象
*/
private
SXSSFWorkbook createXlsx(String sql, String sheetName) throws Exception { SXSSFWorkbook xswb = null; Connection con = null; Statement st = null; ResultSet rs = null; try { con = JDBCUtils.getConnection(); st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); xswb = new SXSSFWorkbook(); // 創建工作表 Sheet sheet = xswb.createSheet(); xswb.setSheetName(0, sheetName); // 查詢數據 rs = st.executeQuery(sql); System.out.println(rs); ResultSetMetaData metaData = rs.getMetaData(); int columnCount = metaData.getColumnCount(); // 創建表頭 Row head = sheet.createRow(0); for (int i = 0; i < columnCount; i++) { Cell cell = head.createCell(i); cell.setCellValue(metaData.getColumnName(i + 1)); } // 獲取總行數 rs.last(); int rowCount = rs.getRow(); rs.beforeFirst(); // 創建標題 for (int i = 1; i <= rowCount; i++) { rs.next(); Row row = sheet.createRow(i); for (int j = 0; j < columnCount; j++) { Cell cell = row.createCell(j); cell.setCellValue(rs.getString(j + 1)); } } } catch (Exception e) { throw new Exception(e); } finally { JDBCUtils.colseResource(con, st, rs); } return xswb; }

 方式二:通過MyBatis的xml放式導出數據(我覺得適用於條件只查詢一張表數據) 

          @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          if (null == req || null == resp){
            return;
          }

          ......
          省略 獲得JSONArray格式的數據
          //二、 將數據轉成excel req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("application/x-download"); String fileName = convertToSheetName(type); fileName = URLEncoder.encode(fileName, "UTF-8"); resp.addHeader("Content-Disposition", "attachment;filename=" + fileName); // 第一步:定義一個新的工作簿 XSSFWorkbook wb = new XSSFWorkbook(); // 第二步:創建一個Sheet頁 XSSFSheet sheet = wb.createSheet("startTimeendTime"); sheet.setDefaultRowHeight((short) (2 * 256));//設置行高 sheet.setColumnWidth(0, 6000);//設置列寬 sheet.setColumnWidth(3,5500); sheet.setColumnWidth(4,5500); sheet.setColumnWidth(8,5500); sheet.setColumnWidth(9,5500); sheet.setColumnWidth(10,5500); sheet.setColumnWidth(11,5500); XSSFFont font = wb.createFont(); font.setFontName("宋體"); font.setFontHeightInPoints((short) 16); XSSFRow row = sheet.createRow(0); XSSFCell cell = row.createCell(0); cell.setCellValue("記錄ID"); cell = row.createCell(1); cell.setCellValue("賬套"); cell = row.createCell(2); cell.setCellValue("日期"); cell = row.createCell(3); cell.setCellValue("產品屬性名稱"); cell = row.createCell(4); cell.setCellValue("庫存類型名稱"); cell = row.createCell(5); cell.setCellValue("大類名稱"); cell = row.createCell(6); cell.setCellValue("中類名稱"); cell = row.createCell(7); cell.setCellValue("物料名稱"); // cell = row.createCell(8); // cell.setCellValue("廠別名稱"); // cell = row.createCell(9); // cell.setCellValue("庫存分類名稱"); cell = row.createCell(8); cell.setCellValue("部門名稱"); // cell = row.createCell(11); // cell.setCellValue("庫齡名稱"); // cell = row.createCell(12); // cell.setCellValue("內外銷名稱"); // cell = row.createCell(13); // cell.setCellValue("庫區名稱"); // cell = row.createCell(14); // cell.setCellValue("期貨現貨名稱"); // cell = row.createCell(15); // cell.setCellValue("付款方式名稱"); // cell = row.createCell(16); // cell.setCellValue("產品流向名稱"); // cell = row.createCell(17); // cell.setCellValue("庫存標志名稱"); cell = row.createCell(9); cell.setCellValue("庫存重量"); cell = row.createCell(10); cell.setCellValue("庫存金額"); cell = row.createCell(11); cell.setCellValue("市場金額"); XSSFRow rows; XSSFCell cells; for(int i = 0; i < listArray.size(); i++) { // 第三步:在這個sheet頁里創建一行 rows = sheet.createRow(i+1); // 第四步:在該行創建一個單元格 cells = rows.createCell(0); // 第五步:在該單元格里設置值 cells.setCellValue(listArray.getJSONObject(i).get("REC_ID").toString()); cells = rows.createCell(1); cells.setCellValue(listArray.getJSONObject(i).get("ACCOUNT").toString()); cells = rows.createCell(2); cells.setCellValue(listArray.getJSONObject(i).get("DATE_PRC").toString()); cells = rows.createCell(3); cells.setCellValue(listArray.getJSONObject(i).get("PROD_ATTR_NAME").toString()); cells = rows.createCell(4); cells.setCellValue(listArray.getJSONObject(i).get("INV_TYPE_NAME").toString()); cells = rows.createCell(5); cells.setCellValue(listArray.getJSONObject(i).get("BIGCLASS_NAME").toString()); cells = rows.createCell(6); cells.setCellValue(listArray.getJSONObject(i).get("MIDCLASS_NAME").toString()); cells = rows.createCell(7); cells.setCellValue(listArray.getJSONObject(i).get("MAT_NAME").toString()); // cells.setCellValue(listArray.getJSONObject(i).get("FACTORY_NAME").toString()); // cells.setCellValue(listArray.getJSONObject(i).get("INV_CAT_NAME").toString()); cells = rows.createCell(8); cells.setCellValue(listArray.getJSONObject(i).get("DEPT_NAME").toString()); // cells.setCellValue(listArray.getJSONObject(i).get("INV_AGE_NAME").toString()); // cells.setCellValue(listArray.getJSONObject(i).get("DOMESTIC_EXP_NAME").toString()); // cells.setCellValue(listArray.getJSONObject(i).get("STORE_NAME").toString()); // cells.setCellValue(listArray.getJSONObject(i).get("FUTURES_SPOT_NAME").toString()); // cells.setCellValue(listArray.getJSONObject(i).get("PAY_METHOD_NAME").toString()); // cells.setCellValue(listArray.getJSONObject(i).get("PROD_FLOW_NAME").toString()); // cells.setCellValue(listArray.getJSONObject(i).get("INV_FLAG_NAME").toString()); cells = rows.createCell(9); cells.setCellValue(listArray.getJSONObject(i).get("INV_WT").toString()); cells = rows.createCell(10); cells.setCellValue(listArray.getJSONObject(i).get("INV_AMT").toString()); cells = rows.createCell(11); cells.setCellValue(listArray.getJSONObject(i).get("MARKET_AMT").toString()); } try { OutputStream out = resp.getOutputStream(); wb.write(out); out.flush(); out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }

  

 


免責聲明!

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



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