java如何直接读取excel文件进行增删改查操作

55 篇文章 0 订阅
8 篇文章 0 订阅

首先先创建一个文件路径类,用来放置文件的位置

package com.ruoyi.web.core.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * fileConfig.properties文件配置信息
 */
@Configuration
@ConfigurationProperties(prefix = "config", ignoreUnknownFields = false)
@PropertySource("classpath:fileConfig.properties")
@Data
public class FileConfigProperties {
    /**
     * 文件存储位置配置
     */
    private String filePath;
}

获取到文件储位置后,就可以进行用文件操作类进行操作,这里可以用若依框架里面自带的,或者使用hutool工具,也可以

在这里我自己写了一个工具类, 可以参考一下,就是把读取的文件用Redis进行缓存,根据文件最后的修改时间和文件名作为Key值进行存储 和查询,这样的话就可以保证查询速率,只有在第一次加载的时候,比较慢,后面的话,如果不改动文件内容的话,之后用的都是redis里面缓存的值.     

这个工具类如下: 

package com.ruoyi.web.controller.tool;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.enumVo.FileNameVo;
import com.ruoyi.web.core.config.FileConfigProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Collection;
import java.util.List;

@Component
public class FileDataUtil {
    @Resource
    FileConfigProperties fileConfigProperties;
    @Resource
    RedisCache redis;

    /**
     * 读取Excel文件数据
     *
     * @param fileNameVo 文件类型
     * @return 文件数据
     * @throws FileNotFoundException 文件不存在
     */
    public List<?> getFileDataList(FileNameVo fileNameVo) throws FileNotFoundException {
        String fileName = fileNameVo.getFileName();
        File file = ResourceUtils.getFile(fileConfigProperties.getFilePath() + fileName);
        String fileLastTime = String.valueOf((file.lastModified()));
        String dataListKey = fileName + "Data";
        if (!redis.hasKey(fileName) || !redis.getCacheObject(fileName).equals(fileLastTime)) {
            redis.setCacheObject(fileName, fileLastTime);
            FileInputStream fileInputStream = new FileInputStream(file);
            ExcelUtil<?> util = new ExcelUtil<>(fileNameVo.getEntityClass());
            List<?> dataList = util.importExcel(fileInputStream);
            if (!dataList.isEmpty()) redis.setCacheObject(dataListKey, dataList);
            return dataList;
        } else {
            return redis.getCacheObject(dataListKey);
        }
    }

    /**
     * 加载数据
     *
     * @param dataList 数据集
     * @param file     文件
     */
    public <T> void loadData(List<T> dataList, FileNameVo file) throws Exception {
        if (dataList.isEmpty()) {
            try {
                dataList.addAll((Collection<? extends T>) getFileDataList(file));
            } catch (Exception e) {
                throw new FileNotFoundException("加载文件数据时发生错误: " + e.getMessage());
            }
            if (dataList.isEmpty()) {
                throw new FileNotFoundException("文件数据为空");
            }
        }
    }
}

这个工具类可以适用不同的类型,也就是List<?>这种  使用的时候直接传入你需要读取的文件,和相对应接收的 List<自定义实体类> 数据集

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
下面是Appliances类的代码实现: ```java public class Appliances { private String brand; private double price; public String getBrand() { return brand; } public void setBrand(String brand) throws Exception { if (brand.length() < 4) { throw new Exception("品牌至少4位!"); } this.brand = brand; } public double getPrice() { return price; } public void setPrice(double price) throws Exception { if (price < 0) { throw new Exception("价格必须大于等于0!"); } this.price = price; } } ``` 下面是Test类的代码实现: ```java import java.io.File; import java.util.ArrayList; import java.util.List; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; import jxl.read.biff.BiffException; public class Test { private static final String FILE_NAME = "goodsInfo.xls"; public static void main(String[] args) { List<Appliances> list = new ArrayList<>(); Appliances haier = new Appliances(); try { haier.setBrand("Haier"); haier.setPrice(2399.00); } catch (Exception e) { e.printStackTrace(); } list.add(haier); Appliances midea = new Appliances(); try { midea.setBrand("Midea"); midea.setPrice(1999.00); } catch (Exception e) { e.printStackTrace(); } list.add(midea); Appliances gree = new Appliances(); try { gree.setBrand("Gree"); gree.setPrice(2899.00); } catch (Exception e) { e.printStackTrace(); } list.add(gree); createExcel(list); readExcel(); updateExcel(); deleteExcel(); } public static void createExcel(List<Appliances> list) { try { // 创建excel工作簿 WritableWorkbook wbook = Workbook.createWorkbook(new File(FILE_NAME)); // 创建新的一页 WritableSheet wsheet = wbook.createSheet("商品信息", 0); // 创建表头 Label label0 = new Label(0, 0, "品牌"); wsheet.addCell(label0); Label label1 = new Label(1, 0, "价格"); wsheet.addCell(label1); // 写入数据 for (int i = 0; i < list.size(); i++) { Label brand = new Label(0, i + 1, list.get(i).getBrand()); Label price = new Label(1, i + 1, String.valueOf(list.get(i).getPrice())); wsheet.addCell(brand); wsheet.addCell(price); } // 把创建的内容写入到输出流中,并关闭输出流 wbook.write(); wbook.close(); } catch (Exception e) { e.printStackTrace(); } } public static void readExcel() { try { // 读取excel文件 Workbook workbook = Workbook.getWorkbook(new File(FILE_NAME)); // 读取第一张表 WritableSheet sheet = workbook.getSheet(0); // 读取表格内容 for (int i = 1; i < sheet.getRows(); i++) { String brand = sheet.getCell(0, i).getContents(); String price = sheet.getCell(1, i).getContents(); System.out.println("品牌:" + brand + ",价格:" + price); } workbook.close(); } catch (BiffException | IOException e) { e.printStackTrace(); } } public static void updateExcel() { try { // 读取excel文件 Workbook workbook = Workbook.getWorkbook(new File(FILE_NAME)); // 打开一个可写的excel文件副本 WritableWorkbook wbook = Workbook.createWorkbook(new File(FILE_NAME), workbook); // 读取第一张表 WritableSheet sheet = wbook.getSheet(0); // 修改表格内容 Label label = new Label(1, 2, "2699.00"); sheet.addCell(label); // 把创建的内容写入到输出流中,并关闭输出流 wbook.write(); wbook.close(); workbook.close(); System.out.println("修改成功!"); } catch (BiffException | IOException | WriteException e) { e.printStackTrace(); } } public static void deleteExcel() { try { // 读取excel文件 Workbook workbook = Workbook.getWorkbook(new File(FILE_NAME)); // 打开一个可写的excel文件副本 WritableWorkbook wbook = Workbook.createWorkbook(new File(FILE_NAME), workbook); // 读取第一张表 WritableSheet sheet = wbook.getSheet(0); // 删除表格内容 sheet.removeRow(2); // 把创建的内容写入到输出流中,并关闭输出流 wbook.write(); wbook.close(); workbook.close(); System.out.println("删除成功!"); } catch (BiffException | IOException | WriteException e) { e.printStackTrace(); } } } ``` 运行Test类后,可以在控制台上看到输出结果: ``` 品牌:Haier,价格:2399.0 品牌:Midea,价格:1999.0 品牌:Gree,价格:2899.0 修改成功! 品牌:Haier,价格:2399.0 品牌:Midea,价格:1999.0 ``` 同时,也会在项目目录下生成一个名为“goodsInfo.xls”的文件,其中存储了商品信息。可以通过本程序实现excel文件增删改查

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小高求学之路

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

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

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

打赏作者

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

抵扣说明:

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

余额充值