ExcelUtil<MaterialsPropertyRefDto> util = new ExcelUtil<>(MaterialsPropertyRefDto.class); // param1:导出数据集合 param2:工作表名称 创建工作簿对象 HSSFWorkbook workbook = util.exportExcelExt(null, "material", fields); workbook.createName(); workbook.write(baos);
时间: 2024-04-16 14:25:54 浏览: 132
根据您提供的代码片段,我可以看出您在使用Excel框架进行导出操作。这段代码使用了一个名为`ExcelUtil`的工具类来导出Excel文件,并将数据写入到`HSSFWorkbook`对象中。
根据代码中的注释,`param1`表示导出的数据集合,`param2`表示工作表的名称,`fields`可能是用于指定导出字段的参数。
接下来,代码调用了`util.exportExcelExt()`方法来执行导出操作,返回一个`HSSFWorkbook`对象。然后,通过调用`createName()`方法创建了一个名称,并使用`workbook.write(baos)`将数据写入到一个输出流(例如`ByteArrayOutputStream`)中。
根据您的需求,您可能需要提供数据集合和工作表名称作为参数来导出实际的数据。如果您需要更具体的帮助,请提供更多代码或详细描述您遇到的问题,我将尽力协助您解决。
相关问题
Map<String, List<PortReportResultVo>> relayLinkAndPortMap = devPortReportByEs.getRelayLinkAndPortMap(); 遍历这个map,key为表头,value为数据,在一个sheet页中用easyExcel实现,导包也展示
好的,你可以参考以下代码实现:
```
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ExcelUtil {
/**
* 导出到Excel
*
* @param outputStream 输出流
* @param dataMap 数据集合,key为表头,value为数据
* @throws IOException
*/
public static void exportExcel(OutputStream outputStream, Map<String, List<PortReportResultVo>> dataMap) throws IOException {
List<PortReportResultVo> dataList = new ArrayList<>();
for (Map.Entry<String, List<PortReportResultVo>> entry : dataMap.entrySet()) {
// 添加表头
PortReportResultVo header = new PortReportResultVo();
header.setPortCode(entry.getKey());
dataList.add(header);
// 添加数据
List<PortReportResultVo> list = entry.getValue();
dataList.addAll(list);
}
// 导出Excel
EasyExcel.write(outputStream, PortReportResultVo.class)
.excelType(ExcelTypeEnum.XLSX)
.sheet("Sheet1")
.doWrite(dataList);
}
/**
* 导出到文件
*
* @param filePath 文件路径
* @param dataMap 数据集合,key为表头,value为数据
* @throws IOException
*/
public static void exportExcel(String filePath, Map<String, List<PortReportResultVo>> dataMap) throws IOException {
try (OutputStream outputStream = new FileOutputStream(filePath)) {
exportExcel(outputStream, dataMap);
}
}
/**
* 导出到文件
*
* @param filePath 文件路径
* @param dataMap 数据集合,key为表头,value为数据
* @throws IOException
*/
public static void exportExcel(String filePath, Map<String, List<PortReportResultVo>> dataMap, String sheetName) throws IOException {
try (OutputStream outputStream = new FileOutputStream(filePath)) {
exportExcel(outputStream, dataMap, sheetName);
}
}
/**
* 导出到Excel
*
* @param outputStream 输出流
* @param dataMap 数据集合,key为表头,value为数据
* @param sheetName sheet页名称
* @throws IOException
*/
public static void exportExcel(OutputStream outputStream, Map<String, List<PortReportResultVo>> dataMap, String sheetName) throws IOException {
List<PortReportResultVo> dataList = new ArrayList<>();
for (Map.Entry<String, List<PortReportResultVo>> entry : dataMap.entrySet()) {
// 添加表头
PortReportResultVo header = new PortReportResultVo();
header.setPortCode(entry.getKey());
dataList.add(header);
// 添加数据
List<PortReportResultVo> list = entry.getValue();
dataList.addAll(list);
}
// 导出Excel
Sheet sheet = new Sheet(1, 0, PortReportResultVo.class);
sheet.setSheetName(sheetName);
EasyExcel.write(outputStream, PortReportResultVo.class)
.excelType(ExcelTypeEnum.XLSX)
.sheet(sheet)
.doWrite(dataList);
}
}
/**
* Excel行数据类
*/
class PortReportResultVo extends BaseRowModel {
@ExcelProperty(value = "端口编码", index = 0)
private String portCode;
@ExcelProperty(value = "端口名称", index = 1)
private String portName;
@ExcelProperty(value = "设备编码", index = 2)
private String deviceCode;
@ExcelProperty(value = "设备名称", index = 3)
private String deviceName;
// 省略getter/setter方法
}
```
其中,PortReportResultVo类为Excel行数据类,用于存储一行数据。ExcelUtil类中的exportExcel方法可以将Map<String, List<PortReportResultVo>>数据导出为一个Excel文件。你可以根据需要修改ExcelUtil类中的代码,并添加相应的依赖包,比如:
```
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.4</version>
</dependency>
</dependencies>
```
ruoyi-vue使用excelutil生成excel并将excel存放到指定目录
### RuoYi-Vue 使用 ExcelUtil 生成 Excel 文件并存储到指定目录
在 RuoYi-Vue 项目中,`ExcelUtil` 是一个非常方便的工具类,用于快速导出 Excel 数据。以下是实现将 Excel 文件生成并保存到指定目录的具体方法。
---
#### 1. 后端逻辑实现
RuoYi-Vue 的后端基于 Spring Boot,因此可以使用 Java 提供的相关 IO 流技术来完成文件的生成与存储。
##### 导入依赖
确保项目中已经导入了 Apache POI 或 FastExcel 等支持 Excel 处理的依赖包。通常情况下,RuoYi 已经默认包含了这些依赖。
```xml
<!-- pom.xml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>
```
---
##### 编写服务层代码
在 `com.ruoyi.common.utils.excel` 包下找到 `ExcelUtil.java` 类,并编写相应的业务逻辑。
以下是一个完整的示例代码片段:
```java
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.excel.ExcelUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
public class LogisticsExportService {
/**
* 生成 Excel 文件并保存到指定目录
*
* @param logisticsList 物流信息列表
* @param exportPath 输出路径
*/
public static void generateAndSaveExcel(List<JSONObject> logisticsList, String exportPath) {
if (StringUtils.isEmpty(exportPath)) {
throw new IllegalArgumentException("输出路径不能为空");
}
// 定义表头名称数组
String[] headers = {"ID", "部门", "发货情况", "厂家单号", "随货数量", "发货人",
"收货单位", "收货人", "收货人手机", "收货地址", "件数", "创建时间", "修改时间",
"创建人", "修改人", "备注"};
// 构建数据对象
List<List<Object>> dataRows = logisticsList.stream().map(logistics -> {
return List.of(
logistics.getString("id"),
logistics.getString("department"),
logistics.getInteger("shippingStatus"), // 发货情况
logistics.getString("manufacturerOrderNo"),
logistics.getInteger("withGoodsCount"), // 随货数量
logistics.getString("shipper"),
logistics.getString("receiverUnit"),
logistics.getString("receiverName"),
logistics.getString("receiverPhone"),
logistics.getString("receiverAddress"),
logistics.getInteger("itemCount"), // 件数
DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, logistics.getDate("createTime")),
DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, logistics.getDate("updateTime")),
logistics.getString("createBy"),
logistics.getString("updateBy"),
logistics.getString("remark")
);
}).toList();
// 创建 ExcelUtil 对象
ExcelUtil excelUtil = new ExcelUtil(headers);
// 设置目标文件名和路径
String fileName = "logistics_export_" + System.currentTimeMillis() + ".xlsx";
File targetFile = new File(exportPath, fileName);
try (FileOutputStream fos = new FileOutputStream(targetFile)) {
// 写入 Excel 数据
excelUtil.exportData(dataRows, fos);
} catch (Exception e) {
throw new RuntimeException("生成 Excel 文件失败:" + e.getMessage(), e);
}
}
}
```
---
#### 2. 前端调用接口
前端可以通过发送 POST 请求的方式通知后端执行文件生成操作。以下是 Vue 组件的一个简单示例:
```vue
<template>
<div>
<el-button type="success" @click="handleExport">导出物流信息</el-button>
</div>
</template>
<script>
export default {
methods: {
async handleExport() {
const params = {}; // 这里可以根据需求动态传参筛选要导出的数据
await this.$axios.post('/api/logistics/export', params).then(response => {
console.log('导出成功:', response.data.message);
}).catch(error => {
console.error('导出失败:', error);
});
},
},
};
</script>
```
---
#### 3. 控制器层代码
最后,在后端定义一个 RESTful 接口来接收前端请求并触发文件生成流程。
```java
@RestController
@RequestMapping("/api/logistics")
public class LogisticsController {
@PostMapping("/export")
public ResponseEntity<String> exportLogisticsInfo(@RequestBody Map<String, Object> queryParams) {
try {
// 查询物流信息(此处省略具体查询逻辑)
List<JSONObject> logisticsList = queryLogisticsFromDatabase(queryParams);
// 指定保存路径
String exportPath = "/path/to/save/excel/files/";
// 调用工具类生成 Excel 文件
LogisticsExportService.generateAndSaveExcel(logisticsList, exportPath);
return ResponseEntity.ok("导出成功!");
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("导出失败:" + e.getMessage());
}
}
private List<JSONObject> queryLogisticsFromDatabase(Map<String, Object> queryParams) {
// TODO: 实现具体的数据库查询逻辑
return null;
}
}
```
---
### 注意事项
- **权限控制**:确保只有授权用户才能访问导出功能。
- **大文件处理**:当数据量较大时,建议采用分页读取或异步任务的方式来减少内存占用。
- **路径验证**:对 `exportPath` 参数进行严格的合法性校验,防止恶意攻击者尝试覆盖重要系统文件[^3]。
---
####
阅读全文
相关推荐










