【导入Excel】java导入Excel 文件转成对象

一、spring boot 配置文件

spring:
  mvc:
    hiddenmethod:
      filter:
        enabled: true

二、接口

    @RequestMapping("/importByExcel.do")
    @ResponseBody
    public BaseResult importByExcel(@RequestParam(value = "fileName") MultipartFile attach ) throws Exception {

        BaseResult rslt = new BaseResult();
        houseLogicService.importByExcel(attach);
        rslt.setErrorCode(BaseResult.SUCCESS);

        return rslt;
    }
 @Override
    public void importByExcel(MultipartFile attach) {
        /*
         * 生成字段映射map
         */
        LinkedHashMap<String, String> deviceHeaderMap = null;
        try {
            deviceHeaderMap = ExcelUtils.generateHeaderMap(HouseDto.class, false);

        } catch (Exception e) {
            LogUtils.error(e);
            throw new ErrorInfoException(PlatformResultCst.SYSTEM_ERROR, new String[]{deviceHeaderMap.getClass().getName()});
        }

        /*
         * 根据表格获取对象信息
         */
        List<HouseDto> houseDtoList = new ArrayList<>();
        try {
            houseDtoList = ExcelUtils.importExcel(HouseDto.class, attach.getInputStream(), deviceHeaderMap);
        } catch (Exception e) {
            LogUtils.error(e);
            throw new ErrorInfoException(PlatformResultCst.SYSTEM_ERROR, new String[]{attach.getName()});
        }

        /*
         * @Date: 2021/7/21 14:18
         * Step 3: 保存数据,只要有一个错,就导入失败
         */
        for (HouseDto houseDto : houseDtoList) {

            // 其他字段业务填充

            // 保存到数据库
            addAndUpdateHouse(houseDto);
        }
    }

导入的工具类



import org.apache.commons.beanutils.BeanUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
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.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTColor;

import java.awt.*;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;

public class ExcelUtils {

   

    /**
     * 生成一个标题style
     *
     * @return style
     */
    public static XSSFCellStyle getHeaderStyle(Workbook workbook) {
        return getHeaderStyle(workbook, (CTColor) Color.BLUE, IndexedColors.WHITE.getIndex());
    }

    /**
     * 生成一个指定颜色的标题style
     *
     * @param workbook
     * @param foregroundColor
     * @param fontColor
     * @return
     */
    public static XSSFCellStyle getHeaderStyle(Workbook workbook, CTColor foregroundColor, short fontColor) {

        /*
         *  生成一个样式(用于标题)
         */
        XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle();

        /*
         * 设置这些样式
         */
        style.setFillForegroundColor(new XSSFColor(foregroundColor));
        style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        style.setBorderRight(XSSFCellStyle.BORDER_THIN);
        style.setBorderTop(XSSFCellStyle.BORDER_THIN);
        style.setAlignment(XSSFCellStyle.ALIGN_CENTER);

        /*
         *  生成一个字体
         */
        XSSFFont font = (XSSFFont) workbook.createFont();
        font.setColor(fontColor);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);

        /*
         *  把字体应用到当前的样式
         */
        style.setFont(font);

