java 實現導出Excel(java生成 excel 並導出文件)html
常常有有一些數據須要導出成 excel 格式 ,因此就須要實現啦java
開始:apache
1.加入jar app
poi-3.6-20091214.jar字體
commons-logging-1.1.jar spa
junit-3.8.1.jar .net
log4j-1.2.13.jarexcel
2. 實現代碼 :code
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.各個參數詳解orm
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.基本操做步驟
一、用HSSFWorkbook打開或者建立「Excel文件對象」 二、用HSSFWorkbook對象返回或者建立Sheet對象 三、用Sheet對象返回行對象,用行對象獲得Cell對象 四、對Cell對象讀寫。
我的參考他人博客 及 本身項目:
https://blog.csdn.net/xunwei0303/article/details/53213130