SpringMVC 實現POI讀取Excle文件中數據導入數據庫(上傳)、導出數據庫中數據到Excle文件中(下載)


讀取Excale表返回一個集合:

package com.shiliu.game.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * SpringMVC 讀取Excle工具類
 * @author  otowa
 * @Date    2016-12-04 14:57
 *
 * @param <T>
 */
public class LeadingInExcel<T> {
    
    //log4j輸出
    private Logger logger = Logger.getLogger(this.getClass());
    // 時間的格式
    private String format="yyyy-MM-dd";

    /**
     * 無參構造
     */
    public LeadingInExcel() {
        super();
    }
    
    /**
     * 構造設置顯示時間的格式
     * @param format 例:"yyyy-MM-dd"
     */
    public LeadingInExcel(String format) {
        super();
        this.format = format;
    }
    
    /**
     * 設置顯示時間的格式
     * @param format 例:"yyyy-MM-dd"
     */
    public void setFormat(String format) {
        this.format = format;
    }
    
    /**
     * 上傳Excle文件、並讀取其中數據、返回list數據集合
     * @param multipart
     * @param propertiesFileName    properties文件名稱
     * @param kyeName                properties文件中上傳存儲文件的路徑
     * @param sheetIndex            讀取Excle中的第幾頁中的數據
     * @param titleAndAttribute        標題名與實體類屬性名對應的Map集合
     * @param clazz                    實體類.class
     * @return                        返回讀取出的List集合
     * @throws Exception
     */
    public List<T> uploadAndRead(MultipartFile multipart,String propertiesFileName, String kyeName,int sheetIndex,
            Map<String, String> titleAndAttribute,Class<T> clazz) throws Exception{
        
            String originalFilename=null;
            int i = 0;
            boolean isExcel2003 = false;
            
            //取出文件名稱
            originalFilename = multipart.getOriginalFilename();
            
            //判斷Excel是什么版本
            i = isExcleVersion(originalFilename);
            if(i==0)return null; else if(i==1)isExcel2003=true;
            
            String filePath = readPropertiesFilePathMethod( propertiesFileName, kyeName);
            File filePathname = this.upload(multipart, filePath, isExcel2003);
            List<T> judgementVersion = judgementVersion(filePathname, sheetIndex, titleAndAttribute, clazz, isExcel2003);
        
        return judgementVersion;
    }
    
    /**
     * @描述:判斷Excel是什么版本
     * @param originalFilename
     * @return
     *         1 :2003
     *         2 :2007
     *         0 :不是Excle版本
     */
    public int isExcleVersion(String originalFilename){
        int i = 0;
        
        if(originalFilename.matches("^.+\\.(?i)(xls)$"))i = 1; 
        else
        if(originalFilename.matches("^.+\\.(?i)(xlsx)$"))i = 2;
        
        return i;
    }

