java excle導出

最早開始的時候做過一些數據Excel導出的功能,但是到後期每一次導出都需要寫一些差不多類似的代碼,稍微研究了一下寫了個公共的導出方法。

這裏用的是POI,然後寫成了一個公共類,傳入設置好格式的數據,就能彈出下載框。

[java] view plain copy
  1. package com.hwt.glmf.common;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.OutputStream;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import javax.servlet.http.HttpServletResponse;  
  9.   
  10. import org.apache.poi.hssf.usermodel.HSSFCell;  
  11. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  12. import org.apache.poi.hssf.usermodel.HSSFFont;  
  13. import org.apache.poi.hssf.usermodel.HSSFRichTextString;  
  14. import org.apache.poi.hssf.usermodel.HSSFRow;  
  15. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  16. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  17. import org.apache.poi.hssf.util.CellRangeAddress;  
  18. import org.apache.poi.hssf.util.HSSFColor;  
  19.   
  20. /** 
  21.  * 導出Excel公共方法 
  22.  * @version 1.0 
  23.  *  
  24.  * @author wangcp 
  25.  * 
  26.  */  
  27. public class ExportExcel extends BaseAction {  
  28.       
  29.     //顯示的導出表的標題  
  30.     private String title;  
  31.     //導出表的列名  
  32.     private String[] rowName ;  
  33.       
  34.     private List<Object[]>  dataList = new ArrayList<Object[]>();  
  35.       
  36.     HttpServletResponse  response;  
  37.       
  38.     //構造方法,傳入要導出的數據  
  39.     public ExportExcel(String title,String[] rowName,List<Object[]>  dataList){  
  40.         this.dataList = dataList;  
  41.         this.rowName = rowName;  
  42.         this.title = title;  
  43.     }  
  44.               
  45.     /* 
  46.      * 導出數據 
  47.      * */  
  48.     public void export() throws Exception{  
  49.         try{  
  50.             HSSFWorkbook workbook = new HSSFWorkbook();                     // 創建工作簿對象  
  51.             HSSFSheet sheet = workbook.createSheet(title);                  // 創建工作表  
  52.               
  53.             // 產生表格標題行  
  54.             HSSFRow rowm = sheet.createRow(0);  
  55.             HSSFCell cellTiltle = rowm.createCell(0);  
  56.               
  57.             //sheet樣式定義【getColumnTopStyle()/getStyle()均爲自定義方法 - 在下面  - 可擴展】  
  58.             HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//獲取列頭樣式對象  
  59.             HSSFCellStyle style = this.getStyle(workbook);                  //單元格樣式對象  
  60.               
  61.             sheet.addMergedRegion(new CellRangeAddress(010, (rowName.length-1)));    
  62.             cellTiltle.setCellStyle(columnTopStyle);  
  63.             cellTiltle.setCellValue(title);  
  64.               
  65.             // 定義所需列數  
  66.             int columnNum = rowName.length;  
  67.             HSSFRow rowRowName = sheet.createRow(2);                // 在索引2的位置創建行(最頂端的行開始的第二行)  
  68.               
  69.             // 將列頭設置到sheet的單元格中  
  70.             for(int n=0;n<columnNum;n++){  
  71.                 HSSFCell  cellRowName = rowRowName.createCell(n);               //創建列頭對應個數的單元格  
  72.                 cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);             //設置列頭單元格的數據類型  
  73.                 HSSFRichTextString text = new HSSFRichTextString(rowName[n]);  
  74.                 cellRowName.setCellValue(text);                                 //設置列頭單元格的值  
  75.                 cellRowName.setCellStyle(columnTopStyle);                       //設置列頭單元格樣式  
  76.             }  
  77.               
  78.             //將查詢出的數據設置到sheet對應的單元格中  
  79.             for(int i=0;i<dataList.size();i++){  
  80.                   
  81.                 Object[] obj = dataList.get(i);//遍歷每個對象  
  82.                 HSSFRow row = sheet.createRow(i+3);//創建所需的行數  
  83.                   
  84.                 for(int j=0; j<obj.length; j++){  
  85.                     HSSFCell  cell = null;   //設置單元格的數據類型  
  86.                     if(j == 0){  
  87.                         cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);  
  88.                         cell.setCellValue(i+1);   
  89.                     }else{  
  90.                         cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);  
  91.                         if(!"".equals(obj[j]) && obj[j] != null){  
  92.                             cell.setCellValue(obj[j].toString());                       //設置單元格的值  
  93.                         }  
  94.                     }  
  95.                     cell.setCellStyle(style);                                   //設置單元格樣式  
  96.                 }  
  97.             }  
  98.             //讓列寬隨着導出的列長自動適應  
  99.             for (int colNum = 0; colNum < columnNum; colNum++) {  
  100.                 int columnWidth = sheet.getColumnWidth(colNum) / 256;  
  101.                 for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {  
  102.                     HSSFRow currentRow;  
  103.                     //當前行未被使用過  
  104.                     if (sheet.getRow(rowNum) == null) {  
  105.                         currentRow = sheet.createRow(rowNum);  
  106.                     } else {  
  107.                         currentRow = sheet.getRow(rowNum);  
  108.                     }  
  109.                     if (currentRow.getCell(colNum) != null) {  
  110.                         HSSFCell currentCell = currentRow.getCell(colNum);  
  111.                         if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {  
  112.                             int length = currentCell.getStringCellValue().getBytes().length;  
  113.                             if (columnWidth < length) {  
  114.                                 columnWidth = length;  
  115.                             }  
  116.                         }  
  117.                     }  
  118.                 }  
  119.                 if(colNum == 0){  
  120.                     sheet.setColumnWidth(colNum, (columnWidth-2) * 256);  
  121.                 }else{  
  122.                     sheet.setColumnWidth(colNum, (columnWidth+4) * 256);  
  123.                 }  
  124.             }  
  125.               
  126.             if(workbook !=null){  
  127.                 try  
  128.                 {  
  129.                     String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(413) + ".xls";  
  130.                     String headStr = "attachment; filename=\"" + fileName + "\"";  
  131.                     response = getResponse();  
  132.                     response.setContentType("APPLICATION/OCTET-STREAM");  
  133.                     response.setHeader("Content-Disposition", headStr);  
  134.                     OutputStream out = response.getOutputStream();  
  135.                     workbook.write(out);  
  136.                 }  
  137.                 catch (IOException e)  
  138.                 {  
  139.                     e.printStackTrace();  
  140.                 }  
  141.             }  
  142.   
  143.         }catch(Exception e){  
  144.             e.printStackTrace();  
  145.         }  
  146.           
  147.     }  
  148.       
  149.     /*  
  150.      * 列頭單元格樣式 
  151.      */      
  152.     public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {  
  153.           
  154.           // 設置字體  
  155.           HSSFFont font = workbook.createFont();  
  156.           //設置字體大小  
  157.           font.setFontHeightInPoints((short)11);  
  158.           //字體加粗  
  159.           font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  160.           //設置字體名字   
  161.           font.setFontName("Courier New");  
  162.           //設置樣式;   
  163.           HSSFCellStyle style = workbook.createCellStyle();  
  164.           //設置底邊框;   
  165.           style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
  166.           //設置底邊框顏色;    
  167.           style.setBottomBorderColor(HSSFColor.BLACK.index);  
  168.           //設置左邊框;     
  169.           style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
  170.           //設置左邊框顏色;   
  171.           style.setLeftBorderColor(HSSFColor.BLACK.index);  
  172.           //設置右邊框;   
  173.           style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
  174.           //設置右邊框顏色;   
  175.           style.setRightBorderColor(HSSFColor.BLACK.index);  
  176.           //設置頂邊框;   
  177.           style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
  178.           //設置頂邊框顏色;    
  179.           style.setTopBorderColor(HSSFColor.BLACK.index);  
  180.           //在樣式用應用設置的字體;    
  181.           style.setFont(font);  
  182.           //設置自動換行;   
  183.           style.setWrapText(false);  
  184.           //設置水平對齊的樣式爲居中對齊;    
  185.           style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  186.           //設置垂直對齊的樣式爲居中對齊;   
  187.           style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
  188.             
  189.           return style;  
  190.             
  191.     }  
  192.       
  193.     /*   
  194.      * 列數據信息單元格樣式 
  195.      */    
  196.     public HSSFCellStyle getStyle(HSSFWorkbook workbook) {  
  197.           // 設置字體  
  198.           HSSFFont font = workbook.createFont();  
  199.           //設置字體大小  
  200.           //font.setFontHeightInPoints((short)10);  
  201.           //字體加粗  
  202.           //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  203.           //設置字體名字   
  204.           font.setFontName("Courier New");  
  205.           //設置樣式;   
  206.           HSSFCellStyle style = workbook.createCellStyle();  
  207.           //設置底邊框;   
  208.           style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
  209.           //設置底邊框顏色;    
  210.           style.setBottomBorderColor(HSSFColor.BLACK.index);  
  211.           //設置左邊框;     
  212.           style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
  213.           //設置左邊框顏色;   
  214.           style.setLeftBorderColor(HSSFColor.BLACK.index);  
  215.           //設置右邊框;   
  216.           style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
  217.           //設置右邊框顏色;   
  218.           style.setRightBorderColor(HSSFColor.BLACK.index);  
  219.           //設置頂邊框;   
  220.           style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
  221.           //設置頂邊框顏色;    
  222.           style.setTopBorderColor(HSSFColor.BLACK.index);  
  223.           //在樣式用應用設置的字體;    
  224.           style.setFont(font);  
  225.           //設置自動換行;   
  226.           style.setWrapText(false);  
  227.           //設置水平對齊的樣式爲居中對齊;    
  228.           style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  229.           //設置垂直對齊的樣式爲居中對齊;   
  230.           style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
  231.            
  232.           return style;  
  233.       
  234.     }  
  235. }  
