1. 程式人生 > >Spring MVC下 Excel 匯入匯出(poi)

Spring MVC下 Excel 匯入匯出(poi)

Excel 匯入匯出(poi)

1、引入org.apache.poi包

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.9</version>
</dependency>

2、springMVC.xml中需要配置支援上傳操作

<!-- 配置檔案上傳,如果沒有使用檔案上傳可以不用配置,當然如果不配,那麼配置檔案中也不必引入上傳元件包 -->  
<bean id="multipartResolver"    
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
    <!-- 預設編碼 -->  
    <property name="defaultEncoding" value="utf-8" />    
    <!-- 檔案大小最大值 -->  
    <property name="maxUploadSize" value="10485760000" />    
    <!-- 記憶體中的最大值 -->  
    <property name="maxInMemorySize" value="40960" />    
</bean>  

2、頁面部分

<form action="<%=request.getContextPath()%>/operate/upload" id="fileForm"                    method="post" enctype="multipart/form-data">
    <input type="file" id="file" name="file" class="file" >
    <button type="submit">上傳</button>
</form>

1、檔案上傳操作一定得加入 enctype="multipart/form-data"

3、後臺controller部分

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String uploadFile(@RequestParam("file") CommonsMultipartFile file, 
        HttpServletRequest request) {
    // 判斷檔案是否為空  
    if (!file.isEmpty()) {  
        try {  
            // 檔案儲存路徑  
            String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";  
            // 轉存檔案  
            //file.transferTo(new File(filePath)); 

            //操作解析excelutils
            excelUtils.readExcel(file.getOriginalFilename(),file,filePath);
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  

    return "redirect:/login/goLogin";
}

4、上傳解析Excel部分

4.1、自動識別讀取方式

/**
* 合併方法,讀取excel檔案
 * 根據檔名自動識別讀取方式
 * 支援97-2013格式的excel文件
 * @param fileName
 *            上傳檔名
 * @param file
 *            上傳的檔案
*/
public static List<Map> readExcel(String fileName,MultipartFile file) throws Exception{
    //準備返回值列表
    List<Map> valueList=new ArrayList<Map>();
    String filepathtemp="/mnt/b2b/tmp";//快取檔案目錄
    String tmpFileName= System.currentTimeMillis()+"."+getExtensionName(fileName);
    String ExtensionName=getExtensionName(fileName);
    File filelist = new File(filepathtemp);
    if  (!filelist .exists()  && !filelist .isDirectory())      
    {       
        filelist .mkdir();    
    } 
    String filePath = filepathtemp+System.getProperty("file.separator")+tmpFileName;
    File tmpfile = new File(filePath);
    //拷貝檔案到伺服器快取目錄(在專案下) //        copy(file,tmpfile); //stuts用的方法
    copy(file, filepathtemp,tmpFileName);//spring mvc用的方法

    //System.out.println("字尾名:"+ExtensionName);

    if(ExtensionName.equalsIgnoreCase("xls")){
        valueList=readExcel2003(filePath);
    }else if(ExtensionName.equalsIgnoreCase("xlsx")) {
        valueList=readExcel2007(filePath);
    }
    //刪除快取檔案
    tmpfile.delete();
    return valueList;

}

4.2、讀取Excel格式

/
 * 讀取97-2003格式
 * @param filePath 檔案路徑
 * @throws java.io.IOException
 */
@SuppressWarnings("rawtypes")
public static List<Map> readExcel2003(String filePath) throws IOException{
    //返回結果集
    List<Map> valueList=new ArrayList<Map>();
    FileInputStream fis=null;
    try {
        fis=new FileInputStream(filePath);
        HSSFWorkbook wookbook = new HSSFWorkbook(fis);  // 建立對Excel工作簿檔案的引用
        HSSFSheet sheet = wookbook.getSheetAt(0);   // 在Excel文件中,第一張工作表的預設索引是0
        int rows = sheet.getPhysicalNumberOfRows(); // 獲取到Excel檔案中的所有行數­
        Map<Integer,String> keys=new HashMap<Integer, String>();
        int cells=0;
        // 遍歷行­(第1行  表頭) 準備Map裡的key
        HSSFRow firstRow = sheet.getRow(0);
        if (firstRow != null) {
            // 獲取到Excel檔案中的所有的列
            cells = firstRow.getPhysicalNumberOfCells();
            // 遍歷列
            for (int j = 0; j < cells; j++) {
                // 獲取到列的值­
                try {
                    HSSFCell cell = firstRow.getCell(j);
                    String cellValue = getCellValue(cell);
                    keys.put(j,cellValue);                      
                } catch (Exception e) {
                    e.printStackTrace();    
                }
            }
        }
        // 遍歷行­(從第二行開始)
        for (int i = 1; i < rows; i++) {
            // 讀取左上端單元格(從第二行開始)
            HSSFRow row = sheet.getRow(i);
            // 行不為空
            if (row != null) {
                //準備當前行 所儲存值的map
                Map<String, Object> val=new HashMap<String, Object>();

                boolean isValidRow = false;

                // 遍歷列
                for (int j = 0; j < cells; j++) {
                    // 獲取到列的值­
                    try {
                        HSSFCell cell = row.getCell(j);
                        String cellValue = getCellValue(cell);
                        val.put(keys.get(j),cellValue); 
                        if(!isValidRow && cellValue!=null && cellValue.trim().length()>0){
                            isValidRow = true;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();        
                    }
                }
                //第I行所有的列資料讀取完畢,放入valuelist
                if(isValidRow){
                    valueList.add(val);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        fis.close();
    }
    return valueList;
}


/
 * 讀取2007-2013格式
 * @param filePath 檔案路徑
 * @return
 * @throws java.io.IOException
 */
@SuppressWarnings("rawtypes")
public static List<Map> readExcel2007(String filePath) throws IOException{
    List<Map> valueList=new ArrayList<Map>();
    FileInputStream fis =null;
    try {
        fis =new FileInputStream(filePath);
        XSSFWorkbook xwb = new XSSFWorkbook(fis);   // 構造 XSSFWorkbook 物件,strPath 傳入檔案路徑
        XSSFSheet sheet = xwb.getSheetAt(0);            // 讀取第一章表格內容
        // 定義 row、cell
        XSSFRow row;
        // 迴圈輸出表格中的第一行內容   表頭
        Map<Integer, String> keys=new HashMap<Integer, String>();
        row = sheet.getRow(0);
        if(row !=null){
            //System.out.println("j = row.getFirstCellNum()::"+row.getFirstCellNum());
            //System.out.println("row.getPhysicalNumberOfCells()::"+row.getPhysicalNumberOfCells());
            for (int j = row.getFirstCellNum(); j <=row.getPhysicalNumberOfCells(); j++) {
                // 通過 row.getCell(j).toString() 獲取單元格內容,
                if(row.getCell(j)!=null){
                    if(!row.getCell(j).toString().isEmpty()){
                        keys.put(j, row.getCell(j).toString());
                    }
                }else{
                    keys.put(j, "K-R1C"+j+"E");
                }
            }
        }
        // 迴圈輸出表格中的從第二行開始內容
        for (int i = sheet.getFirstRowNum() + 1; i <= sheet.getPhysicalNumberOfRows(); i++) {
            row = sheet.getRow(i);
            if (row != null) {
                boolean isValidRow = false;
                Map<String, Object> val = new HashMap<String, Object>();
                for (int j = row.getFirstCellNum(); j <= row.getPhysicalNumberOfCells(); j++) {
                    XSSFCell cell = row.getCell(j);
                    if (cell != null) {
                        String cellValue = null;
                        if(cell.getCellType()==XSSFCell.CELL_TYPE_NUMERIC){
                            if(DateUtil.isCellDateFormatted(cell)){
                                cellValue = new DataFormatter().formatRawCellContents(cell.getNumericCellValue(), 0, "yyyy-MM-dd HH:mm:ss");
                            }
                            else{
                                cellValue = String.valueOf(cell.getNumericCellValue());
                            }
                        }
                        else{
                            cellValue = cell.toString();
                        }
                        if(cellValue!=null&&cellValue.trim().length()<=0){
                            cellValue=null;
                        }
                        val.put(keys.get(j), cellValue);
                        if(!isValidRow && cellValue!= null && cellValue.trim().length()>0){
                            isValidRow = true;
                        }
                    }
                }

                // 第I行所有的列資料讀取完畢,放入valuelist
                if (isValidRow) {
                    valueList.add(val);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        fis.close();
    }

    return valueList;
}

4.3、其他封裝方法

/
 * 檔案操作 獲取副檔名
 * 
 * @Author: sunny
 * @param filename
 *            檔名稱包含副檔名
 * @return
 */
public static String getExtensionName(String filename) {
    if ((filename != null) && (filename.length() > 0)) {
        int dot = filename.lastIndexOf('.');
        if ((dot > -1) && (dot < (filename.length() - 1))) {
            return filename.substring(dot + 1);
        }
    }
    return filename;
}

/ -----------上傳檔案,工具方法--------- */
private static final int BUFFER_SIZE = 2 * 1024;

/
 * 
 * @param src
 *            原始檔
 * @param dst
 *            目標位置
 */
private static void copy(File src, File dst) {
    InputStream in = null;
    OutputStream out = null;
    try {
        in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
        out = new BufferedOutputStream(new FileOutputStream(dst),
                BUFFER_SIZE);
        byte[] buffer = new byte[BUFFER_SIZE];
        int len = 0;
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (null != in) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (null != out) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

/
 * 上傳copy檔案方法(for MultipartFile)
 * @param savePath 在linux上要儲存完整路徑
 * @param newname 新的檔名稱, 採用系統時間做檔名防止中文報錯的問題
 * @throws Exception
 */
public static void copy(MultipartFile file,String savePath,String newname) throws Exception {
    try {
        File targetFile = new File(savePath,newname);
        if (!targetFile.exists()) {
            //判斷資料夾是否存在,不存在就建立
            targetFile.mkdirs();
        }

        file.transferTo(targetFile);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

private static String getCellValue(HSSFCell cell) {
    DecimalFormat df = new DecimalFormat("#");
    String cellValue=null;
    if (cell == null)
        return null;
    switch (cell.getCellType()) {
        case HSSFCell.CELL_TYPE_NUMERIC:
            if(HSSFDateUtil.isCellDateFormatted(cell)){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                cellValue=sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
                break;
            }
            cellValue=df.format(cell.getNumericCellValue());
            break;
        case HSSFCell.CELL_TYPE_STRING:         
            cellValue=String.valueOf(cell.getStringCellValue());
            break;
        case HSSFCell.CELL_TYPE_FORMULA:
            cellValue=String.valueOf(cell.getCellFormula());
            break;
        case HSSFCell.CELL_TYPE_BLANK:
            cellValue=null;
            break;
        case HSSFCell.CELL_TYPE_BOOLEAN:
            cellValue=String.valueOf(cell.getBooleanCellValue());
            break;
        case HSSFCell.CELL_TYPE_ERROR:
            cellValue=String.valueOf(cell.getErrorCellValue());
            break;
    }
    if(cellValue!=null&&cellValue.trim().length()<=0){
        cellValue=null;
    }
    return cellValue;
}

5、下載操作

5.1、下載頁面

window.location.href = ctx + "/operate/download?fileName="
            + encodeURI(file);
前端直接呼叫後臺方法,這邊由於涉及到中文亂碼的問題,所有此處用encodeURI處理,後臺直接解碼即可。

5.2、下載controller部分

@RequestMapping(value = "/download", method = RequestMethod.GET)
public void download(HttpServletRequest request ,HttpServletResponse response){
    try {
        /**後臺解碼encodeURI()*/
        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("fileName");
        name = new String(name.getBytes("ISO-8859-1"), "UTF-8");
        File file = new File(request.getSession().getServletContext().getRealPath("/upload/"+name));
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;filename="+  new String(name.getBytes("utf-8"),"ISO-8859-1"));
        response.setHeader("Content-Length", "" + file.length());
        //System.out.println(file.getAbsolutePath());

        InputStream in = new BufferedInputStream(new FileInputStream(file));
        OutputStream out = response.getOutputStream();
        byte[] b = new byte[1024];
        int length;
        while((length = in.read(b)) != -1) {
            out.write(b, 0, length);
        }
        in.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
此處還有更好的方式可以實現,沒有必要暴露request介面在外面。

5.3、寫入excel操作

package com.fable.attendance.util;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;  
import java.io.OutputStream;  
import java.lang.reflect.Field;  
import java.lang.reflect.InvocationTargetException;  
import java.lang.reflect.Method;  
import java.text.SimpleDateFormat;  
import java.util.ArrayList;
import java.util.Collection;  
import java.util.Date;  
import java.util.Iterator;  
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;  
import java.util.regex.Pattern;  
import org.apache.poi.hssf.usermodel.HSSFCell;  
import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;  
import org.apache.poi.hssf.usermodel.HSSFComment;  
import org.apache.poi.hssf.usermodel.HSSFFont;  
import org.apache.poi.hssf.usermodel.HSSFPatriarch;  
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 com.fable.attendance.bean.Operate;

public class ExportExcel<T> {

public void exportExcel(Collection<T> dataset, OutputStream out)  
{  
    exportExcel("測試POI匯出EXCEL文件", null, dataset, out, "yyyy-MM-dd");  
}  

public void exportExcel(String[] headers, Collection<T> dataset,  
        OutputStream out)  
{  
    exportExcel("測試POI匯出EXCEL文件", headers, dataset, out, "yyyy-MM-dd");  
}  

public void exportExcel(String[] headers, Collection<T> dataset,  
        OutputStream out, String pattern)  
{  
    exportExcel("測試POI匯出EXCEL文件", headers, dataset, out, pattern);  
}  


@SuppressWarnings({"deprecation" })  
public void exportExcel(String title, String[] headers,  
        OutputStream out, Map<String, List<Operate>> map) {
    // 宣告一個工作薄  
    HSSFWorkbook workbook = new HSSFWorkbook();

    // 生成一個樣式  
    HSSFCellStyle style = workbook.createCellStyle();  
    // 設定這些樣式  
    style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);  
    style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
    style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
    style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
    style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
    style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
    // 生成一個字型  
    HSSFFont font = workbook.createFont();  
    font.setColor(HSSFColor.VIOLET.index);  
    font.setFontHeightInPoints((short) 12);  
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
    // 把字型應用到當前的樣式  
    style.setFont(font);  
    // 生成並設定另一個樣式  
    HSSFCellStyle style2 = workbook.createCellStyle();  
    style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);  
    style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
    style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
    style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
    style2.setBorderRight(HSSFCellStyle.BORDER_THIN);  
    style2.setBorderTop(HSSFCellStyle.BORDER_THIN);  
    style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
    style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
    // 生成另一個字型  
    HSSFFont font2 = workbook.createFont();  
    font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);  
    // 把字型應用到當前的樣式  
    style2.setFont(font2);

    //迴圈map物件
    for (Map.Entry<String, List<Operate>> entry : map.entrySet()) {  
        String sheetTitle = entry.getKey();
        List<Operate> operates = entry.getValue();

        // 生成一個表格  
        HSSFSheet sheet = workbook.createSheet(sheetTitle);  
        // 設定表格預設列寬度為15個位元組  
        sheet.setDefaultColumnWidth((short) 15); 

        // 宣告一個畫圖的頂級管理器  
        //HSSFPatriarch patriarch = sheet.createDrawingPatriarch();  
        // 定義註釋的大小和位置,詳見文件  

// HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
// 0, 0, 0, (short) 4, 2, (short) 6, 5));
// 設定註釋內容
//comment.setString(new HSSFRichTextString(“可以在POI中添加註釋!”));
// 設定註釋作者,當滑鼠移動到單元格上是可以在狀態列中看到該內容.
//comment.setAuthor(“leno”);

        // 產生表格標題行  
        HSSFRow row = sheet.createRow(0);  
        for (short i = 0; i < headers.length; i++) {  
            HSSFCell cell = row.createCell(i);  
            cell.setCellStyle(style);  
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);  
            cell.setCellValue(text);  
        }

        //遍歷集合資料,產生資料行
        for(int i = 0; i < operates.size(); i++) {
            Operate operate = operates.get(i);
            HSSFRow dataRow = sheet.createRow(i + 1);

            //姓名
            HSSFCell cell = dataRow.createCell(0);
            cell.setCellStyle(style2);
            cell.setCellValue(operate.getName());

            //遲到
            cell = dataRow.createCell(1);
            cell.setCellValue(operate.getLate());

            //早退
            cell = dataRow.createCell(2);
            cell.setCellValue(operate.getEarly());


        }

    } 

    try {
        workbook.write(out);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
}

/** 
 * 這是一個通用的方法,利用了JAVA的反射機制,可以將放置在JAVA集合中並且符號一定條件的資料以EXCEL 的形式輸出到指定IO裝置上 
 *  
 * @param title 
 *            表格標題名 
 * @param headers 
 *            表格屬性列名陣列 
 * @param dataset 
 *            需要顯示的資料集合,集合中一定要放置符合javabean風格的類的物件。此方法支援的 
 *            javabean屬性的資料型別有基本資料型別及String,Date,byte[](圖片資料) 
 * @param out 
 *            與輸出裝置關聯的流物件,可以將EXCEL文件匯出到本地檔案或者網路中 
 * @param pattern 
 *            如果有時間資料,設定輸出格式。預設為"yyy-MM-dd" 
 */  
@SuppressWarnings({ "unchecked", "deprecation" })  
public void exportExcel(String title, String[] headers,  
        Collection<T> dataset, OutputStream out, String pattern)  
{  
    // 宣告一個工作薄  
    HSSFWorkbook workbook = new HSSFWorkbook();  
    // 生成一個表格  
    HSSFSheet sheet = workbook.createSheet(title);  
    // 設定表格預設列寬度為15個位元組  
    sheet.setDefaultColumnWidth((short) 15);  
    // 生成一個樣式  
    HSSFCellStyle style = workbook.createCellStyle();  
    // 設定這些樣式  
    style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);  
    style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
    style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
    style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
    style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
    style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
    // 生成一個字型  
    HSSFFont font = workbook.createFont();  
    font.setColor(HSSFColor.VIOLET.index);  
    font.setFontHeightInPoints((short) 12);  
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
    // 把字型應用到當前的樣式  
    style.setFont(font);  
    // 生成並設定另一個樣式  
    HSSFCellStyle style2 = workbook.createCellStyle();  
    style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);  
    style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
    style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
    style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
    style2.setBorderRight(HSSFCellStyle.BORDER_THIN);  
    style2.setBorderTop(HSSFCellStyle.BORDER_THIN);  
    style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
    style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
    // 生成另一個字型  
    HSSFFont font2 = workbook.createFont();  
    font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);  
    // 把字型應用到當前的樣式  
    style2.setFont(font2);  

    // 宣告一個畫圖的頂級管理器  
    HSSFPatriarch patriarch = sheet.createDrawingPatriarch();  
    // 定義註釋的大小和位置,詳見文件  
    HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,  
            0, 0, 0, (short) 4, 2, (short) 6, 5));  
    // 設定註釋內容  
    //comment.setString(new HSSFRichTextString("可以在POI中添加註釋!"));  
    // 設定註釋作者,當滑鼠移動到單元格上是可以在狀態列中看到該內容.  
    //comment.setAuthor("leno");  

    // 產生表格標題行  
    HSSFRow row = sheet.createRow(0);  
    for (short i = 0; i < headers.length; i++)  
    {  
        HSSFCell cell = row.createCell(i);  
        cell.setCellStyle(style);  
        HSSFRichTextString text = new HSSFRichTextString(headers[i]);  
        cell.setCellValue(text);  
    }  

    // 遍歷集合資料,產生資料行  
    Iterator<T> it = dataset.iterator();  
    int index = 0;  
    while (it.hasNext())  
    {  
        index++;  
        row = sheet.createRow(index);  
        T t = (T) it.next();  
        // 利用反射,根據javabean屬性的先後順序,動態呼叫getXxx()方法得到屬性值  
        Field[] fields = t.getClass().getDeclaredFields();  
        for (short i = 0; i < fields.length; i++)  
        {  
            HSSFCell cell = row.createCell(i);  
            cell.setCellStyle(style2);  
            Field field = fields[i];  
            String fieldName = field.getName();  
            String getMethodName = "get"  
                    + fieldName.substring(0, 1).toUpperCase()  
                    + fieldName.substring(1);  
            try  
            {  
                Class tCls = t.getClass();  
                Method getMethod = tCls.getMethod(getMethodName,  
                        new Class[]  
                        {});  
                Object value = getMethod.invoke(t, new Object[]  
                {});  
                // 判斷值的型別後進行強制型別轉換  
                String textValue = null;  

                if (value instanceof Boolean)  
                {  
                    boolean bValue = (Boolean) value;  
                    textValue = "男";  
                    if (!bValue)  
                    {  
                        textValue = "女";  
                    }  
                }  
                else if (value instanceof Date)  
                {  
                    Date date = (Date) value;  
                    SimpleDateFormat sdf = new SimpleDateFormat(pattern);  
                    textValue = sdf.format(date);  
                }  
                else if (value instanceof byte[])  
                {  
                    // 有圖片時,設定行高為60px;  
                    row.setHeightInPoints(60);  
                    // 設定圖片所在列寬度為80px,注意這裡單位的一個換算  
                    sheet.setColumnWidth(i, (short) (35.7 * 80));  
                    // sheet.autoSizeColumn(i);  
                    byte[] bsValue = (byte[]) value;  
                    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,  
                            1023, 255, (short) 6, index, (short) 6, index);  
                    anchor.setAnchorType(2);  
                    patriarch.createPicture(anchor, workbook.addPicture(  
                            bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));  
                }  
                else  
                {  
                    // 其它資料型別都當作字串簡單處理  
                    textValue = value.toString();  
                }  

                // 如果不是圖片資料,就利用正則表示式判斷textValue是否全部由數字組成  
                if (textValue != null)  
                {  
                    Pattern p = Pattern.compile("^//d+(//.//d+)?$");  
                    Matcher matcher = p.matcher(textValue);  
                    if (matcher.matches())  
                    {  
                        // 是數字當作double處理  
                        cell.setCellValue(Double.parseDouble(textValue));  
                    }  
                    else  
                    {  
                        HSSFRichTextString richString = new HSSFRichTextString(  
                                textValue);  
                        HSSFFont font3 = workbook.createFont();  
                        font3.setColor(HSSFColor.BLUE.index);  
                        richString.applyFont(font3);  
                        cell.setCellValue(richString);  
                    }  
                }  
            }  
            catch (SecurityException e)  
            {  
                e.printStackTrace();  
            }  
            catch (NoSuchMethodException e)  
            {  
                e.printStackTrace();  
            }  
            catch (IllegalArgumentException e)  
            {  
                e.printStackTrace();  
            }  
            catch (IllegalAccessException e)  
            {  
                e.printStackTrace();  
            }  
            catch (InvocationTargetException e)  
            {  
                e.printStackTrace();  
            }  
            finally  
            {  
                // 清理資源  
            }  
        }  
    }  
    try  
    {  
        workbook.write(out);  
    }  
    catch (IOException e)  
    {  
        e.printStackTrace();  
    }  
}  

public static void main(String[] args) {
    ExportExcel<Operate> ex = new ExportExcel<Operate>();
    String[] headers = {"姓名","遲到","早退","曠工","加班","請假","外出","出差","應扣","實際扣"};

    List<Operate> dataset = new ArrayList<Operate>();

    try {
        String file = "E://test.xls";
        OutputStream out = new FileOutputStream(file);
        ex.exportExcel(headers, dataset, out);
        out.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
          e.printStackTrace();
      }
}

}