公共POI導出Excel方法–java


最近做了一些數據Excel導出的功能,先是看了很多博客,然后發現都沒有公用的方法,但是又發現好像每一次導出都需要寫一些差不多類似的代碼,后來找到一篇公共導出Excel的方法,https://www.cnblogs.com/coprince/p/5757714.html,但是這位博主好像並沒有完全公布出來,然后自己稍微研究了一下在他的源碼基礎上寫了個公共的導出方法。有寫的不好的地方大佬可以指點指點

maven依賴

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
package com.tl.util;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;

public class ExportExcel {
    
    //顯示的導出表的標題
    private String title;
    //導出表的列名
    private String[] rowName ;
    
    private List<Object[]>  dataList = new ArrayList<Object[]>();
    
    HttpServletResponse  response;
    
    //構造方法,傳入要導出的數據
    public ExportExcel(String title,String[] rowName,List<Object[]>  dataList){
        this.dataList = dataList;
        this.rowName = rowName;
        this.title = title;
    }
    
    /*
     * 導出數據
     * */
    public void export(HttpServletResponse response) throws Exception{
        
        try{
            HSSFWorkbook workbook = new HSSFWorkbook();                        // 創建工作簿對象
            HSSFSheet sheet = workbook.createSheet(title);                     // 創建工作表
            // 產生表格標題行
            HSSFRow rowm = sheet.createRow(0);
            HSSFCell cellTiltle = rowm.createCell(0);
          //sheet樣式定義【getColumnTopStyle()/getStyle()均為自定義方法 - 在下面  - 可擴展】
            HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//獲取列頭樣式對象
            HSSFCellStyle style = this.getStyle(workbook);                    //單元格樣式對象
            sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1)));  
            cellTiltle.setCellStyle(columnTopStyle);
            cellTiltle.setCellValue(title);
         // 定義所需列數
            int columnNum = rowName.length;
            HSSFRow rowRowName = sheet.createRow(2);                // 在索引2的位置創建行(最頂端的行開始的第二行)
         // 將列頭設置到sheet的單元格中
            for(int n=0;n<columnNum;n++){
                HSSFCell  cellRowName = rowRowName.createCell(n);                //創建列頭對應個數的單元格
                cellRowName.setCellValue(CellType.STRING.getCode());                //設置列頭單元格的數據類型
                HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
                cellRowName.setCellValue(text);                                    //設置列頭單元格的值
                cellRowName.setCellStyle(columnTopStyle);                        //設置列頭單元格樣式
            }
            //將查詢出的數據設置到sheet對應的單元格中
            for(int i=0;i<dataList.size();i++){
                
                Object[] obj = dataList.get(i);//遍歷每個對象
                HSSFRow row = sheet.createRow(i+3);//創建所需的行數
                
                for(int j=0; j<obj.length; j++){
                    HSSFCell  cell = null;   //設置單元格的數據類型
                    if(j == 0){
                        cell = row.createCell(j,CellType.NUMERIC);
                        cell.setCellValue(i+1);    
                    }else{
                        cell = row.createCell(j,CellType.STRING);
                        //if(!"".equals(obj[j]) && obj[j] != null){
                            cell.setCellValue(obj[j].toString());                        //設置單元格的值
                       // }
                    }
                    cell.setCellStyle(style);                                    //設置單元格樣式
                }
            }
            //讓列寬隨着導出的列長自動適應
            for (int colNum = 0; colNum < columnNum; colNum++) {
                int columnWidth = sheet.getColumnWidth(colNum) / 256;
                for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                    HSSFRow currentRow;
                    //當前行未被使用過
                    if (sheet.getRow(rowNum) == null) {
                        currentRow = sheet.createRow(rowNum);
                    } else {
                        currentRow = sheet.getRow(rowNum);
                    }
                    if (currentRow.getCell(colNum) != null) {
                        HSSFCell currentCell = currentRow.getCell(colNum);
                        if (currentCell.getCellTypeEnum() == CellType.STRING) {
                                int length = currentCell.getStringCellValue().getBytes().length;
                                if (columnWidth < length) {
                                    columnWidth = length;
                                }
                            
                        }
                    }
                }
                if(colNum == 0){
                    sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
                }else{
                    sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
                }
            }
            
            if(workbook !=null){
                try
                {
                    String fileName = title+".xls";
                    fileName = URLEncoder.encode(fileName, "UTF-8");//中文名稱
                    String headStr = "attachment; filename=\"" + fileName + "\"";
                    response.setContentType("APPLICATION/OCTET-STREAM");
                    response.setHeader("Content-Disposition", headStr);
                    OutputStream out = response.getOutputStream();
                    workbook.write(out);
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    /* 
     * 列頭單元格樣式
     */    
      public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
          
            // 設置字體
          HSSFFont font = workbook.createFont();
          //設置字體大小
          font.setFontHeightInPoints((short)12);
          //字體加粗
          font.setBold(true);
          //設置字體名字 
          font.setFontName("Courier New");
          //設置樣式; 
          HSSFCellStyle style = workbook.createCellStyle();
          //設置底邊框; 
          style.setBorderBottom(BorderStyle.THIN);
          //設置底邊框顏色;  
          style.setBottomBorderColor((short)8);//HSSFColor.BLACK.index(過時,替換成(short)8)下面都一樣
          //設置左邊框;   
          style.setBorderLeft(BorderStyle.THIN);
          //設置左邊框顏色; 
          style.setLeftBorderColor((short)8);
          //設置右邊框; 
          style.setBorderRight(BorderStyle.THIN);
          //設置右邊框顏色; 
          style.setRightBorderColor((short)8);
          //設置頂邊框; 
          style.setBorderTop(BorderStyle.THIN);
          //設置頂邊框顏色;  
          style.setTopBorderColor((short)8);
          //在樣式用應用設置的字體;  
          style.setFont(font);
          //設置自動換行; 
          style.setWrapText(false);
          //設置水平對齊的樣式為居中對齊;  
          style.setAlignment(HorizontalAlignment.CENTER);
          //設置垂直對齊的樣式為居中對齊; 
          style.setVerticalAlignment(VerticalAlignment.CENTER);
          
          return style;
          
      }
      
      /*  
     * 列數據信息單元格樣式
     */  
      public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
            // 設置字體
            HSSFFont font = workbook.createFont();
            //設置字體大小
            font.setFontHeightInPoints((short)11);
            //字體加粗
            //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            //設置字體名字 
            font.setFontName("Courier New");
            //設置樣式; 
            HSSFCellStyle style = workbook.createCellStyle();
            //設置底邊框; 
            style.setBorderBottom(BorderStyle.THIN);
            //設置底邊框顏色;  
            style.setBottomBorderColor((short)8);//HSSFColor.BLACK.index(過時,替換成(short)8)
            //設置左邊框;   
            style.setBorderLeft(BorderStyle.THIN);
            //設置左邊框顏色; 
            style.setLeftBorderColor((short)8);//HSSFColor.BLACK.index(過時,替換成(short)8)
            //設置右邊框; 
            style.setBorderRight(BorderStyle.THIN);
            //設置右邊框顏色; 
            style.setRightBorderColor((short)8);
            //設置頂邊框; 
            style.setBorderTop(BorderStyle.THIN);
            //設置頂邊框顏色;  
            style.setTopBorderColor((short)8);
            //在樣式用應用設置的字體;  
            style.setFont(font);
            //設置自動換行; 
            style.setWrapText(false);
            //設置水平對齊的樣式為居中對齊;  
            style.setAlignment(HorizontalAlignment.CENTER);
            //設置垂直對齊的樣式為居中對齊; 
            style.setVerticalAlignment(VerticalAlignment.CENTER);
           
            return style;
      
      }
      
     


}

