1. 程式人生 > 程式設計 >Java使用poi元件匯出Excel格式資料

Java使用poi元件匯出Excel格式資料

在做管理系統的時候,我想Excel的匯出是我們很難規避掉的,而且這也是個很實用很人性化的功能。

Java中對於Excel的支援有很多種,比如說JXL,POI等。我這邊使用的是POI進行一個Excel的操作,下面我會簡單分享下POI元件的使用,以及我使用比較多一個工具類。

POI元件

poi元件是由Apache提供的元件包,主要職責是為我們的Java程式提供對於office文件的相關操作。本文主要是它對於Excel操作的一個介紹。

官方主頁:http://poi.apache.org/index.html

API文件:http://poi.apache.org/apidocs/index.html

POI元件基本介紹

使用的時候我們可以發現poi元件為我們提供的操作Excel的相關類都是HSSF開頭的,這些類主要是在org.apache.poi.hssf.usermodel這個包下面。裡面包涵有像Excel的物件,單元格的樣式,字型樣式以及部分的工具類。一下介紹幾個我們常用的類:

  1. HSSFWorkbook:Excel物件,相當於一個 .xls/.xlsx 檔案
  2. HSSFSheet:工作表物件,Excel檔案包涵的sheet,一個物件代表一個表單
  3. HSSFRow:表示表格中的行物件。
  4. HSSFCell:表示表格中的單元格物件。
  5. HSSFHeader:Excel文件Sheet的頁首。
  6. HSSFFooter:Excel文件Sheet的頁尾。
  7. HSSFDataFormat:日期格式。
  8. HSSFFont:字型物件。
  9. HSSFCellStyle:單元格樣式(對齊樣式、邊框等)
  10. HSSFComment:批註(註釋)。
  11. HSSFPatriarch:和HSSFComment用於建立註釋的位置。
  12. HSSFColor:顏色物件。
  13. HSSFDateUtil:日期輔助工具
  14. HSSFPrintSetup:列印輔助工具
  15. HSSFErrorConstants:錯誤資訊表

POI元件基本操作

1.HSSFWorkbook建立‘Excel檔案物件'

//建立Excel物件
HSSFWorkbook workbook = new HSSFWorkbook();

2.使用workbook 物件建立工作表物件

//建立工作表單
HSSFSheet sheet = workbook.createSheet("物件報表"); 

3.建立行和操作單元格物件

//建立HSSFRow物件 (行)
HSSFRow row = sheet.createRow(0); 

//建立HSSFCell物件 (單元格)
HSSFCell cell=row.createCell(0); 

//設定單元格的值 
cell.setCellValue("單元格中的中文"); 

4.儲存Excel檔案

//輸出Excel檔案 
FileOutputStream output=new FileOutputStream("d:\\workbook.xls"); 

workbook.write(output); 

output.flush(); 

個性化匯出—樣式設定

這邊我列舉出部分常用的樣式設定的方法!

1.合併單元格,設定寬、高

// 例項化樣式物件
HSSFCellStyle cellStyle = workbook.createCellStyle(); 
// 兩端對齊
cellStyle.setAlignment(HSSFCellStyle.ALIGN_JUSTIFY); 
// 垂直居中
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
// 填充圖案---填充方式
cellStyle.setFillPattern(HSSFCellStyle.DIAMONDS); 
// 設定前景色 (這個要寫在背景色的前面)
cellStyle.setFillForegroundColor(HSSFColor.RED.index); 
// 設定背景顏色 
cellStyle.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index); 
// 設定邊框
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_SLANTED_DASH_DOT); 
// 邊框顏色
cellStyle.setBottomBorderColor(HSSFColor.DARK_RED.index); 
// 日期展示格式 
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));  

//將樣式應用於單元格
cell.setCellStyle(cellStyle); 
//將樣式應用到行 
row.setRowStyle(cellStyle);

2.設定單元格樣式

// 例項化樣式物件
HSSFCellStyle cellStyle = workbook.createCellStyle(); 
// 兩端對齊
cellStyle.setAlignment(HSSFCellStyle.ALIGN_JUSTIFY); 
// 垂直居中
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
// 填充圖案---填充方式
cellStyle.setFillPattern(HSSFCellStyle.DIAMONDS); 
// 設定前景色 (這個要寫在背景色的前面)
cellStyle.setFillForegroundColor(HSSFColor.RED.index); 
// 設定背景顏色 
cellStyle.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index); 
// 設定邊框
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_SLANTED_DASH_DOT); 
// 邊框顏色
cellStyle.setBottomBorderColor(HSSFColor.DARK_RED.index); 
// 日期展示格式 
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));  

