欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java使用poi組件導(dǎo)出Excel格式數(shù)據(jù)

 更新時間:2020年02月20日 16:15:49   作者:Miss小恢灰丶  
這篇文章主要介紹了Java使用poi組件導(dǎo)出Excel格式數(shù)據(jù),需要的朋友可以參考下

在做管理系統(tǒng)的時候,我想Excel的導(dǎo)出是我們很難規(guī)避掉的,而且這也是個很實用很人性化的功能。

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

POI組件

poi組件是由Apache提供的組件包,主要職責(zé)是為我們的Java程序提供對于office文檔的相關(guān)操作。本文主要是它對于Excel操作的一個介紹。

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

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

POI組件基本介紹

使用的時候我們可以發(fā)現(xiàn)poi組件為我們提供的操作Excel的相關(guān)類都是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用于創(chuàng)建注釋的位置。
  12. HSSFColor:顏色對象。
  13. HSSFDateUtil:日期輔助工具
  14. HSSFPrintSetup:打印輔助工具
  15. HSSFErrorConstants:錯誤信息表

POI組件基本操作

1.HSSFWorkbook創(chuàng)建‘Excel文件對象'

//創(chuàng)建Excel對象
HSSFWorkbook workbook = new HSSFWorkbook();

2.使用workbook 對象創(chuàng)建工作表對象

//創(chuàng)建工作表單
HSSFSheet sheet = workbook.createSheet("對象報表"); 

3.創(chuàng)建行和操作單元格對象

//創(chuàng)建HSSFRow對象 (行)
HSSFRow row = sheet.createRow(0); 

//創(chuàng)建HSSFCell對象 (單元格)
HSSFCell cell=row.createCell(0); 

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

4.保存Excel文件

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

workbook.write(output); 

output.flush(); 

個性化導(dǎo)出—樣式設(shè)置

這邊我列舉出部分常用的樣式設(shè)置的方法!

1.合并單元格,設(shè)置寬、高

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

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

2.設(shè)置單元格樣式

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

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

3.設(shè)置字體

// 實例化字體對象
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); 
// 將字體應(yīng)用于單元格樣式中
cellStyle.setFont(font);

個人應(yīng)用

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

處理的action

    //用于導(dǎo)出的數(shù)據(jù)集合
    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導(dǎo)出工具類
      ExportExcel<PBillBean> ex = new ExportExcel<PBillBean>();
      //導(dǎo)出的標題列
      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();// 如果文件不存在則創(chuàng)建文件夾
      }
      //文件路徑
      path = path + File.separator + filename;
      tempFile = new File(path);  //初始化臨時文件
      //輸出流
      OutputStream out = new FileOutputStream(tempFile);
      //實例化Excel表格
      HSSFWorkbook workbook = new HSSFWorkbook();
      //創(chuàng)建工作表單
      String[] sheetNames = { "對賬報表" };
      for (int i = 0; i < sheetNames.length; i++) {
        workbook.createSheet(sheetNames[i]);
      }
      //導(dǎo)出到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();
      // 設(shè)置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();// 刪除臨時文件
      }
    }

導(dǎo)出Excel工具類

public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern,HSSFWorkbook workbook) 
  { 
    // 聲明一個工作薄  生成一個表格 
    HSSFSheet sheet = workbook.getSheet(title);
    // 設(shè)置表格默認列寬度為15個字節(jié) 
    sheet.setDefaultColumnWidth((short) 15); 
    // 生成一個樣式 
    HSSFCellStyle style = workbook.createCellStyle(); 
    // 設(shè)置這些樣式 
    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); 
    // 把字體應(yīng)用到當前的樣式 
    style.setFont(font); 
    // 生成并設(shè)置另一個樣式 
    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); 
    // 把字體應(yīng)用到當前的樣式 
    style2.setFont(font2); 
    // 聲明一個畫圖的頂級管理器 
    HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); 
    // 定義注釋的大小和位置,詳見文檔 
    HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5)); 
    // 設(shè)置注釋內(nèi)容 
    comment.setString(new HSSFRichTextString("可以在POI中添加注釋!")); 
    // 設(shè)置注釋作者,當鼠標移動到單元格上是可以在狀態(tài)欄中看到該內(nèi)容. 
    comment.setAuthor("leno"); 

    // 產(chǎn)生表格標題行 
    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); 
    } 
    // 遍歷集合數(shù)據(jù),產(chǎn)生數(shù)據(jù)行 
    Iterator<T> it = dataset.iterator(); 
    int index = 0; 
    while (it.hasNext()) 
    { 
      index++; 
      row = sheet.createRow(index); 
      T t = (T) it.next(); 
      // 利用反射,根據(jù)javabean屬性的先后順序,動態(tài)調(diào)用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[] {}); 
          // 判斷值的類型后進行強制類型轉(zhuǎn)換 
          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[]) 
          { 
            // 有圖片時,設(shè)置行高為60px; 
            row.setHeightInPoints(60); 
            // 設(shè)置圖片所在列寬度為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 
          { 
            // 其它數(shù)據(jù)類型都當作字符串簡單處理 
            textValue = value == null? "": value.toString(); 
          } 
          // 如果不是圖片數(shù)據(jù),就利用正則表達式判斷textValue是否全部由數(shù)字組成 
          if (textValue != null) 
          { 
            Pattern p = Pattern.compile("^//d+(//.//d+)?$"); 
            Matcher matcher = p.matcher(textValue); 
            if (matcher.matches()) 
            { 
              // 是數(shù)字當作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 
        { 
          // 清理資源 
        } 
      } 
    } 
  }

