poi操作excel导入导出

我的梦境 提交于 2019-12-11 02:23:32

poi操作excel导入导出


java中使用poi对excel进行导入导出操作

使用注解建立实体对象与excel之间的映射关系,反射为对象属性设置值。

1、maven中引入poi包

 <!-- poi-ooxml自动引入操作xlsx文件所用到的其他包 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.4</version>
        </dependency>

2、定义注解:用来与excel建立关系,将对象属性与excel的列建立关系。

@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelAnnotation {
    /**
     * 列索引
     */
    public int columnIndex() default 0;
    /**
     * 列名
     */
    public String columnName() default "";
}

3、实体对象

public class ExcelModel {

    //描述改属性在excel中第0列,列名为  序号
    @ExcelAnnotation (columnIndex=0,columnName="序号")
    private int id;
    
    //描述改属性在excel中第1列,列宁为 名字
    @ExcelAnnotation (columnIndex=1,columnName="名字")
    private String name;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

4、excel导出

	/**
     * excel文件导出
     */
    public static void exportExcel(List<?> data, String path) {
        File file = new File(path);
        // 创建workbook
        HSSFWorkbook wb = new HSSFWorkbook();
        
        // 创建sheet
        Sheet sheet = wb.createSheet("sheel");

        // 创建表头行
        Row row = sheet.createRow(0);

        // 创建单元格样式
        HSSFCellStyle style = wb.createCellStyle();
        // 居中显示
        style.setAlignment(HorizontalAlignment.CENTER);

        // 获取实体所有属性
        Field[] fields = data.get(0).getClass().getDeclaredFields();
        // 列索引
        int index = 0;
        // 列名称
        String name = "";
        ExcelAnnotation excelAnnotation;

        // 创建表头
        for (Field f : fields) {
            // 是否是注解
            if (f.isAnnotationPresent(ExcelAnnotation .class)) {
                // 获取注解
                excelAnnotation= f.getAnnotation(ExcelAnnotation .class);
                // 获取列索引
                index = excelAnnotation.columnIndex();
                // 列名称
                name = excelAnnotation.columnName();
                // 创建单元格
                creCell(row, index, name, style);
            }
        }

        // 行索引  因为表头已经设置,索引行索引从1开始
        int rowIndex = 1;
        for (Object obj : data) {
            // 创建新行,索引加1,为创建下一行做准备
            row = sheet.createRow(rowIndex++);
            for (Field f : fields) {
                // 设置属性可访问
                f.setAccessible(true);
                // 判断是否是注解
                if (f.isAnnotationPresent(ExcelAnnotation .class)) {
                    // 获取注解
                    excelAnnotation = f.getAnnotation(ExcelAnnotation .class);
                    // 获取列索引
                    index = excelAnnotation .columnIndex();
                    try {
                        // 创建单元格     f.get(obj)从obj对象中获取值设置到单元格中
                        creCell(row, index, String.valueOf(f.get(obj)), style);
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        try (FileOutputStream outputStream = = new FileOutputStream(file) ){
            wb.write(outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
    //关闭wb

excel导入

/**
 * 读取excel文件,并把读取到的数据封装到clazz中
 * 返回clazz集合
 */
public static <T extends Object> List<T> readExcelFile(String path, Class<T> clazz) {
    // 存储excel数据
    List<T> list = new ArrayList<>();
    FileInputStream is = null;
    try {
        is = new FileInputStream(new File(path));
    } catch (FileNotFoundException e1) {
        throw new RuntimeException("文件路径异常");
    }
    Workbook wookbook = null;
    // 根据excel文件版本获取工作簿
    if (path.endsWith(".xls")) {
        wookbook = xls(is);
    } else if (path.endsWith(".xlsx")) {
        wookbook = xlsx(is);
    } else {
        throw new RuntimeException("文件出错,非excel文件");
    }

    // 得到一个工作表
    Sheet sheet = wookbook.getSheetAt(0);

    // 获取行总数
    int rows = sheet.getLastRowNum() + 1;

    Row row;

    // 获取类所有属性
    Field[] fields = clazz.getDeclaredFields();

    T obj = null;
    int coumnIndex = 0;
    Cell cell = null;
    ExcelAnnotation excelAnnotation = null;
    for (int i = 1; i < rows; i++) {
        // 获取excel行
        row = sheet.getRow(i);
        try {
            // 创建实体
            obj = clazz.newInstance();
            for (Field f : fields) {
                // 设置属性可访问
                f.setAccessible(true);
                // 判断是否是注解
                if (f.isAnnotationPresent(ExcelAnnotation.class)) {
                    // 获取注解
                    excelAnnotation = f.getAnnotation(ExcelAnnotation.class);
                    // 获取列索引
                    coumnIndex = excelAnnotation .columnIndex();
                    // 获取单元格
                    cell = row.getCell(coumnIndex);
                    // 设置属性
                    setFieldValue(obj, f, wookbook, cell);
                }
            }
            // 添加到集合中
            list.add(obj);
        } catch (InstantiationException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        }
    }

    try {
        //释放资源
        wookbook.close();
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return list;
}

设置属性值

/**
 * 设置属性值 
 * @param obj 操作对象
 * @param f对象属性
 * @param cell  excel单元格
 */
private static void setFieldValue(Object obj, Field f, Workbook wookbook, Cell cell) {
    try {
        if (f.getType() == int.class || f.getType() == Integer.class) {
            f.setInt(obj, getInt(cell));
        } else if (f.getType() == Double.class || f.getType() == double.class) {
            f.setDouble(obj, getDouble(null, cell));
        } else {
            f.set(obj, getString(cell));
        }
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

excel版本处理

/**
 * 对excel 2003处理
 */
private static Workbook xls(InputStream is) {
    try {
        // 得到工作簿
        return new HSSFWorkbook(is);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
/**
 * 对excel 2007处理
 */
private static Workbook xlsx(InputStream is) {
    try {
        // 得到工作簿
        return new XSSFWorkbook(is);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

创建单元格

/**
 * 创建单元格
 * */
private static void creCell(Row row, int c, String cellValue, CellStyle style) {
    Cell cell = row.createCell(c);
    cell.setCellValue(cellValue);
    cell.setCellStyle(style);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!