        return style;
    }

    /**
     * 生成一个用于内容的style
     *
     * @param workbook
     * @return
     */
    public static XSSFCellStyle getContentStyle(Workbook workbook) {
        /*
         *  生成并设置另一个样式(用于内容)
         */
        XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle();
        // style.setFillForegroundColor(new XSSFColor(Color.YELLOW));
        // style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
        style.setBorderRight(XSSFCellStyle.BORDER_THIN);
        style.setBorderTop(XSSFCellStyle.BORDER_THIN);
        style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);

        /*
         *  生成另一个字体
         */
        XSSFFont font = (XSSFFont) workbook.createFont();
        font.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);

        /*
         *  把字体应用到当前的样式
         */
        style.setFont(font);

        return style;
    }

    /**
     * excel导入数据
     * 导入的表格第一行必须为标题行
     *
     * @param clazz             导入的类型
     * @param xls               excel源
     * @param propertyHeaderMap key为标题头  value为类字段
     * @return
     * @throws Exception
     */
    @SuppressWarnings("rawtypes")
    public static <T> List importExcel(Class<T> clazz, InputStream xls, LinkedHashMap<String, String> propertyHeaderMap) throws Exception {
        try {
            /*
             *  取得Excel
             */
            HSSFWorkbook wb = new HSSFWorkbook(xls);
            HSSFSheet sheet = wb.getSheetAt(0);
            Field[] fields = clazz.getDeclaredFields();

            /*
             * 获取标题行
             */
            HSSFRow rowTitle = sheet.getRow(0);

            /*
             *  行循环
             */
            List<T> modelList = new ArrayList<T>(sheet.getPhysicalNumberOfRows() * 2);
            for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
                /*
                 * 数据模型
                 */
                T model = clazz.newInstance();
                int nullCount = 0;

                // for (Field field : fields) {

                while (true) {

                    /*
                     * 获取字段
                     */
                    HSSFCell cell = sheet.getRow(i).getCell(nullCount);
                    if (cell == null) {
                        break;
                    }
                    String strField = propertyHeaderMap.get(rowTitle.getCell(nullCount).getStringCellValue());
                    Field field = clazz.getDeclaredField(strField);

                    /*
                     * 赋值给model
                     */
                    try {
                        if (cell == null || cell.toString().length() == 0) {
                            nullCount++;
                        } else if (field.getType().equals(Date.class)) {
                            if (Cell.CELL_TYPE_STRING == cell.getCellType()) {
                                BeanUtils.setProperty(model, field.getName(), new Date(parseDate(parseString(cell))));
                            } else {
                                BeanUtils.setProperty(model, field.getName(), new Date(cell.getDateCellValue().getTime()));

                            }
                        } else if (field.getType().equals(Timestamp.class)) {
                            if (Cell.CELL_TYPE_STRING == cell.getCellType()) {
                                BeanUtils.setProperty(model, field.getName(), new Timestamp(parseDate(parseString(cell))));
                            } else {
                                BeanUtils.setProperty(model, field.getName(),
                                        new Timestamp(cell.getDateCellValue().getTime()));
                            }

                        } else if (field.getType().equals(java.sql.Date.class)) {
                            if (Cell.CELL_TYPE_STRING == cell.getCellType()) {
                                BeanUtils.setProperty(model, field.getName(),
                                        new java.sql.Date(parseDate(parseString(cell))));
                            } else {
                                BeanUtils.setProperty(model, field.getName(),
                                        new java.sql.Date(cell.getDateCellValue().getTime()));
                            }
                        } else if (field.getType().equals(Integer.class)) {
                            if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {
                                BeanUtils.setProperty(model, field.getName(), (int) cell.getNumericCellValue());
                            } else if (Cell.CELL_TYPE_STRING == cell.getCellType()) {
                                BeanUtils.setProperty(model, field.getName(), Integer.parseInt(parseString(cell)));
                            }
                        } else if (field.getType().equals(BigDecimal.class)) {
                            if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {
                                BeanUtils.setProperty(model, field.getName(), new BigDecimal(cell.getNumericCellValue()));
                            } else if (Cell.CELL_TYPE_STRING == cell.getCellType()) {
                                BeanUtils.setProperty(model, field.getName(), new BigDecimal(parseString(cell)));
                            }
                        } else {
                            if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {
                                BeanUtils.setProperty(model, field.getName(), new BigDecimal(cell.getNumericCellValue()));
                            } else if (Cell.CELL_TYPE_STRING == cell.getCellType()) {
                                BeanUtils.setProperty(model, field.getName(), parseString(cell));
                            }
                        }
                    } catch (Exception e) {
                        LogUtils.error(e);

                    }
                    // }
                    if (nullCount >= rowTitle.getLastCellNum()) {
                        break;
                    }
                    nullCount++;
                }
                modelList.add(model);

            }
            return modelList;

        } finally {
            xls.close();
        }
    }

    /**
     * 解析字符串为string
     *
     * @param cell
     * @return
     */
    private static String parseString(HSSFCell cell) {
        return String.valueOf(cell).trim();
    }

    /**
     * 日期字符串转换为日期
     *
     * @param dateString
     * @return
     * @throws ParseException
     */
    private static long parseDate(String dateString) throws ParseException {
        if (dateString.indexOf("/") == 4) {
            return new SimpleDateFormat("yyyy/MM/dd").parse(dateString).getTime();
        } else if (dateString.indexOf("-") == 4) {
            return new SimpleDateFormat("yyyy-MM-dd").parse(dateString).getTime();
        } else if (dateString.indexOf("年") == 4) {
            return new SimpleDateFormat("yyyy年MM月dd").parse(dateString).getTime();
        } else if (dateString.length() == 8) {
            return new SimpleDateFormat("yyyyMMdd").parse(dateString).getTime();
        } else {
            return new Date().getTime();
        }
    }

    /**
     * 生成字段表头的map映射
     *
     * @param clazz
     * @param flag  true表示字段为key(生成表格用) false表示表头名称为key(表格导入使用)
     * @return
     * @throws Exception
     */
    public static <T> LinkedHashMap<String, String> generateHeaderMap(Class<T> clazz, Boolean flag) throws Exception {
        LinkedHashMap<String, String> propertyHeaderMap = new LinkedHashMap<String, String>();

        /*
         * 取出类字段
         */
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            /*
             * 取出注解
             */
            FieldMata mataAnnotation = field.getAnnotation(FieldMata.class);
            if (mataAnnotation == null) {
                continue;
            }
            if (mataAnnotation.name() != null && !"".equals(mataAnnotation.name())) {
                if (mataAnnotation.isList() == false) {
                    if (flag == true) {
                        propertyHeaderMap.put(field.getName(), mataAnnotation.name());
                    } else {
                        propertyHeaderMap.put(mataAnnotation.name(), field.getName());
                    }
                }
            }
        }
        return propertyHeaderMap;
    }


}

