工具類--Excel 導出poi

實現功能 --批量導出excel 文件,配置一個sheet多少條數據,根據查詢數據量的多少肯定生成幾個sheet頁。java

 

pom 文件導入ExcelUtils工具包,依賴於poi包。spring

<!-- https://mvnrepository.com/artifact/org.hellojavaer/poi-excel-utils -->
<dependency>
    <groupId>org.hellojavaer</groupId>
    <artifactId>poi-excel-utils</artifactId>
    <version>1.1.0-beta</version>
</dependency>apache

找到ExcelUtils工具包,重構代碼。app

package cn.enn.chaoscloud.master.utils;

import com.lkx.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.BeanUtils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
public class ExcelUtils implements Serializable {

private static final long serialVersionUID = 1L;

/**
* getMap:(將傳進來的表頭和表頭對應的屬性存進Map集合,表頭字段爲key,屬性爲value)
*
* @author likaixuan
* @param
* : String keyValue = "手機名稱:phoneName,顏色:color,售價:price";
* @return
* @since JDK 1.7
*/
public static Map<String, String> getMap(String keyValue) {
Map<String, String> map = new HashMap<String, String>();
if (keyValue != null) {
String[] str = keyValue.split(",");
for (String element : str) {
String[] str2 = element.split(":");
map.put(str2[0], str2[1]);
}
}
return map;
}

/**
* @author likaixuan
* @param
* @return List
* @Date 2018年5月9日 21:42:24
* @since JDK 1.7
*/
public static List<String> getList(String keyValue) {
List<String> list = new ArrayList<String>();
if (keyValue != null) {
String[] str = keyValue.split(",");

for (String element : str) {
String[] str2 = element.split(":");
list.add(str2[0]);
}
}
return list;
}

/**
* setter:(反射的set方法給屬性賦值)
*
* @author likaixuan
* @param obj
* 具體的類
* @param att
* 類的屬性
* @param value
* 賦予屬性的值
* @param type
* 屬性是哪一種類型 好比:String double boolean等類型
* @throws Exception
* @since JDK 1.7
*/
public static void setter(Object obj, String att, Object value, Class<?> type, int row, int col, Object key)
throws Exception {
try {
Method method = obj.getClass().getMethod("set" + StringUtil.toUpperCaseFirstOne(att), type);
method.invoke(obj, value);
} catch (Exception e) {
throw new Exception("第" + (row + 1) + " 行 " + (col + 1) + "列 屬性:" + key + " 賦值異常 " + e);
}

}

/**
* getAttrVal:(反射的get方法獲得屬性值)
*
* @author likaixuan
* @param obj
* 具體的類
* @param att
* 類的屬性
* @param
*
* @param type
* 屬性是哪一種類型 好比:String double boolean等類型
* @throws Exception
* @since JDK 1.7
*/
public static Object getAttrVal(Object obj, String att, Class<?> type) throws Exception {
try {
Method method = obj.getClass().getMethod("get" + StringUtil.toUpperCaseFirstOne(att));
Object value = new Object();
value = method.invoke(obj);
return value;
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}

}

/**
* getValue:(獲得Excel列的值)
*
* @author likaixuan
* @param
* @return
* @throws Exception
* @since JDK 1.7
*/
public static void getValue(Cell cell, Object obj, String attr, Class attrType, int row, int col, Object key)
throws Exception {
Object val = null;
if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
val = cell.getBooleanCellValue();

} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
if (DateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
if (attrType == String.class) {
val = sdf.format(DateUtil.getJavaDate(cell.getNumericCellValue()));
} else {
val = dateConvertFormat(sdf.format(DateUtil.getJavaDate(cell.getNumericCellValue())));
}
} catch (ParseException e) {
throw new Exception("第" + (row + 1) + " 行 " + (col + 1) + "列 屬性:" + key + " 日期格式轉換錯誤 ");
}
} else {
if (attrType == String.class) {
cell.setCellType(Cell.CELL_TYPE_STRING);
val = cell.getStringCellValue();
} else if (attrType == BigDecimal.class) {
val = new BigDecimal(cell.getNumericCellValue());
} else if (attrType == long.class) {
val = (long) cell.getNumericCellValue();
} else if (attrType == Double.class) {
val = cell.getNumericCellValue();
} else if (attrType == Float.class) {
val = (float) cell.getNumericCellValue();
} else if (attrType == int.class || attrType == Integer.class) {
val = (int) cell.getNumericCellValue();
} else if (attrType == Short.class) {
val = (short) cell.getNumericCellValue();
} else {
val = cell.getNumericCellValue();
}
}

} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
val = cell.getStringCellValue();
}