//將樣式應用於單元格
cell.setCellStyle(cellStyle); 
//將樣式應用到行 
row.setRowStyle(cellStyle);

3.設定字型

// 例項化字型物件
HSSFFont fontStyle = workbook.createFont(); 
// 字型
fontStyle.setFontName("宋體");  
// 高度 
fontStyle.setFontHeightInPoints((short)12);  
// 字型 
font.setColor(HSSFColor.BLUE.index); 
// 加粗 
fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); 
// 斜體  
font.setItalic(true); 
// 下劃線 
font.setUnderline(HSSFFont.U_SINGLE); 
// 將字型應用於單元格樣式中
cellStyle.setFont(font);

個人應用

下面給大家分享下個人的整體使用過程!

Java使用poi元件匯出Excel格式資料

處理的action

    //用於匯出的資料集合
    List<PBillBean> dataset = new ArrayList<PBillBean>();
    //填充dataset
    for (int i = 0; i < 10; i++) {
      PBillBean bean = new PBillBean();
      dataset.add(bean);
    }
    //臨時檔案
    File tempFile = null;
    try {
      //Excel匯出工具類
      ExportExcel<PBillBean> ex = new ExportExcel<PBillBean>();
      //匯出的標題列
      String[] headers = { "標題1","標題2","標題3","標題4","標題5","標題6" };
      //時間格式化
      SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
      //要儲存的檔名
      String filename = "bill_" + format.format(new Date()) + ".xls";
      //要儲存的根目錄
      String rootDir = request.getSession().getServletContext().getRealPath("/");
      //要儲存的目錄路徑
      String path = rootDir + File.separator + "tempfile";
      File saveDir = new File(path);
      if (!saveDir.exists()) {
        saveDir.mkdirs();// 如果檔案不存在則建立資料夾
      }
      //檔案路徑
      path = path + File.separator + filename;
      tempFile = new File(path);  //初始化臨時檔案
      //輸出流
      OutputStream out = new FileOutputStream(tempFile);
      //例項化Excel表格
      HSSFWorkbook workbook = new HSSFWorkbook();
      //建立工作表單
      String[] sheetNames = { "對賬報表" };
      for (int i = 0; i < sheetNames.length; i++) {
        workbook.createSheet(sheetNames[i]);
      }
      //匯出到Excel
      ex.exportExcel(sheetNames[0],headers,dataset,out,"yyyy-MM-dd HH:mm",workbook);
      try {
        //儲存檔案
        workbook.write(out);
      } catch (IOException e) {
        e.printStackTrace();
      }
      out.close();
      // 以流的形式下載檔案。
      BufferedInputStream fis = new BufferedInputStream(
          new FileInputStream(path));
      byte[] buffer = new byte[fis.available()];
      fis.read(buffer);
      fis.close();
      // 清空response
      response.reset();
      // 設定response的Header
      response.addHeader("Content-Disposition","attachment;filename="
          + new String(filename.getBytes()));
      response.addHeader("Content-Length","" + tempFile.length());
      OutputStream toClient = new BufferedOutputStream(
          response.getOutputStream());
      response.setContentType("application/vnd.ms-excel;charset=utf-8");
      toClient.write(buffer);
      toClient.flush();
      toClient.close();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (tempFile != null && tempFile.exists()) {
        tempFile.delete();// 刪除臨時檔案
      }
    }

匯出Excel工具類

public void exportExcel(String title,String[] headers,Collection<T> dataset,OutputStream out,String pattern,HSSFWorkbook workbook) 
  { 
    // 宣告一個工作薄  生成一個表格 
    HSSFSheet sheet = workbook.getSheet(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,(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,1023,255,index,index); 
            anchor.setAnchorType(2); 
            patriarch.createPicture(anchor,workbook.addPicture(bsValue,HSSFWorkbook.PICTURE_TYPE_JPEG)); 
          } 
          else 
          { 
            // 其它資料型別都當作字串簡單處理 
            textValue = value == null? "": 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 
        { 
          // 清理資源 
        } 
      } 
    } 
  }

小結

Excel資料的匯出大功告成了,個人感覺這個匯出的工具類還是很好用的,希望大家能喜歡!

更多關於Java使用poi元件匯出Excel格式資料文章請檢視下面的相關連結