    /**
     * 讀取properties文件中對應鍵的值
     * @param propertiesFileName
     * @param kyeName
     * @return value值
     */
    public String readPropertiesFilePathMethod(String propertiesFileName, String kyeName){
        
        //讀取properties文件
        InputStream inputStream=null;
        Properties properties=null;
        String filePath=null;//讀取出的文件路徑
        try {
          inputStream= new FileInputStream(this.getClass().getClassLoader().getResource("/"+propertiesFileName+".properties").getPath());
          properties=new Properties();
          properties.load(inputStream);
          filePath = properties.getProperty(kyeName);
        } catch (FileNotFoundException e1) {
            logger.error("未找到properties文件!", e1);
        } catch (IOException e1) {
            logger.error("打開文件流異常!", e1);
        } finally{
            //關閉流
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error("關閉文件流異常!", e);
                }
            }
        }
        return filePath;
    }
    
    /**
     * SpringMVC 上傳Excle文件至本地
     * @param multipart
     * @param filePath        上傳至本地的文件路徑    例:D:\\fileupload
     * @param isExcel2003    是否是2003版本的Excle文件
     * @return                返回上傳文件的全路徑
     * @throws Exception
     */
    public File upload(MultipartFile multipart,String filePath,boolean isExcel2003) throws Exception{
        //文件后綴
        String extension=".xlsx";
        if(isExcel2003)extension=".xls";
        //指定上傳文件的存儲路徑
        File file=new File(filePath);
        
        //接口強轉實現類
        CommonsMultipartFile commons=(CommonsMultipartFile) multipart;
        
        //判斷所屬路徑是否存在、不存在新建
        if(file.exists())file.mkdirs();
        
        /*
         * 新建一個文件
         * LongIdWorker longID工具類
         */
        File filePathname=new File(file+File.separator+LongIdWorker.getDataId()+extension);
        
        //將上傳的Excel寫入新建的文件中
        try {
            commons.getFileItem().write(filePathname);
        } catch (Exception e) {
            logger.error("寫入文件異常", e);
        }
        
        return filePathname;
    }
    
    /**
     * 讀取本地Excel文件返回List集合
     * @param filePathname
     * @param sheetIndex
     * @param titleAndAttribute
     * @param clazz
     * @param isExcel2003
     * @return
     * @throws Exception
     */
    public List<T> judgementVersion(File filePathname,int sheetIndex,Map<String, String> titleAndAttribute,Class<T> clazz,boolean isExcel2003) throws Exception{
        
        FileInputStream is=null;
        POIFSFileSystem fs=null;
        Workbook workbook=null;
            try {
                //打開流
                is=new FileInputStream(filePathname);
                if(isExcel2003){
                    //把excel文件作為數據流來進行傳入傳出
                    fs=new POIFSFileSystem(is);
                    //解析Excel 2003版
                    workbook = new HSSFWorkbook(fs);
                }else{
                    //解析Excel 2007版
                    workbook=new XSSFWorkbook(is);
                }
                
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        
        return readExcelTitle(workbook,sheetIndex,titleAndAttribute,clazz);
    }

    /**
     * 判斷接收的Map集合中的標題是否於Excle中標題對應
     * @param workbook
     * @param sheetIndex
     * @param titleAndAttribute
     * @param clazz
     * @return
     * @throws Exception
     */
    private List<T> readExcelTitle(Workbook workbook,int sheetIndex,Map<String, String> titleAndAttribute,Class<T> clazz) throws Exception{

        //得到第一個shell  
        Sheet sheet = workbook.getSheetAt(sheetIndex);
        
        // 獲取標題
        Row titelRow = sheet.getRow(0);
        Map<Integer, String> attribute = new HashMap<Integer, String>();
        if (titleAndAttribute != null) {
            for (int columnIndex = 0; columnIndex < titelRow.getLastCellNum(); columnIndex++) {
                Cell cell = titelRow.getCell(columnIndex);
                if (cell != null) {
                    String key = cell.getStringCellValue();
                    String value = titleAndAttribute.get(key);
                    if (value == null) {
                        value = key;
                    }
                    attribute.put(Integer.valueOf(columnIndex), value);
                }
            }
        } else {
            for (int columnIndex = 0; columnIndex < titelRow.getLastCellNum(); columnIndex++) {
                Cell cell = titelRow.getCell(columnIndex);
                if (cell != null) {
                    String key = cell.getStringCellValue();
                    attribute.put(Integer.valueOf(columnIndex), key);
                }
            }
        }

        return readExcelValue(workbook,sheet,attribute,clazz);
        
    }
    
    /**
     * 獲取Excle中的值
     * @param workbook
     * @param sheet
     * @param attribute
     * @param clazz
     * @return
     * @throws Exception
     */
    private List<T> readExcelValue(Workbook workbook,Sheet sheet,Map<Integer, String> attribute,Class<T> clazz) throws Exception{
        List<T> info=new ArrayList<T>();
        //獲取標題行列數
        int titleCellNum = sheet.getRow(0).getLastCellNum();
        // 獲取值
        for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
            Row row = sheet.getRow(rowIndex);
//            logger.debug("第--" + rowIndex);
            
            //    1.若當前行的列數不等於標題行列數就放棄整行數據(若想放棄此功能注釋4個步驟即可)
            int lastCellNum = row.getLastCellNum();
            if(titleCellNum !=  lastCellNum){
                continue;
            }
            
            // 2.標記
            boolean judge = true;
            T obj = clazz.newInstance();
            for (int columnIndex = 0; columnIndex < row.getLastCellNum(); columnIndex++) {//這里小於等於變成小於
                Cell cell = row.getCell(columnIndex);
                
                //處理單元格中值得類型
                String value = getCellValue(cell);
                
                // 3.單元格中的值等於null或等於"" 就放棄整行數據
                if(value == null || "".equals(value)){
                    judge = false;
                    break;
                }
                
                /*
                 * 測試:查看自定義的title Map集合中定義的Excle標題和實體類中屬性對應情況!
                   System.out.println("c:"+columnIndex+"\t"+attribute.get(Integer.valueOf(columnIndex)));
                 */
                Field field = clazz.getDeclaredField(attribute.get(Integer
                        .valueOf(columnIndex)));
                Class<?> fieldType = field.getType();
                Object agge = null;
                if (fieldType.isAssignableFrom(Integer.class)) {
                    agge = Integer.valueOf(value);
                } else if (fieldType.isAssignableFrom(Double.class)) {
                    agge = Double.valueOf(value);
                } else if (fieldType.isAssignableFrom(Float.class)) {
                    agge = Float.valueOf(value);
                } else if (fieldType.isAssignableFrom(Long.class)) {
                    agge = Long.valueOf(value);
                } else if (fieldType.isAssignableFrom(Date.class)) {
                    agge = new SimpleDateFormat(format).parse(value);
                } else if (fieldType.isAssignableFrom(Boolean.class)) {
                    agge = "Y".equals(value) || "1".equals(value);
                } else if (fieldType.isAssignableFrom(String.class)) {
                    agge = value;
                }
                // 個人感覺char跟byte就不用判斷了 用這兩個類型的很少如果是從數據庫用IDE生成的話就不會出現了
                Method method = clazz.getMethod("set"
                        + toUpperFirstCase(attribute.get(Integer
                                .valueOf(columnIndex))), fieldType);
                method.invoke(obj, agge);

            }
            // 4. if
            if(judge)info.add(obj);
        }
        return info;
    }
    
    /**
     *  @ 首字母大寫
     */
    private String toUpperFirstCase(String str) {
        return str.replaceFirst(str.substring(0, 1), str.substring(0, 1)
                .toUpperCase());
    }
    
    /**
     * 功能:處理單元格中值得類型
     * @param cell
     * @return
     */
    private String getCellValue(Cell cell) {
        Object result = "";
        if (cell != null) {
            switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                result = cell.getStringCellValue();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                //判斷是是日期型,轉換日期格式,否則轉換數字格式。
                if(DateUtil.isCellDateFormatted(cell)){
                    Date dateCellValue = cell.getDateCellValue();
                    if(dateCellValue != null){
                        result = new SimpleDateFormat(this.format).format(dateCellValue);
                    }else{
                        result="";
                    }
                }else{
                    result = new DecimalFormat("0").format(cell.getNumericCellValue());
                };
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                result = cell.getBooleanCellValue();
                break;
            case Cell.CELL_TYPE_FORMULA:
                /*
                 *  導入時如果為公式生成的數據則無值
                 *  
                    if (!cell.getStringCellValue().equals("")) {
                        value = cell.getStringCellValue();
                    } else {
                        value = cell.getNumericCellValue() + "";
                    }
                */
                result = cell.getCellFormula();
                break;
            case Cell.CELL_TYPE_ERROR:
                result = cell.getErrorCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                break;
            default:
                break;
            }
        }
        return result.toString();
    } 
}

