標籤:tps data trace tail rac mic try ica pac
java 實現匯出Excel(java產生 excel 並匯出檔案)
經常有有一些資料需要匯出成 excel 格式 ,所以就需要實現啦
開始:
1.加入jar
poi-3.6-20091214.jar
commons-logging-1.1.jar
junit-3.8.1.jar
log4j-1.2.13.jar
2. 實現代碼 :
1 /** 2 * 建立excel 3 * 4 * @param list 5 * @param request 6 * @param response 7 */ 8 private void excel(List<MyBrowselog> list, HttpServletRequest request, HttpServletResponse response) { 9 OutputStream outputStream = null;10 response.setCharacterEncoding("utf-8");11 response.setContentType("application/x-msdownload");12 try {13 response.setHeader("Content-disposition",14 "attachment;filename=" + new String("個人使用者統計".getBytes("utf-8"), "ISO8859-1") + ".xls");15 } catch (UnsupportedEncodingException e2) {16 e2.printStackTrace();17 }18 try {19 outputStream = response.getOutputStream();20 } catch (IOException e1) {21 e1.printStackTrace();22 }23 24 SXSSFWorkbook workbook = new SXSSFWorkbook(list.size() + 1);25 Sheet sheet = workbook.createSheet("個人使用者統計");26 Row headRow = sheet.createRow(0);27 Cell cell0 = headRow.createCell(0);28 cell0.setCellValue("使用者名稱");29 Cell cell1 = headRow.createCell(1);30 cell1.setCellValue("瀏覽量");31 Cell cell2 = headRow.createCell(2);32 cell2.setCellValue("下載量");33 // 建立行34 for (int i = 0; i < list.size(); i++) {35 Row dataRow = sheet.createRow(i + 1);36 Cell cell_0 = dataRow.createCell(0);37 cell_0.setCellValue(list.get(i) == null ? "" : list.get(i).getUserLoginName());38 Cell cell_1 = dataRow.createCell(1);39 cell_1.setCellValue(list.get(i) == null ? "" : list.get(i).getBrowseCount());40 Cell cell_2 = dataRow.createCell(2);41 cell_2.setCellValue(list.get(i) == null ? "" : list.get(i).getDownloadCount());42 }43 try {44 workbook.write(outputStream);45 } catch (IOException e1) {46 e1.printStackTrace();47 }48 try {49 outputStream.flush();50 outputStream.close();51 } catch (IOException e) {52 e.printStackTrace();53 }54 }
3.各個參數詳解
HSSF(用於操作Excel的組件)提供給使用者使用的對象在rg.apache.poi.hssf.usermodel包中,主要部分包括Excel對象,樣式和格式,還有輔助操作。有以下幾種對象:
常用組件: HSSFWorkbook excel的文檔對象 HSSFSheet excel的表單 HSSFRow excel的行 HSSFCell excel的格子單元 HSSFFont excel字型 HSSFDataFormat 日期格式 HSSFHeader sheet頭 HSSFFooter sheet尾(只有列印的時候才能看到效果) 樣式: HSSFCellStyle cell樣式 輔助操作包括: HSSFDateUtil 日期 HSSFPrintSetup 列印 HSSFErrorConstants 錯誤資訊表
4.基本操作步驟
1、用HSSFWorkbook開啟或者建立“Excel檔案對象” 2、用HSSFWorkbook對象返回或者建立Sheet對象 3、用Sheet對象返回行對象,用行對象得到Cell對象 4、對Cell對象讀寫。
個人蔘考他人部落格 及 自己項目:
53213130
java 實現匯出Excel檔案