poi 導出Excel 工具類

package com.nisco.dms.util;

import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
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.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 org.apache.poi.hssf.util.Region;
/**
 *
 * @author Bruce Xu
 *
 * @param <T>
 */
public class ExcelUtil<T> {   
   
    /** 
     * 導出Excel的方法 
     * @param title excel中的sheet名稱 
     * @param headers 表頭 
     * @param result 結果集 
     * @param out 輸出流 
     * @param pattern 時間格式 
     * @throws Exception 
     */   
    public void exportExcel(String title, String[] headers,String[] columns, Collection<T> result, OutputStream out, String pattern) throws Exception{   
        // 聲明一個工作薄   
        HSSFWorkbook workbook = new HSSFWorkbook();   
        // 生成一個表格   
        HSSFSheet sheet = workbook.createSheet(title);   
        // 設置表格默認列寬度爲20個字節   
        sheet.setDefaultColumnWidth((short)20);   
           
           
        // 生成一個樣式   
        HSSFCellStyle style = workbook.createCellStyle();   
        // 設置這些樣式   
        style.setFillForegroundColor(HSSFColor.GOLD.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);   
           
        // 指定當單元格內容顯示不下時自動換行   
        style.setWrapText(true);   
         
        // 聲明一個畫圖的頂級管理器  
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); 
        /* 
          
         以下可以用於設置導出的數據的樣式 
           
        // 生成並設置另一個樣式 
        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");*/   
           
           
        // 產生表格標題行   
        //表頭的樣式 
        HSSFCellStyle titleStyle = workbook.createCellStyle();// 創建樣式對象 
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);// 水平居中 
        titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中 
        // 設置字體 
        HSSFFont titleFont = workbook.createFont(); // 創建字體對象 
        titleFont.setFontHeightInPoints((short) 15); // 設置字體大小 
        titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 設置粗體 
      //  titleFont.setFontName("黑體"); // 設置爲黑體字 
        titleStyle.setFont(titleFont); 
        sheet.addMergedRegion(new Region(0,(short)0,0,(short)(headers.length-1)));//指定合併區域  
        HSSFRow rowHeader = sheet.createRow(0);   
        HSSFCell cellHeader = rowHeader.createCell((short)0);   //只能往第一格子寫數據,然後應用樣式,就可以水平垂直居中 
        HSSFRichTextString textHeader = new HSSFRichTextString(title);   
        cellHeader.setCellStyle(titleStyle); 
        cellHeader.setCellValue(textHeader); 
         
        HSSFRow row = sheet.createRow(1);   
        for (int i = 0; i < headers.length; i++) {   
            HSSFCell cell = row.createCell((short)i);   
            cell.setCellStyle(style);   
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);   
            cell.setCellValue(text);   
         }   
         // 遍歷集合數據,產生數據行   
         if(result != null){   
             int index = 2;   
             for(T t:result){  
             //  Field[] fields = t.getClass().getDeclaredFields(); 
                 row = sheet.createRow(index);   
                 index++; 
                 for(short i = 0; i < columns.length; i++) { 
                     HSSFCell cell = row.createCell(i); 
//                   Field field = fields[i]; 
//                   String fieldName = field.getName(); 
                     String fieldName = columns[i]; 
                     String getMethodName = "get" 
                         + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); 
                     Class tCls = t.getClass(); 
                     Method getMethod = tCls.getMethod(getMethodName, new Class[]{}); 
                    // getMethod.getReturnType().isInstance(obj);
                     Object value = getMethod.invoke(t, new Class[]{}); 
                     String textValue = null; 
                     if(value == null) { 
                         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(); 
                      } 
                      
                     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); 
                         } 
                      } 
                 } 
             }      
         }   
         workbook.write(out);   
     }   
 }  

 

 

調用示例:以springmvc爲例,導出數據庫記錄到Excel,彈出下載對話框

@RequestMapping(value="/exprotExcel")
 public @ResponseBody String exprotExcel(HttpServletResponse response,NjWorkLog njWorkLog,@RequestParam(value="createUserIds",required=false) String createUserIds,@RequestParam(value="workLogGrantUsersName",required=false)String workLogGrantUsersName,@RequestParam(value="strWorkEndDate",required=false)String strWorkEndDate)
 {
  
  ExcelUtil<NjWorkLog> excelUtil=new ExcelUtil<NjWorkLog>();
  OutputStream out=null;
  try
  {
   out = response.getOutputStream();// 取得輸出流  
   //out.flush();
             response.reset();// 清空輸出流  

             response.setHeader("Content-disposition", "attachment; filename="+new String("工作日誌".getBytes("GB2312"),"8859_1")+".xls");// 設定輸出文件頭  
             response.setContentType("application/msexcel");// 定義輸出類型

  }  catch (IOException e)
  {
   e.printStackTrace();
  } 
  String[] headers ={"跟蹤目標","工作時間","事項類型","項目名稱","完成情況自述","工作量","進度","配合人員","加班","作者","附件名稱"};
  String[]columns={ "strTarget", "strWorkDate", "dictTypeId", "projectId", "strDesc", "bdWorkload", "strSchedule", "strCooperate","isOverTime","createUserId", "strFileName"};
  if("on".equals(njWorkLog.getIsOverTime()))
   njWorkLog.setIsOverTime("1");
  else
   njWorkLog.setIsOverTime("");
  if(StringUtils.isNotBlank(createUserIds))
   njWorkLog.setTempArray(createUserIds.split(","));
  List<NjWorkLog> dataset=njWorkLogService.findMyAttentionExcel(njWorkLog);
  
  try
  {
   excelUtil.exportExcel("工作日誌", headers, columns, dataset, out, "");
   
  } catch (Exception e1)
  {
   e1.printStackTrace();
  }
  try
  {
   out.close();
  } catch (IOException e)
  {
   e.printStackTrace();
  }
  return null;
 }


 

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