1. 程式人生 > >用Java實現下載功能,並儲存到excel表格中

用Java實現下載功能,並儲存到excel表格中

一,通過POI介面,將從資料庫中查出的資訊以excel的形式儲存

1.首先寫一個Utils類
public class DownPOIUtils {

	/**
	 * 
	 * @param response:響應物件,型別是HttpServletResponse
	 * @param map:要封裝的資訊的map容器,其中key為Student,value為String型別的,在這裡代表分數
	 * @throws Exception:代表異常物件
	 */
	public static void downPoi(HttpServletResponse response,
			Map<Student, String> map) throws Exception {
		String fname = "detial" + getTimeStamp();// Excel檔名
		OutputStream os = response.getOutputStream();// 取得輸出流
		response.reset();// 清空輸出流
		response.setHeader("Content-disposition", "attachment; filename="
				+ fname + ".xls"); // 設定輸出檔案頭,該方法有兩個引數,分別表示應答頭的名字和值。
		response.setContentType("application/msexcel");
		try {
			new DownPOIUtils().new POIS().createFixationSheet(os, map);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 該方法用來產生一個時間字串(即:時間戳)
	 * @return
	 */
	public static String getTimeStamp() {
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd hh:MM:ss");
		Date date = new Date();
		return dateFormat.format(date);
	}
2.編寫POI程式碼
class POIS {

		public void createFixationSheet(OutputStream os,
				Map<Student, String> student) throws Exception {
			// 建立工作薄
			HSSFWorkbook wb = new HSSFWorkbook();
			// 在工作薄上建一張工作表
			HSSFSheet sheet = wb.createSheet();
			HSSFRow row = sheet.createRow((short) 0);
			sheet.createFreezePane(0, 1);
			cteateCell(wb, row, (short) 0, "學號");
			cteateCell(wb, row, (short) 1, "姓名");
			cteateCell(wb, row, (short) 2, "性別");
			cteateCell(wb, row, (short) 3, "班級");
			cteateCell(wb, row, (short) 4, "分數");
			int i = 0;
			Set<Student> keySet = student.keySet();
			Iterator<Student> iterator = keySet.iterator();
			while (iterator.hasNext()) {
				HSSFRow rowi = sheet.createRow((short) (++i));
				Student student2 = iterator.next();
				for (int j = 0; j < 4; j++) {
					cteateCell(wb, rowi, (short) 0, student2.getId());
					cteateCell(wb, rowi, (short) 1, student2.getName());
					cteateCell(wb, rowi, (short) 2, student2.getSex());
					cteateCell(wb, rowi, (short) 3, student2.getGrade());
					cteateCell(wb, rowi, (short) 4, student.get(student2));
				}
			}
			wb.write(os);
			os.flush();
			os.close();
			System.out.println("檔案生成");

		}

		@SuppressWarnings("deprecation")
		private void cteateCell(HSSFWorkbook wb, HSSFRow row, short col,
				String val) {
			HSSFCell cell = row.createCell(col);
			cell.setCellValue(val);
			HSSFCellStyle cellstyle = wb.createCellStyle();
			cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
			cell.setCellStyle(cellstyle);
		}
	}

3.效果如下圖:

4.開啟可以看到資料已經寫入:

5.總結: 在本次程式碼中,可以看到呼叫下載的方法的引數中,資料是被放到Map容器中的,其中的key是一個物件,value是一個分數型別是String。當然封裝資料的引數也可以List型別的,只不過要看我們實際需求,如果從資料庫中查出的資訊不是一張表,那麼就不能用一個實體物件來封裝,所以可以使用map。在本次程式碼中,student作為map 的key,儘量在Student類中重寫一下hashcode方法和equals方法,保證map的鍵值得唯一性。