分类 hutool 下的文章

开发环境:

   RuoYi-Vue
   jdk1.8
   SpringBoot 2.0
   Hutool
   Vue+Element UI

文件上传导入

1.文件上传:(element-upload)
1.1 界面展示
excel导入.png

前端代码【完整代码

<el-dialog :title="upload.title" :visible.sync="upload.open" :close-on-click-modal="false" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处,或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的代表品数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:#ff0000" slot="tip">提示:仅允许导入“xls”或“xlsx”格式文件!</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

1.2

2.Excel文件解析(Hutool中的poi封装类ExcelReader)
@Log(title = "", businessType = BusinessType.EXPORT)
@PostMapping("/imports")
public AjaxResult imports(MultipartFile file, boolean updateSupport) throws Exception
{
//Workbook wb= WorkbookFactory.create(file.getInputStream());

InputStream inputStream = null;
try{

 inputStream = file.getInputStream();

}catch (Exception e){

return ResponseData.fail(ResponseCodeEnum.ERROR_PARAM_INVALID);

}

ExcelReader excelReader = ExcelUtil.getReader(inputStream, "导入材料清单");

}

   

3.数据入库
       

相关文档:

   1.文件是如何上传的。
   2.文件上传原理。

需求:单个Excel文件读取

 public class  FileTest{
    
        public static void main(String[] args) throws SQLException {
    
        ExcelReader reader = ExcelUtil.getReader("/file.xlsx");
        List<List<Object>> readAll = reader.read();

        System.out.println(readAll.toString());
    
        }

}

需求: 本地有部分文件需要导入数据库

多文件文件存储位置: D盘

直接上代码:

public class  FileTest{

    public static void main(String[] args) throws SQLException {

        File f = new File("D://temp/result/week");
        for(File temp : f.listFiles()) {
            if(temp.isFile()) {
                System.out.println(temp.getName());
                ExcelReader  reader2= ExcelUtil.getReader(temp, 0);
                List<Map<String,Object>> readAll2 = reader2.readAll();
                for(Map<String,Object> map:readAll2){

                   Db.use().insert(
                            Entity.create("table")
                                    .set("date_week", map.get("date"))
                                   
                    );
                }
            }
        }


    }

    public static void readCsv(String[] args) throws SQLException, ParseException {
        CsvReader reader = CsvUtil.getReader();
        //从文件中读取CSV数据
        CsvData data = reader.read(FileUtil.file("D://temp/2022.csv"));
        List<CsvRow> rows = data.getRows();
        int numbers=rows.size();
        for (int i=1;i<numbers;i++) {
            CsvRow csvRow=rows.get(i);

            Db.use().insert(
                    Entity.create("table")
                            .set("year",csvRow.getRawList().get(0))
                            .set("month", csvRow.getRawList().get(0))
                           
            );
        }

    }


}

0:原样式

未修改之前.png

冻结.png

1:前期数据准备(List<Bean> list);

2:导出代码(基于Ruoyi-vue SpringBoot后端版本);

  @GetMapping("/priceweek/importTemplate")
@Log(title = "导出周平均价格", businessType = BusinessType.EXPORT)
public AjaxResult importTemplate(DrWeekPrice drWeekPrice) throws IOException {
    SysDept sysDept=sysDeptService.selectDeptById(Long.parseLong(drWeekPrice.getMarketId()));
    List<DrWeekPrice> list = drWeekPriceService.selectDrWeekAvgPrice(drWeekPrice);
    //定义hutool格式
    ExcelWriter writer = ExcelUtil.getWriter();
    writer.autoSizeColumnAll(); //自动列宽 感觉不太好用
    writer.setColumnWidth(-1,20);
    writer.setRowHeight(-1,50);
    writer.setOnlyAlias(true); //将导出的excel表中的ID去掉。
    //冻结前两行
    writer.setFreezePane(2);
    OutputStream out =null;
    writer.addHeaderAlias("shopNumber","商户编号");
    writer.addHeaderAlias("shopName","商户名称");
    writer.addHeaderAlias("shopPeople","商户负责人");
    writer.addHeaderAlias("className","类别名称");
    writer.addHeaderAlias("product","规格型号");
    writer.addHeaderAlias("unit","单位");
    writer.addHeaderAlias("thisWeekPrice","本周总销售额");
    writer.addHeaderAlias("thisDayTrading","本周总销量");
    writer.addHeaderAlias("thisWeekAvgPrice","本周均价");
    writer.addHeaderAlias("lastWeekAvgPrice","上周均价");
    writer.addHeaderAlias("ringvalue","价格浮动");

    String fileweek= DateUtil.format(drWeekPrice.getSurveyDateWeek(), "yyyy-MM-dd");

    writer.merge(11, fileweek+"-"+sysDept.getDeptName()+"-"+"代表品周价格信息");

    writer.write(list,true);

    writer.renameSheet("all");
    String filename="代表品周价格.xls";
    out= new FileOutputStream(getAbsoluteFile(filename));
    writer.flush(out);

    return AjaxResult.success(filename);

}

3

Hutool的Http文件下载方法

因为Hutool-http机制问题,请求页面返回结果是一次性解析为byte[]的,如果请求URL返回结果太大(比如文件下载),那内存会爆掉,因此针对文件下载HttpUtil单独做了封装。文件下载在面对大文件时采用流的方式读写,内存中只是保留一定量的缓存,然后分块写入硬盘,因此大文件情况下不会对内存有压力。

文件下载 since 5.7.12

String fileUrl = "http://mirrors.sohu.com/centos/8.4.2105/isos/x86_64/CentOS-8.4.2105-x86_64-dvd1.iso";
//将文件下载后保存在E盘,返回结果为下载文件大小
long size = HttpUtil.downloadFile(fileUrl, FileUtil.file("e:/"));
System.out.println("Download size: " + size);

下载流文件 since 5.7.12

HttpUtil.download()