Java使用POI导出Excel工具类(反射)

pom.xml:

    <dependency>
      <groupId>org.apache.poigroupId>
      <artifactId>poiartifactId>
      <version>3.6version>
    dependency>

工具类:


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

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Excel导出工具类
 * @author 单继重
 * @since 2017/11/23 16:44
 */
public class ExcelUtil {

    private static Map exportFields = new HashMap();

    //初始化属性Map
    static {
        exportFields.put("name","活动名称");
        exportFields.put("content","活动内容");
        exportFields.put("population","活动人数");
        exportFields.put("provideMeal","提供餐饮");
        exportFields.put("provideHotel","提供住宿");
        exportFields.put("organization","主办单位");
        exportFields.put("tel","电话");
        exportFields.put("qq","负责人qq");
        exportFields.put("time","活动时间");
        exportFields.put("budget","活动经费");
        exportFields.put("certificate","活动证书");
        exportFields.put("status","活动状态");
    }

    /**
     * 获取Excel实体
     * @param sheetName sheet名字
     * @param list 对象集合
     * @return Excel实体
     * @throws IllegalAccessException 安全权限异常
     */
    public static HSSFWorkbook getHSSFWorkbook(String sheetName, List list) throws IllegalAccessException {

        //获取对象所有属性
        Field[] fields = list.get(0).getClass().getDeclaredFields();

        //表头数组
        String[] title = new String[fields.length];

        //设置表头
        for (int i = 0 ; i < fields.length ; i ++) {
            //获取属性
            Field field = fields[i];
            //设置该属性可访问
            field.setAccessible(true);
            //在属性Map中找到该属性对应表头
            title[i] = exportFields.get(field.getName());
        }

        // 第一步,创建一个workbook,对应一个Excel文件
        HSSFWorkbook workbook = new HSSFWorkbook();

        // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = workbook.createSheet(sheetName);

        // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow(0);

        // 第四步,创建单元格,并设置值表头 设置表头居中
        HSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        HSSFCell cell = null;

        //创建标题
        for(int i=0;i < title.length;i++){
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }

        //创建内容
        for(int i = 0 ; i < list.size() ; i ++) {
            row = sheet.createRow(i + 1);
            for(int j = 0 ; j < fields.length ; j ++) {
                Field field = fields[j];
                field.setAccessible(true);
                String value = String.valueOf(field.get(list.get(0)));
                row.createCell(j).setCellValue(value);
            }
        }
        return workbook;
    }
}

测试类:


import com.taiji.jilin.common.entity.Activity;
import com.taiji.jilin.common.util.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.junit.Test;

import java.io.*;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 单继重
 * @since 2017/11/23 13:58
*/

public class ExcelTest {

    @Test
    public void test () throws Exception {
        String fileName = "test.xls";
        String sheetName = "sheet1";

        List activities = new ArrayList();
        for (int i = 0 ; i < 10 ; i ++ ) {
            Activity activity = new Activity();
            activity.setName("名称");
            activity.setContent("内容");
            activity.setCertificate("证书");
            activity.setIsFinish(1);
            activity.setBudget("预算");
            activity.setId(123);
            activity.setOrganization("组织");
            activity.setPopulation(123456);
            activity.setProvideHotel("是");
            activity.setProvideMeal("餐饮");
            activity.setQq("QQ");
            activity.setTel("电话");
            activity.setTime("时间");
            activity.setStatus("啊啊啊");
            activities.add(activity);
        }
        HSSFWorkbook hssfWorkbook = ExcelUtil.getHSSFWorkbook(sheetName,activities);
        File file = new File("F:\\Shanjz" + fileName);
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            hssfWorkbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(工具类)