使用例子(項目代碼只能模仿):

    /**
     * 讀取Excel中的用戶信息插入數據庫
     * @param multipart
     * @param session
     * @return
     */
    @RequestMapping(value="/batchimport")
    @ResponseBody
    public String batchImportMethod(
            @RequestParam(value="gameId") String gameId,
            @RequestParam(value="filename") MultipartFile multipart
    ){
        //局部變量
        LeadingInExcel<UserWhiteList> testExcel=null;
        List<UserWhiteList> uploadAndRead=null;
        boolean judgement = false;
        String Msg =null;
        String error = "";
        
        
        //定義需要讀取的數據
        String formart = "yyyy-MM-dd";
        String propertiesFileName = "config";
        String kyeName = "file_path";
        int sheetIndex = 0;
        Map<String, String> titleAndAttribute=null;
        Class<UserWhiteList> clazz=UserWhiteList.class;
            //定義對應的標題名與對應屬性名
            titleAndAttribute=new HashMap<String, String>();
            titleAndAttribute.put("手機號碼", "phone");
            titleAndAttribute.put("總抽獎次數", "playtimes");
        
        //調用解析工具包
        testExcel=new LeadingInExcel<UserWhiteList>(formart);
        //解析excel,獲取客戶信息集合
        try {
            uploadAndRead = testExcel.uploadAndRead(multipart, propertiesFileName, kyeName, sheetIndex, titleAndAttribute, clazz);
        } catch (Exception e) {
            log.error("讀取Excel文件錯誤!",e);
        }
        if(uploadAndRead != null && !"[]".equals(uploadAndRead.toString()) && uploadAndRead.size()>=1){
            judgement = true;
        }
        if(judgement){
            
            //把客戶信息分為沒100條數據為一組迭代添加客戶信息(注:將customerList集合作為參數,在Mybatis的相應映射文件中使用foreach標簽進行批量添加。)
            //int count=0;
            int listSize=uploadAndRead.size();
            int toIndex=100;
            for (int i = 0; i < listSize; i+=100) {
                if(i+100>listSize){
                    toIndex=listSize-i;
                }
                List<UserWhiteList> subList = uploadAndRead.subList(i, i+toIndex);
                /*
                 * 測試數據:
                     count=count+subList.size();
                    System.out.println("subList長度:"+subList.size()+"\t總長度:"+count);
                 * 
                     for (UserJHDX userJHDX : subList) {
                        System.out.println("手機號:"+userJHDX.getPhone()+"截止日期:"+userJHDX.getUptodate()+"流量值"+userJHDX.getFlux()+"總次數"+userJHDX.getTotal());
                    }
                 */
                
                /** 此處執行集合添加 */
                userWhiteListService.batchInport(subList, gameId);
            }
            
             Msg ="批量導入EXCEL成功!";
        }else{
             Msg ="批量導入EXCEL失敗!";
        }
        
        String res = "{ error:'" + error + "', msg:'" + Msg + "'}";
        return res;
    }

