Java使用Apache.POI中HSSFWorkbook導出到Excel的實現方法

使用Apache.POI中HSSFWorkbook導出到Excel,具體內容如下所示:

1.引入Poi依賴(3.12)

依賴如下:

<dependency>
   <groupId>org.apache.poi</groupId>
   <artifactId>poi</artifactId>
   <version>3.12</version>
</dependency>

2.創建實體類(User.java)

package com.kd.nm.entity.pojo;

/**
 * 實體類(User)
 *
 * author 小辰哥哥
 */
public class User {
 // 用戶編號
 private String userNo;
 // 用戶名稱
 private String userName;
 // 年齡
 private String age;

 // 無參構造
 public User() {
 }

 // 有參構造
 public User(String userNo, String userName, String age) {
  this.userNo = userNo;
  this.userName = userName;
  this.age = age;
 }

 // get與set方法進行封裝
 public String getUserNo() {
  return userNo;
 }

 public void setUserNo(String userNo) {
  this.userNo = userNo;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public String getAge() {
  return age;
 }

 public void setAge(String age) {
  this.age = age;
 }

 // 重新toString方法
 @Override
 public String toString() {
  return "User{" +
    "userNo='" + userNo + '\'' +
    ", userName='" + userName + '\'' +
    ", age='" + age + '\'' +
    '}';
 }
}

3.Excel相關工具類(ExcelUtil、ReflectUtil)

package com.kd.nm.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.*;

/**
 * Description : Excel相關工具類
 *
 * @author: 小辰哥哥
 *
 */
public class ExcelUtil {

 /**
  * 生成excel表格
  * @param heads 表頭內容
  * @param data 數據內容
  * @return
  */
 public static HSSFWorkbook creatExcel(Map<String, String> heads, List data) {

  // 聲明一個工作薄
  HSSFWorkbook workbook = new HSSFWorkbook();
  // 生成一個表格
  HSSFSheet sheet = workbook.createSheet();

  // 生成標題行樣式
  HSSFCellStyle headStyle = creatStyle(workbook, (short) 14);

  // 生成表格內容樣式
  HSSFCellStyle bodyStyle = creatStyle(workbook, (short) 10);

  // 標題元素
  List<String> keys = new ArrayList<String>(heads.keySet());

  // 像素單位
  short px = 1000;
  // 設置列寬
  for (int columnIndex = 0; columnIndex < keys.size(); columnIndex++) {

   sheet.setColumnWidth(columnIndex, 6 * px);
  }

  // 生成表格
  for (int rowNum = 0; rowNum <= data.size(); rowNum++) {

   // 創建行
   HSSFRow row = sheet.createRow(rowNum);

   for (int cellNum = 0; cellNum < keys.size(); cellNum++) {

    // 創建列
    HSSFCell cell = row.createCell(cellNum);

    // 標題
    if (rowNum == 0) {

     cell.setCellStyle(headStyle);
     cell.setCellValue(heads.get(keys.get(cellNum)));
    } else { // 內容

     cell.setCellStyle(bodyStyle);
     // 通過反射獲取
     cell.setCellValue(ReflectUtil.getValue(keys.get(cellNum), data.get(rowNum - 1)));
    }
   }
  }

  return workbook;
 }

 /**
  * 生成樣式
  * @param workbook
  * @param size
  * @return
  */
 public static HSSFCellStyle creatStyle(HSSFWorkbook workbook, short size) {

  HSSFCellStyle style = workbook.createCellStyle();
  style.setAlignment((HSSFCellStyle.ALIGN_CENTER));
  style.setVerticalAlignment((HSSFCellStyle.VERTICAL_CENTER));
  HSSFFont font = workbook.createFont();
  font.setFontHeightInPoints(size);
  font.setFontName("微軟雅黑");
  style.setFont(font);
  style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  style.setBorderTop(HSSFCellStyle.BORDER_THIN);
  style.setBorderRight(HSSFCellStyle.BORDER_THIN);
  style.setBorderLeft(HSSFCellStyle.BORDER_THIN);

  return style;
 }
}
package com.kd.nm.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ReflectionUtils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

/**
 * 反射工具包
 *
 * @author: 小辰哥哥
 */
public class ReflectUtil {

 private static final Logger logger = LoggerFactory.getLogger(ReflectUtil.class);

 public static String getValue(String key, Object obj) {

  String value = "";

  try {

   // 獲取當前屬性
   PropertyDescriptor pd = new PropertyDescriptor(key, obj.getClass());
   // 獲取get方法
   Method getMd = pd.getReadMethod();
   value = getMd.invoke(obj).toString();
  } catch (Exception e) {

   logger.error("獲取內容失敗!");
   e.printStackTrace();
  }

  return value;
 }

 public static void setValue(String key, String value, Object obj) {

  try {

   // 獲取當前屬性
   PropertyDescriptor pd = new PropertyDescriptor(key, obj.getClass());
   // 獲取set方法
   Method writeMd = pd.getWriteMethod();
   writeMd.invoke(obj, value);
  } catch (Exception e) {

   logger.error("設置內容失敗!");
   e.printStackTrace();
  }
 }
}

4.後端控制器代碼

@RequestMapping(value = "/exportExcel",method = RequestMethod.GET,produces = "application/json")
 public void exportExcel(HttpServletResponse httpServletResponse) throws IOException {

  // 表頭內容(可在前端設置,通過參數傳遞進來) Key是實體類的屬性值,value是表頭的lable
  Map<String,String> head = new HashMap<>();
  head.put("userNo","用戶編號");
  head.put("userName","用戶名稱");
  head.put("age","年齡");

  // 表格數據內容,模擬數據庫查詢出來的數據
  List<User> data = new ArrayList<>();
  data.add(new User("1","小辰哥哥","18"));
  data.add(new User("2","小豬妹妹","18"));
  data.add(new User("3","大豬哥哥","18"));
  
  
  // 生成工作薄
  HSSFWorkbook hssfWorkbook = ExcelUtil.creatExcel(head, data);

  // 定義文件名
  String fileName = "導出Excel表格";

  httpServletResponse.setHeader("Cache-Control", "max-age=0");
  httpServletResponse.setContentType("application/vnd.ms-excel");
  httpServletResponse.addHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"),
    "ISO-8859-1") + ".xls");

  OutputStream outputStream = httpServletResponse.getOutputStream();

  hssfWorkbook.write(outputStream);
  outputStream.flush();
  outputStream.close();
 }

5.訪問映射地址

接口訪問:

http://localhost:9090/FaultTreatment/api/standard/exportExcel

在這裡插入圖片描述


在這裡插入圖片描述

到此這篇關於Java使用Apache.POI中HSSFWorkbook導出到Excel的實現方法的文章就介紹到這瞭,更多相關Apache.POI中HSSFWorkbook導出到Excel內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀:

    None Found