setter(obj, attr, val, attrType, row, col, key);
}

/**
* exportExcel:(導出Excel)
*
* @author likaixuan
* @param
* @return
* @throws Exception
* @since JDK 1.7
*/
public static void exportExcel(HSSFWorkbook wb,OutputStream outputStream, String keyValue, List<?> list, String classPath,int sheetNum,int pageNum)
throws Exception {

Map<String, String> map = getMap(keyValue);
List<String> keyList = getList(keyValue);

Class<?> demo = null;
demo = Class.forName(classPath);
Object obj = demo.newInstance();

// 創建新的sheet對象(excel的表單)
String sheetName = "sheet"+String.valueOf(sheetNum);
HSSFSheet sheet = wb.createSheet(sheetName);
// 聲明樣式
HSSFCellStyle style = wb.createCellStyle();
// 居中顯示
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 在sheet裏建立第一行爲表頭,參數爲行索引(excel的行),能夠是0~65535之間的任何一個
HSSFRow rowHeader = sheet.createRow(0);
// 建立單元格並設置單元格內容

// 存儲屬性信息
Map<String, String> attMap = new HashMap();
int index = 0;

for (String key : keyList) {
rowHeader.createCell(index).setCellValue(key);
attMap.put(Integer.toString(index), map.get(key).toString());
index++;
}

// 在sheet裏建立表頭下的數據
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
HSSFRow row = sheet.createRow(i + 1);
for (int j = 0; j < map.size(); j++) {

Class<?> attrType = BeanUtils.findPropertyType(attMap.get(Integer.toString(j)),
new Class[] { obj.getClass() });

Object value = getAttrVal(list.get(i), attMap.get(Integer.toString(j)), attrType);
if (null == value) {
value = "";
}
row.createCell(j).setCellValue(value.toString());
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
}
}
// 輸出Excel文件
try {
if(sheetNum == pageNum || pageNum == 0){
wb.write(outputStream);
outputStream.close();
}
} catch (FileNotFoundException e) {
throw new FileNotFoundException("導出失敗!" + e);
} catch (IOException e) {
throw new IOException("導出失敗!" + e);
}

}

/**
* String類型日期轉爲Date類型
*
* @param dateStr
* @return
* @throws ParseException
* @throws Exception
*/
public static Date dateConvertFormat(String dateStr) throws ParseException {
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
date = format.parse(dateStr);
return date;
}
}

調用封裝工具類
public static final int page_size = 10000;

@PostMapping("queryUnusedGasListExcel")public byte[] queryUnusedGasListExcel(@RequestBody UnusedGasDTO unusedGasDTO) throws Exception{    byte[] bytes = null;    try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()){        int list_count  = unusedGasService.findCountList(unusedGasDTO);        // 根據行數求數據提取次數        int export_times = list_count % page_size > 0 ? list_count / page_size                + 1 : list_count / page_size;        // 建立HSSFWorkbook對象(excel的文檔對象)        HSSFWorkbook wb = new HSSFWorkbook();        for (int j = 0; j < export_times; j++) {            unusedGasDTO.setPositionNum(j*page_size);            unusedGasDTO.setShowNum(page_size);            List<UnusedGasVO> list = unusedGasService.downLoadByList(unusedGasDTO);            int len = list.size() < page_size ? list.size() : page_size;            String keyValue = "客戶名稱:customerName,房產名稱:houseName,表鋼號:meterCode,餘額(元):balance,表底數:meterBase,未用氣天數:unusedGasDays,客戶類型編碼:customerCode,聯繫方式:customerTel,表型名稱:metersTypeName,合約號:contractNum," +                    "集團id:groupId,集團編碼:groupName,公司id:companyId,公司編碼:companyCode,公司名稱:companyName," +                    "客戶電話:customerTel,房產編碼:houseCode,表型編碼:meterType,未用氣天數時間:unusedGasTime";            //HSSFWorkbook ;j+1 sheet當前頁; export_times sheet總頁數            /**             * HSSFWorkbook             * outputStream流             * 根據反射獲取實體類,而且賦值             * list 查詢到的實體集合             * classPath list 中實體的路徑,反射用到             * j+1 要寫入sheet的頁數             * 從新查詢數據的次數             */            ExcelUtils.exportExcel(wb,byteArrayOutputStream, keyValue, list, "cn.enn.chaoscloud.domain.archives.meter.vo.UnusedGasVO", j+1,export_times);        }        bytes = byteArrayOutputStream.toByteArray();    }catch (Exception e){        log.error(e.getMessage(), e);    }    return bytes;}
相關文章
相關標籤/搜索