讀取一個集合輸出Excle:

package com.shiliu.game.utils;

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.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;  
  
/** 
 * 導出Excel公共方法 
 *  
 * @author wkr 
 * 
 */  
public class LeadingOutExcel {  

    //導出文件的名字
    private String fileName;
    //顯示的導出表的標題  
    private String title;  
    //導出表的列名  
    private String[] rowName;
      
    private List<Object[]>  dataList = new ArrayList<Object[]>();  
      
    private HttpServletResponse  response = null;
    
    private HSSFWorkbook workbook = null;
    
    private OutputStream out = null;
      
    //構造方法,傳入要導出的數據  
    public LeadingOutExcel(String fileName,String title,String[] rowName,List<Object[]>  dataList,HttpServletResponse response){
        this.fileName = fileName;
        this.dataList = dataList;  
        this.rowName = rowName;  
        this.title = title;  
        this.response = response;
    }
    
    public void export () throws Exception{
        
        HSSFWorkbook createExcel = this.createExcel();
        this.writeInOutputStream(createExcel);
    }
              
    /* 
     * 導出數據 
     * */  
    public HSSFWorkbook createExcel() throws Exception{  
        try{  
            workbook = new HSSFWorkbook();                     // 創建工作簿對象  
            HSSFSheet sheet = workbook.createSheet(title);                  // 創建工作表  
              
            /*
             *  產生表格標題行  
            HSSFRow rowm = sheet.createRow(0);  
            HSSFCell cellTiltle = rowm.createCell(0);//設置開頭兩行
                
                 * 使用條件:
                 * HSSFRow rowRowName = sheet.createRow(0);設置索引2的位置創建行
                 * HSSFRow row = sheet.createRow(i+1);//創建所需的行數     改為i+3
                 * 
             */
              
            //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("");//設置空單元格的內容。比如傳入List的值是空的。
             */
            // 定義所需列數  
            int columnNum = rowName.length;  
            HSSFRow rowRowName = sheet.createRow(0);                // 在索引2的位置創建行(最頂端的行開始的第二行)  
              
            // 將列頭設置到sheet的單元格中  
            for(int n=0;n<columnNum;n++){  
                HSSFCell  cellRowName = rowRowName.createCell(n);               //創建列頭對應個數的單元格  
                cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);             //設置列頭單元格的數據類型  
                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+1);//創建所需的行數  
                  
                for(int j=0; j<obj.length; j++){  
                    HSSFCell  cell = null;   //設置單元格的數據類型  
                    if(j == 0){  
                        cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);  
                        cell.setCellValue(i+1);   
                    }else{  
                        cell = row.createCell(j,HSSFCell.CELL_TYPE_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.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                            //int length = currentCell.getStringCellValue().getBytes().length;
                            String stringCellValue = null;
                            try {
                                stringCellValue = currentCell.getStringCellValue();
                            } catch (Exception e) {
                                continue;
                            }
                            int length = stringCellValue==null?50:stringCellValue.getBytes().length;  
                            
                            if (columnWidth < length) {  
                                columnWidth = length;  
                            }  
                        }  
                    }  
                }  
                if(colNum == 0){  
                    sheet.setColumnWidth(colNum, (columnWidth-2) * 256);  
                }else{  
                    sheet.setColumnWidth(colNum, (columnWidth+4) * 256);  
                }  
            }  
  
        }catch(Exception e){  
            e.printStackTrace();  
        }
        return workbook;  
          
    }
    
    public void writeInOutputStream(HSSFWorkbook workbook) throws Exception{
        
        //設置響應類型、與頭信息
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName+".xls", "UTF-8"));
        out = response.getOutputStream();
        workbook.write(out);
        
          //清除資源
        out.close();
    }
      
    /*  
     * 列頭單元格樣式 
     */      
    public HSSFCellStyle getColumnTopStyle(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(HSSFCellStyle.BORDER_THIN);  
          //設置底邊框顏色;    
          style.setBottomBorderColor(HSSFColor.BLACK.index);  
          //設置左邊框;     
          style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
          //設置左邊框顏色;   
          style.setLeftBorderColor(HSSFColor.BLACK.index);  
          //設置右邊框;   
          style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
          //設置右邊框顏色;   
          style.setRightBorderColor(HSSFColor.BLACK.index);  
          //設置頂邊框;   
          style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
          //設置頂邊框顏色;    
          style.setTopBorderColor(HSSFColor.BLACK.index);  
          //在樣式用應用設置的字體;    
          style.setFont(font);  
          //設置自動換行;   
          style.setWrapText(false);  
          //設置水平對齊的樣式為居中對齊;    
          style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
          //設置垂直對齊的樣式為居中對齊;   
          style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
            
          return style;  
            
    }  
      
    /*   
     * 列數據信息單元格樣式 
     */    
    public HSSFCellStyle getStyle(HSSFWorkbook workbook) {  
          // 設置字體  
          HSSFFont font = workbook.createFont();  
          //設置字體大小  
          //font.setFontHeightInPoints((short)10);  
          //字體加粗  
          //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
          //設置字體名字   
          font.setFontName("Courier New");  
          //設置樣式;   
          HSSFCellStyle style = workbook.createCellStyle();  
          //設置底邊框;   
          style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
          //設置底邊框顏色;    
          style.setBottomBorderColor(HSSFColor.BLACK.index);  
          //設置左邊框;     
          style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
          //設置左邊框顏色;   
          style.setLeftBorderColor(HSSFColor.BLACK.index);  
          //設置右邊框;   
          style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
          //設置右邊框顏色;   
          style.setRightBorderColor(HSSFColor.BLACK.index);  
          //設置頂邊框;   
          style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
          //設置頂邊框顏色;    
          style.setTopBorderColor(HSSFColor.BLACK.index);  
          //在樣式用應用設置的字體;    
          style.setFont(font);  
          //設置自動換行;   
          style.setWrapText(false);  
          //設置水平對齊的樣式為居中對齊;    
          style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
          //設置垂直對齊的樣式為居中對齊;   
          style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
           
          return style;  
      
    }  
}  
package com.shiliu.game.utils;

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.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;  
  