补充注解 FieldMata 

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface FieldMata {

    /**
     * 字段名称
     *
     * @return
     */
    String name() default "";

    /**
     * 是否是列表
     */
    boolean isList() default false;

    /**
     * 字段是否是dto
     */
    boolean isDto() default false;

}

三、测试

postman

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
你可以使用 Apache POI 库来将 Excel 文件导入对象。Apache POI 提供了一组用于读取和写入 Excel 文件Java API。下面是一个简单示例代码,演示如何使用 POI 将 Excel 文件的数据导入对象```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import.util.Iterator; import java.util.List; public class ExcelImporter { public static List<MyObject> importExcel(String filePath) throws IOException { List<MyObject> objects = new ArrayList<>(); FileInputStream fileInputStream = new FileInputStream(filePath); Workbook workbook = new XSSFWorkbook(fileInputStream); Sheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); MyObject object = new MyObject(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); int columnIndex = cell.getColumnIndex(); switch (columnIndex) { case 0: object.setProperty1(cell.getStringCellValue()); break; case 1: object.setProperty2(cell.getNumericCellValue()); break; // 添加更多属性的处理 default: // 忽略其他列 break; } } objects.add(object); } workbook.close(); fileInputStream.close(); return objects; } } ``` 在上面的示例中,MyObject 是你自己定义的类,根据实际情况进行调整。你可以根据每列的索引(从0开始)来设置对象的属性值。请确保你的 Excel 文件与代码中的逻辑相匹配,包括表头和数据的顺序。 请注意,这只是一个简单的示例,并且假设你使用的是 .xlsx 格式的 Excel 文件。如果你使用的是 .xls 格式,需要将代码中的 XSSFWorkbook 替换为 HSSFWorkbook。 希望以上信息对你有所帮助!如有任何问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cy谭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值