這個導出用到的方法,組裝數據的如下:

[java] view plain copy
  1.           String title = Message.getString("manifestIExportTitle");  
  2.     String[] rowsName = new String[]{"序號","貨物運輸批次號","提運單號","狀態","錄入人","錄入時間"};  
  3. List<Object[]>  dataList = new ArrayList<Object[]>();  
  4. Object[] objs = null;  
  5. for (int i = 0; i < manifestIMainList.size(); i++) {  
  6.     ManifestIMain man = manifestIMainList.get(i);  
  7.     objs = new Object[rowsName.length];  
  8.     objs[0] = i;  
  9.     objs[1] = man.getTranNo();  
  10.     objs[2] = man.getBillNo();  
  11.     objs[3] = man.getStatusFlagCnName();  
  12.     objs[4] = man.getLoginName();  
  13.     SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  14.     String date = df.format(man.getModiDate());  
  15.     objs[5] = date;  
  16.     dataList.add(objs);  
  17. }  
  18. ExportExcel ex = new ExportExcel(title, rowsName, dataList);  
  19. ex.export();  
是通過組裝一個List<Object>的類型(裏面是一些列的導出數據,可以爲String/int/long等全部數據類型)。數組rowsName是指導出數據的欄位名稱,title是指導出excel的標題

和sheet名。


以以上的數據爲例,導出的結果顯示如下(只是做了簡單的處理,有一些合併行與excel的樣式問題沒有涉及):

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章