两个实体间转换导出excel
首先建两个实体
public class Order {
private Long id;
private String orderNo;
private String customerName;
private Date createTime;
// getter 和 setter 方法
}
public class OrderVO {
private String orderNo;
private String customerName;
private String createTime;
// getter 和 setter 方法
}
其次,在 OrderVO 类中定义一个静态方法 fromOrder(),用于将 Order 转换为 OrderVO 对象。
public class OrderVO {
private String orderNo;
private String customerName;
private String createTime;
// getter 和 setter 方法public static OrderVO fromOrder(Order order) {OrderVO orderVO = new OrderVO();orderVO.setOrderNo(order.getOrderNo());orderVO.setCustomerName(order.getCustomerName());orderVO.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(order.getCreateTime()));return orderVO;
}
}
最后方法内应用
在 Controller 类中编写导出 Excel 数据的方法。
@GetMapping("/export")
public void exportExcel(HttpServletResponse response) {
// 查出数据,原始的Java实体List<Order> orderList = orderService.getOrderList();// 将 Order 转换为 OrderVOList<OrderVO> orderVOList = orderList.stream().map(OrderVO::fromOrder).collect(Collectors.toList());// 将 OrderVO 列表写入 Excel 文件String[] titles = { "订单编号", "客户姓名", "创建时间" };try (XSSFWorkbook workbook = new XSSFWorkbook()) {XSSFSheet sheet = workbook.createSheet("订单列表");// 设置标题行XSSFRow titleRow = sheet.createRow(0);for (int i = 0; i < titles.length; i++) {titleRow.createCell(i).setCellValue(titles[i]);}// 填充数据行for (int i = 0; i < orderVOList.size(); i++) {XSSFRow row = sheet.createRow(i + 1);OrderVO orderVO = orderVOList.get(i);row.createCell(0).setCellValue(orderVO.getOrderNo());row.createCell(1).setCellValue(orderVO.getCustomerName());row.createCell(2).setCellValue(orderVO.getCreateTime());}// 写入 Excel 文件到输出流response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("utf-8");response.setHeader("Content-Disposition", "");............