Java 导出 Excel 文件

java

目前,很多报表,都需要导出Excel文件

首先,maven

 <dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi-ooxml</artifactId>

<version>3.8</version>

</dependency>

标题对象

@Data

public class ExcelTitleName {

String name;

String value;

public ExcelTitleName(String value, String name) {

this.name = name;

this.value = value;

}

}

标题

 public static List<ExcelTitleName> getOrder() {

List<ExcelTitleName> orderMap = new ArrayList<>();

orderMap.add(new ExcelTitleName("orderId", "订单号"));

orderMap.add(new ExcelTitleName("orderType", "订单类型"));

orderMap.add(new ExcelTitleName("createTime", "下单时间"));

orderMap.add(new ExcelTitleName("userName", "买家名称"));

orderMap.add(new ExcelTitleName("status", "订单状态"));

orderMap.add(new ExcelTitleName("supplierName", "供应商名称"));

orderMap.add(new ExcelTitleName("paymentName", "付款类型"));

orderMap.add(new ExcelTitleName("payStatus", "付款状态"));

orderMap.add(new ExcelTitleName("payTime", "付款时间"));

orderMap.add(new ExcelTitleName("payType", "付款方式"));

orderMap.add(new ExcelTitleName("shipType", "物流方式"));

orderMap.add(new ExcelTitleName("goodsAmount", "商品总价"));

orderMap.add(new ExcelTitleName("shipAmount", "物流费用"));

orderMap.add(new ExcelTitleName("couponAmount", "折扣金额"));

orderMap.add(new ExcelTitleName("orderAmount", "订单金额"));

return orderMap;

}

解析过程

 /**

* data 转化为Excel

*/

public void builderOrderExcel(Workbook book, List list,List<ExcelTitleName> map,String title) {

if(CollectionUtils.isEmpty(list)){

return;

}

JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(list));

jsonArray.add(0, new Object()); //标题占位

Sheet sheet1 = book.createSheet(title);

Row titleRow = sheet1.createRow(0);

for (int i = 0; i < map.size(); i++) {

Cell cell = titleRow.createCell(i);

cell.setCellValue(map.get(i).getName());

}

for (int rowi = 0; rowi < jsonArray.size(); rowi++) {

Row row = sheet1.createRow(rowi);

for (int contentj = 0; contentj < map.size(); contentj++) {

Cell cell = row.createCell(contentj);

if (rowi == 0) {

//设置标题

cell.setCellValue(map.get(contentj).getName());

} else {

//设置内容

Object value = jsonArray.getJSONObject(rowi).get(map.get(contentj).getValue());

if (value != null) {

cell.setCellValue(String.valueOf(value));

} else {

cell.setCellValue("");

}

}

}

}

}

调用

  //创建Excel

Workbook workbook = new HSSFWorkbook();

//创建order

deliveryGoodsResNberExcel.builderOrderExcel(workbook, data.getOrderList(),

OrderExportUtil.getOrder(), "订单");

 

以上是 Java 导出 Excel 文件 的全部内容, 来源链接: utcz.com/z/390653.html

回到顶部