/** 
 * 導出Excel公共方法 
 *  
 * @author wkr 
 * 
 */  
public class LeadingOutExcel {  

    //導出文件的名字
    private String fileName;
    //顯示的導出表的標題  
    private String title;  
    //導出表的列名  
    private String[] rowName;
      
    private List<Object[]>  dataList = new ArrayList<Object[]>();  
      
    private HttpServletResponse  response = null;
    
    private HSSFWorkbook workbook = null;
    
    private OutputStream out = null;
      
    //構造方法,傳入要導出的數據  
    public LeadingOutExcel(String fileName,String title,String[] rowName,List<Object[]>  dataList,HttpServletResponse response){
        this.fileName = fileName;
        this.dataList = dataList;  
        this.rowName = rowName;  
        this.title = title;  
        this.response = response;
    }
    
    public void export () throws Exception{
        
        HSSFWorkbook createExcel = this.createExcel();
        this.writeInOutputStream(createExcel);
    }
              
    /* 
     * 導出數據 
     * */  
    public HSSFWorkbook createExcel() throws Exception{  
        try{  
            workbook = new HSSFWorkbook();                     // 創建工作簿對象  
            HSSFSheet sheet = workbook.createSheet(title);                  // 創建工作表  
              
            /*
             *  產生表格標題行  
            HSSFRow rowm = sheet.createRow(0);  
            HSSFCell cellTiltle = rowm.createCell(0);//設置開頭兩行
                
                 * 使用條件:
                 * HSSFRow rowRowName = sheet.createRow(0);設置索引2的位置創建行
                 * HSSFRow row = sheet.createRow(i+1);//創建所需的行數     改為i+3
                 * 
             */
              
            //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("");//設置空單元格的內容。比如傳入List的值是空的。
             */
            // 定義所需列數  
            int columnNum = rowName.length;  
            HSSFRow rowRowName = sheet.createRow(0);                // 在索引2的位置創建行(最頂端的行開始的第二行)  
              
            // 將列頭設置到sheet的單元格中  
            for(int n=0;n<columnNum;n++){  
                HSSFCell  cellRowName = rowRowName.createCell(n);               //創建列頭對應個數的單元格  
                cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);             //設置列頭單元格的數據類型  
                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+1);//創建所需的行數  
                  
                for(int j=0; j<obj.length; j++){  
                    HSSFCell  cell = null;   //設置單元格的數據類型  
                    if(j == 0){  
                        cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);  
                        cell.setCellValue(i+1);   
                    }else{  
                        cell = row.createCell(j,HSSFCell.CELL_TYPE_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.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                            //int length = currentCell.getStringCellValue().getBytes().length;
                            String stringCellValue = null;
                            try {
                                stringCellValue = currentCell.getStringCellValue();
                            } catch (Exception e) {
                                continue;
                            }
                            int length = stringCellValue==null?50:stringCellValue.getBytes().length;  
                            
                            if (columnWidth < length) {  
                                columnWidth = length;  
                            }  
                        }  
                    }  
                }  
                if(colNum == 0){  
                    sheet.setColumnWidth(colNum, (columnWidth-2) * 256);  
                }else{  
                    sheet.setColumnWidth(colNum, (columnWidth+4) * 256);  
                }  
            }  
  
        }catch(Exception e){  
            e.printStackTrace();  
        }
        return workbook;  
          
    }
    
    public void writeInOutputStream(HSSFWorkbook workbook) throws Exception{
        
        //設置響應類型、與頭信息
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName+".xls", "UTF-8"));
        out = response.getOutputStream();
        workbook.write(out);
        
          //清除資源
        out.close();
    }
      
    /*  
     * 列頭單元格樣式 
     */      
    public HSSFCellStyle getColumnTopStyle(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(HSSFCellStyle.BORDER_THIN);  
          //設置底邊框顏色;    
          style.setBottomBorderColor(HSSFColor.BLACK.index);  
          //設置左邊框;     
          style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
          //設置左邊框顏色;   
          style.setLeftBorderColor(HSSFColor.BLACK.index);  
          //設置右邊框;   
          style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
          //設置右邊框顏色;   
          style.setRightBorderColor(HSSFColor.BLACK.index);  
          //設置頂邊框;   
          style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
          //設置頂邊框顏色;    
          style.setTopBorderColor(HSSFColor.BLACK.index);  
          //在樣式用應用設置的字體;    
          style.setFont(font);  
          //設置自動換行;   
          style.setWrapText(false);  
          //設置水平對齊的樣式為居中對齊;    
          style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
          //設置垂直對齊的樣式為居中對齊;   
          style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
            
          return style;  
            
    }  
      
    /*   
     * 列數據信息單元格樣式 
     */    
    public HSSFCellStyle getStyle(HSSFWorkbook workbook) {  
          // 設置字體  
          HSSFFont font = workbook.createFont();  
          //設置字體大小  
          //font.setFontHeightInPoints((short)10);  
          //字體加粗  
          //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
          //設置字體名字   
          font.setFontName("Courier New");  
          //設置樣式;   
          HSSFCellStyle style = workbook.createCellStyle();  
          //設置底邊框;   
          style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
          //設置底邊框顏色;    
          style.setBottomBorderColor(HSSFColor.BLACK.index);  
          //設置左邊框;     
          style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
          //設置左邊框顏色;   
          style.setLeftBorderColor(HSSFColor.BLACK.index);  
          //設置右邊框;   
          style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
          //設置右邊框顏色;   
          style.setRightBorderColor(HSSFColor.BLACK.index);  
          //設置頂邊框;   
          style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
          //設置頂邊框顏色;    
          style.setTopBorderColor(HSSFColor.BLACK.index);  
          //在樣式用應用設置的字體;    
          style.setFont(font);  
          //設置自動換行;   
          style.setWrapText(false);  
          //設置水平對齊的樣式為居中對齊;    
          style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
          //設置垂直對齊的樣式為居中對齊;   
          style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
           
          return style;  
      
    }  
}  