小結(jié)

Excel數(shù)據(jù)的導(dǎo)出大功告成了,個人感覺這個導(dǎo)出的工具類還是很好用的,希望大家能喜歡!

更多關(guān)于Java使用poi組件導(dǎo)出Excel格式數(shù)據(jù)文章請查看下面的相關(guān)鏈接

相關(guān)文章

  • Kotlin + Retrofit + RxJava簡單封裝使用詳解

    Kotlin + Retrofit + RxJava簡單封裝使用詳解

    這篇文章主要介紹了Kotlin + Retrofit + RxJava簡單封裝使用詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-07-07
  • Java 關(guān)鍵字 速查表介紹

    Java 關(guān)鍵字 速查表介紹

    下面小編就為大家?guī)硪黄狫ava 關(guān)鍵字 速查表介紹。小編覺得聽不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-04-04
  • 深入淺析HashMap key和value能否為null

    深入淺析HashMap key和value能否為null

    HashMap的key和value可為null,線程不安全,HashTable的key和value均不可為null,線程安全,ConcurrentHashMap在多線程場景下使用,key和value也不能為null,還對它們進行了測試和底層代碼分析,本文介紹HashMap key和value能否為null,感興趣的朋友跟隨小編一起看看吧
    2025-04-04
  • java實現(xiàn)后臺返回base64圖形編碼

    java實現(xiàn)后臺返回base64圖形編碼

    這篇文章主要介紹了java實現(xiàn)后臺返回base64圖形編碼,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • SpringBoot集成Redis使用Cache緩存的實現(xiàn)方法

    SpringBoot集成Redis使用Cache緩存的實現(xiàn)方法

    SpringBoot通過配置RedisConfig類和使用Cache注解可以輕松集成Redis實現(xiàn)緩存,主要包括@EnableCaching開啟緩存,自定義key生成器,改變序列化規(guī)則,以及配置RedisCacheManager,本文為使用SpringBoot與Redis處理緩存提供了詳實的指導(dǎo)和示例,感興趣的朋友一起看看吧
    2024-10-10
  • SpringBoot對接clerk實現(xiàn)用戶信息獲取功能

    SpringBoot對接clerk實現(xiàn)用戶信息獲取功能

    Clerk是一個提供身份驗證和用戶管理的服務(wù),可以幫助開發(fā)者快速集成這些功能,下面我們就來看看如何使用Spring?Boot對接Clerk實現(xiàn)用戶信息的獲取吧
    2025-02-02
  • Springboot?上傳文件或頭像(MultipartFile、transferTo)

    Springboot?上傳文件或頭像(MultipartFile、transferTo)

    本文主要介紹了Springboot?上傳文件或頭像(MultipartFile、transferTo),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-04-04
  • SpringMVC開發(fā)中十大常見問題深度解析與解決方案

    SpringMVC開發(fā)中十大常見問題深度解析與解決方案

    在Java Web開發(fā)領(lǐng)域,SpringMVC作為一款主流的Web框架,憑借其強大的功能和便捷的開發(fā)體驗深受開發(fā)者喜愛,然而,在實際使用過程中,開發(fā)者常常會遇到各種各樣的“坑”,本文將針對SpringMVC開發(fā)中常見的十大問題,需要的朋友可以參考下
    2025-06-06
  • Java線程生命周期的終止與復(fù)位

    Java線程生命周期的終止與復(fù)位

    這篇文章主要介紹了Java線程生命周期的終止與復(fù)位,Java的線程狀態(tài)描述放在Thread類里面的枚舉類State中.總共包含了6中狀態(tài),具體詳情需要的小伙伴可以參考一下文章描述
    2022-07-07
  • SpringBoot配置的加載流程詳細分析

    SpringBoot配置的加載流程詳細分析

    了解內(nèi)部原理是為了幫助我們做擴展,同時也是驗證了一個人的學(xué)習(xí)能力,如果你想讓自己的職業(yè)道路更上一層樓,這些底層的東西你是必須要會的,這篇文章主要介紹了SpringBoot配置的加載流程
    2023-01-01

最新評論