XSSF解析

本文介绍了一个使用Java进行Excel文件解析并存储数据至数据库的方法。通过读取指定路径下的Excel文件,逐行读取数据,并利用Spring框架的依赖注入将数据持久化。涉及的技术包括Apache POI库用于处理Excel文件,以及Spring框架提供的服务层接口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class TestExcel {

    static Log log = LogFactory.getLog(TestExcel.class);

    private final static int httpPort = 8087;

    

    @Autowired

    PhoneMatchCodeService phoneMatchCodeService;

 

    // 获取Excel文档的路径

    public static String filePath = "E://phoneMatchCode//phoneMatchCode.xlsx";

 

    private String saveData() {

        try {

            // 创建对Excel工作簿文件的引用

            Workbook wookbook = null;

//            OPCPackage pkg = OPCPackage.open(path);

            wookbook = new XSSFWorkbook(new FileInputStream(filePath));

            // HSSFWorkbook wookbook = new HSSFWorkbook(new

            // FileInputStream(filePath));

            // 在Excel文档中,第一张工作表的缺省索引是0

            // 其语句为: HSSFSheet sheet = workbook.getSheetAt(0);

            Sheet sheet = wookbook.getSheet("Sheet1");

            // HSSFSheet sheet = wookbook.getSheet("Sheet1");

            // 获取到Excel文件中的所有行数

            int rows = sheet.getPhysicalNumberOfRows();

            // 遍历行

 

            PhoneMatchCode phoneMatchCode = new PhoneMatchCode();

            for (int i = 1; i < rows; i++) {

                // 读取左上端单元格

                Row row = sheet.getRow(i);

                // 行不为空

                if (row != null) {

                    // 获取到Excel文件中的所有的列

                    int cells = row.getPhysicalNumberOfCells();

                    String value = ""; // 遍历列

 

                    row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);

                    phoneMatchCode.setCode(row.getCell(0).getStringCellValue());

 

                    row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);

                    phoneMatchCode.setMatchCode(row.getCell(1).getStringCellValue());

 

                    row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);

                    phoneMatchCode.setProvince(row.getCell(2).getStringCellValue());

 

                    row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);

                    phoneMatchCode.setCity(row.getCell(3).getStringCellValue());

 

                    System.out.println(phoneMatchCode.getCity());

                    phoneMatchCodeService.add(phoneMatchCode);

                }

            }

            return "ok";

        } catch (Exception e) {

            log.error("excell 解析失败", e);

            return "error";

        }

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值