這個導出用到的方法,組裝數據的如下:

@RequestMapping("/outPartitionExcel")
    public void outPartitionExcel(Partition partition,HttpServletResponse response) throws Exception {
        List<Partition> Partitions = partitionService.findAllPartitionPage(partition);
        String title = "管理分區";
        String[] rowsName = new String[] {"序號","分揀編碼","定區編碼","省份","城市","區(縣)","關鍵字","起始號","終止號","單雙號","操作人員","操作單位","操作時間"};
        List<Object[]> dataList = new ArrayList<>();
        Object[] objs = null;
        for(int i=0; i<Partitions.size();i++) {
             Partition main = Partitions.get(i);
             objs = new Object[rowsName.length];
             objs[0] = i;
             objs[1] = main.getSortingCode();
             objs[2] = main.getZoneCode();
             objs[3] = main.getProvince();
             objs[4] = main.getCity();
             objs[5] = main.getCounty();
             objs[6] = main.getKeyword();
             objs[7] = main.getStartNumber();
             objs[8] = main.getTerminateNumber();
             objs[9] = main.getsDNumber();
             objs[10] = main.getEmp().getEmpName();
             objs[11] = main.getSyUnits().getName();
              SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String date = df.format(main.getOperationTime());
             objs[12] = date;
             dataList.add(objs);
        }
         ExportExcel ex = new ExportExcel(title, rowsName, dataList);
         ex.export(response);
    }

是通過組裝一個List的類型(里面是一些列的導出數據,可以為String/int/long等全部數據類型)。數組rowsName是指導出數據的欄位名稱,title是指導出excel的標題

和sheet名。

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


免責聲明!

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



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