欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > Easyexcel操作文件

Easyexcel操作文件

2025/3/17 17:17:57 来源:https://blog.csdn.net/weixin_64770547/article/details/146238807  浏览:    关键词:Easyexcel操作文件

常见问题汇总

1.往文件里写数据时,如果没有对应的实体类时,需要创建一个List<String,Map<Integer,String>>来保存一行的数据

private Map<Integer,Object> convertToMap(ResultSet rs){LinkedHashMap<Integer, Object> row = new LinkedHashMap<Integer, Object>;for (int i = 0; i < columns.size(); i++) {row.put(i,columns.get(i));}return row;
}

注意:如果与表头无法对应,数据插入不进去(则row中的key值从0开始)

2.文件无法打开

当时排查好久,发现流没有正常关闭,最后不要忘记finish();

3.poi于EasyExcel结合使用时注意事项

@Testvoid test38() throws IOException {// 模板文件路径(已用 POI 设置好样式)String templatePath = "D:\\idea代码\\demo1\\src\\main\\resources\\output1.xlsx";// 输出文件路径String outputPath = "D:\\idea代码\\demo1\\src\\main\\resources\\output2.xlsx";// 准备数据List<Map<Integer, Object>> data = new ArrayList<>();Map<Integer, Object> rowData = new HashMap<>();rowData.put(0, "张三");rowData.put(1, 25);rowData.put(2, "开发");rowData.put(3, "技术部");data.add(rowData);// 配置 EasyExcelExcelWriter excelWriter = EasyExcel.write(outputPath).withTemplate(templatePath) // 指定模板文件.build();// 指定从第2行开始写入数据(假设第0行是标题,第1行是表头)WriteSheet writeSheet = EasyExcel.writerSheet().relativeHeadRowIndex(1) // 数据从第2行开始写入.build();// 写入数据excelWriter.write(data, writeSheet);excelWriter.finish();System.out.println("数据写入完成,样式已保留!");}

4.文件压缩注意事项

 private static boolean packFileIntoZip(String filePath, String zipFilePath) {try (FileInputStream fis = new FileInputStream(filePath);FileOutputStream fos = new FileOutputStream(zipFilePath);ZipOutputStream zipOut = new ZipOutputStream(fos)) {// 获取文件名(去掉路径)String fileName = new File(filePath).getName();System.out.println("正在压缩文件: " + fileName);// 创建 ZipEntryZipEntry zipEntry = new ZipEntry(fileName);zipOut.putNextEntry(zipEntry);// 将文件内容读取为字节数组byte[] fileBytes = readAllBytes(fis);// 检查文件大小System.out.println("文件大小: " + fileBytes.length + " 字节");// 将字节数组写入 ZIP 文件zipOut.write(fileBytes);// 关闭当前条目zipOut.closeEntry();return true;} catch (FileNotFoundException e) {System.err.println("找不到文件: " + e.getMessage());} catch (IOException e) {e.printStackTrace();}return false;}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词