excelutil java_ExcelUtil.java

package cn.youthwechat.utils.excel;

import org.apache.poi.hssf.usermodel.*;

import org.apache.poi.ss.usermodel.HorizontalAlignment;

import org.apache.poi.ss.usermodel.VerticalAlignment;

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.ss.util.CellRangeAddress;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;

import java.util.*;

public class ExcelUtil {

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

//记录表头占几行

private int headDeep;

/**

* 导出excel

* @param dataList 即将导出的数据列表

* @param propertyToDescription 数据列表实体bean中属性与excel表头文字的对应关系

* @param

* @return

*/

public static synchronized Workbook export(List dataList, Map propertyToDescription) throws Exception {

try {

HSSFWorkbook workbook = new HSSFWorkbook();

HSSFSheet hssfSheet = workbook.createSheet("sheet1");

HSSFCellStyle hssfCellStyle = workbook.createCellStyle();

hssfCellStyle.setAlignment(HorizontalAlignment.CENTER);

hssfCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

ExcelTreeBodyStructure structure = parseHeaderTree(propertyToDescription);

printExcelHead(structure.getTreeNodeList(),hssfSheet,hssfCellStyle);

printExcelBody(dataList, structure.getHeadPropertyTreeLeafList(),hssfSheet,null,getTreeHight(propertyToDescription),0);

return workbook;

}catch(Exception e){

e.printStackTrace();

logger.error(e.toString());

throw new Exception("导出信息失败!");

}

}

/**

* 根据表头单元格描述,构造表头

* @param nodeList 表头单元格描述节点

* @param sheet excel表单

* @param style 样式对象

*/

private static synchronized void printExcelHead(List nodeList,HSSFSheet sheet, HSSFCellStyle style){

Map rowNum2Obj = new HashMap<>();

HSSFRow row = null;

HSSFCell cell = null;

for (ExcelHeadNode node:nodeL

你可能感兴趣的:(excelutil,java)