使用例子(項目代碼只能模仿):

    /**
     * 條件導出 
     * @param gameId
     * @param startDate
     * @param endDate
     * @param level
     * @param response
     */
    @RequestMapping(value="/conditionalExportDate")
    public void conditionalExportDateMethod(
        @RequestParam(value="gameId") String gameId,
        @RequestParam(value="startDate") String startDate,
        @RequestParam(value="endDate") String endDate,
        @RequestParam(value="level") String level,
        HttpServletResponse response
    ){
        Map<String, Object> conditionMap = null;
        List<PlayRecord> dataSet = null;
        LeadingOutExcel leadingOutExcel = null;    //工具類
        
        //配置信息
        String fileName = "client";
        String format = "yyyy-MM-dd hh:mm:ss";
        String title = "用戶信息";
        String[] rowName = { "編號","微信號","微信名稱", "手機號", "參與活動時間","中獎等級", "獲得獎品" };
        
        //查詢條件
        conditionMap = new HashMap<String, Object>();
        conditionMap.put("gameId", gameId);
        //導出全部
        if(!"請選擇日期".equals(startDate) && !"請選擇日期".equals(endDate)){
            conditionMap.put("startDate", startDate);
            conditionMap.put("endDate", endDate);
        }
        if(!"請輸入中獎等級".equals(level)){
            conditionMap.put("level", level);
        }
        
        dataSet = playRecordService.conditionQuery(conditionMap);
        
        List<Object[]>  dataList = new ArrayList<Object[]>();  
        Object[] objs = null;  
        for (int i = 0; i < dataSet.size(); i++) {  
            PlayRecord man = dataSet.get(i);  
            objs = new Object[rowName.length];  
            objs[0] = i;  
            objs[1] = man.getOpenid();
            objs[2] = man.getNickName();
            objs[3] = man.getPhoneNumber();
                //日期類型處理
                Date date = man.getPalyTime();
                String dateStr = "";
                if(date!=null){
                    SimpleDateFormat df = new SimpleDateFormat(format);  
                    dateStr = df.format(date);
                }
            objs[4] = dateStr;
            objs[5] = man.getLevel();
            objs[6] = man.getAwardName();  
            dataList.add(objs);  
        }  
        
        leadingOutExcel = new LeadingOutExcel(fileName,title, rowName, dataList,response);
        try {
            leadingOutExcel.export();
        } catch (Exception e) {
            log.error("寫入Excle出錯!", e);
        }
    }
}

原創:意藝


免責聲明!

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



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