فهرست منبع

feat: 完成了Excel报表功能

Gudge-ZL 2 سال پیش
والد
کامیت
d76447cc72

+ 32 - 0
pom.xml

@@ -52,6 +52,38 @@
 			<artifactId>aliyun-sdk-oss</artifactId>
 			<version>3.15.1</version>
 		</dependency>
+
+        <dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi</artifactId>
+            <version>3.17</version>
+        </dependency>
+
+        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
+        <dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi-ooxml</artifactId>
+            <version>3.17</version>
+        </dependency>
+
+        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-contrib -->
+        <dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi-contrib</artifactId>
+            <version>3.6</version>
+        </dependency>
+        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
+        <dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi-ooxml-schemas</artifactId>
+            <version>3.17</version>
+        </dependency>
+        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
+        <dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi-scratchpad</artifactId>
+            <version>3.17</version>
+        </dependency>
 	</dependencies>
 
 	<build>

+ 25 - 0
src/main/java/com/seecoder/BlueWhale/controller/ExcelController.java

@@ -0,0 +1,25 @@
+package com.seecoder.BlueWhale.controller;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import com.seecoder.BlueWhale.service.ExcelService;
+
+import org.springframework.web.bind.annotation.GetMapping;
+
+
+@RestController
+@RequestMapping("/api/excel")
+public class ExcelController {
+
+    @Autowired
+    ExcelService excelService;
+
+    @GetMapping
+    public ResponseEntity<byte[]> export(){
+        return excelService.export();
+    }
+    
+}

+ 7 - 0
src/main/java/com/seecoder/BlueWhale/service/ExcelService.java

@@ -0,0 +1,7 @@
+package com.seecoder.BlueWhale.service;
+
+import org.springframework.http.ResponseEntity;
+
+public interface ExcelService {
+    public ResponseEntity<byte[]> export();
+}

+ 25 - 0
src/main/java/com/seecoder/BlueWhale/serviceImpl/ExcelServiceImpl.java

@@ -0,0 +1,25 @@
+package com.seecoder.BlueWhale.serviceImpl;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Service;
+
+import com.seecoder.BlueWhale.service.ExcelService;
+import com.seecoder.BlueWhale.service.OrderService;
+import com.seecoder.BlueWhale.util.ExcelUtil;
+
+@Service
+public class ExcelServiceImpl implements ExcelService{
+
+    @Autowired
+    ExcelUtil excelUtil;
+
+    @Autowired
+    OrderService orderService;
+
+    @Override
+    public ResponseEntity<byte[]> export() {
+        return excelUtil.exportExcel(orderService.getAllOrders());
+    }
+    
+}

+ 10 - 5
src/main/java/com/seecoder/BlueWhale/serviceImpl/OrderServiceImpl.java

@@ -51,13 +51,18 @@ public class OrderServiceImpl implements OrderService {
     public List<OrderVO> getAllOrders() {
         User user=securityUtil.getCurrentUser();
         List<Order> orders;
-        if (user.getRole()== RoleEnum.CUSTOMER){
+        if (user.getRole()==RoleEnum.CUSTOMER){
             orders = orderRepository.findByUserId(user.getId());
         }else {
-            Integer storeId=user.getStoreId();
-            orders = orderRepository.findAll().stream()
-                    .filter(x-> storeId.equals(productRepository.findById(x.getProductId()).get().getStoreId()))
-                    .collect(Collectors.toList());
+            if (user.getRole()==RoleEnum.STAFF) {
+                Integer storeId=user.getStoreId();
+                orders = orderRepository.findAll().stream()
+                        .filter(x-> storeId.equals(productRepository.findById(x.getProductId()).get().getStoreId()))
+                        .collect(Collectors.toList());
+            }else {
+                orders = orderRepository.findAll().stream()
+                        .collect(Collectors.toList());
+            }
         }
         return orders.stream().map(x->wrapWithProductId(x.toVO())).collect(Collectors.toList());
     }

+ 167 - 0
src/main/java/com/seecoder/BlueWhale/util/ExcelUtil.java

@@ -0,0 +1,167 @@
+package com.seecoder.BlueWhale.util;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URLEncoder;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.poi.hssf.util.HSSFColor;
+import org.apache.poi.ss.usermodel.BorderStyle;
+import org.apache.poi.ss.usermodel.CellStyle;
+import org.apache.poi.ss.usermodel.FillPatternType;
+import org.apache.poi.ss.usermodel.Font;
+import org.apache.poi.ss.usermodel.HorizontalAlignment;
+import org.apache.poi.ss.usermodel.VerticalAlignment;
+import org.apache.poi.util.IOUtils;
+import org.apache.poi.xssf.streaming.SXSSFCell;
+import org.apache.poi.xssf.streaming.SXSSFRow;
+import org.apache.poi.xssf.streaming.SXSSFSheet;
+import org.apache.poi.xssf.streaming.SXSSFWorkbook;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Component;
+import org.springframework.util.StringUtils;
+
+import com.seecoder.BlueWhale.vo.OrderVO;
+
+@Component
+public class ExcelUtil {
+
+    public CellStyle headSytle(SXSSFWorkbook workbook) {
+        // 设置style1的样式,此样式运用在第二行
+        CellStyle style1 = workbook.createCellStyle();// cell样式
+        // 设置单元格背景色,设置单元格背景色以下两句必须同时设置
+        style1.setFillPattern(FillPatternType.SOLID_FOREGROUND);// 设置填充样式
+        style1.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);// 设置填充色
+        // 设置单元格上、下、左、右的边框线
+        style1.setBorderBottom(BorderStyle.THIN);
+        style1.setBorderLeft(BorderStyle.THIN);
+        style1.setBorderRight(BorderStyle.THIN);
+        style1.setBorderTop(BorderStyle.THIN);
+        Font font1 = workbook.createFont();// 创建一个字体对象
+//        font1.setBoldweight((short) 10);// 设置字体的宽度
+        font1.setFontHeightInPoints((short) 10);// 设置字体的高度
+        font1.setBold(true);// 粗体显示
+        style1.setFont(font1);// 设置style1的字体
+        style1.setWrapText(true);// 设置自动换行
+        style1.setAlignment(HorizontalAlignment.CENTER);// 设置单元格字体显示居中(左右方向)
+        style1.setVerticalAlignment(VerticalAlignment.CENTER);// 设置单元格字体显示居中(上下方向)
+        return style1;
+    }
+
+    public CellStyle contentStyle(SXSSFWorkbook wb) {
+        // 设置style1的样式,此样式运用在第二行
+        CellStyle style1 = wb.createCellStyle();// cell样式
+        // 设置单元格上、下、左、右的边框线
+        style1.setBorderBottom(BorderStyle.THIN);
+        style1.setBorderLeft(BorderStyle.THIN);
+        style1.setBorderRight(BorderStyle.THIN);
+        style1.setBorderTop(BorderStyle.THIN);
+        style1.setWrapText(true);// 设置自动换行
+        style1.setAlignment(HorizontalAlignment.CENTER);// 设置单元格字体显示居中(左右方向)
+        style1.setVerticalAlignment(VerticalAlignment.CENTER);// 设置单元格字体显示居中(上下方向)
+        return style1;
+    }
+
+    public void initTitleEX(SXSSFSheet sheet, CellStyle header, List<String> attributeList, int titleLength[]) {
+        SXSSFRow row0 = sheet.createRow(0);
+        row0.setHeight((short) 800);
+        for (int j = 0; j < attributeList.size(); j++) {
+            SXSSFCell cell = row0.createCell(j);
+            //设置每一列的字段名
+            cell.setCellValue(attributeList.get(j));
+            cell.setCellStyle(header);
+            sheet.setColumnWidth(j, titleLength[j]);
+        }
+    }
+
+    public ResponseEntity<byte[]> buildResponseEntity(InputStream is, String name) throws Exception {
+
+        HttpHeaders header = new HttpHeaders();
+        String fileSuffix = name.substring(name.lastIndexOf('.') + 1);
+        fileSuffix = fileSuffix.toLowerCase();
+
+        Map<String, String> arguments = new HashMap<String, String>();
+        arguments.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
+        arguments.put("xls", "application/vnd.ms-excel");
+
+        String contentType = arguments.get(fileSuffix);
+        header.add("Content-Type", (StringUtils.hasText(contentType) ? contentType : "application/x-download"));
+        if (is != null && is.available() != 0) {
+            header.add("Content-Length", String.valueOf(is.available()));
+            header.add("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(name, "UTF-8"));
+            byte[] bs = IOUtils.toByteArray(is);
+            return new ResponseEntity<>(bs, header, HttpStatus.OK);
+        } else {
+            String string = "数据为空";
+            header.add("Content-Length", "0");
+            return new ResponseEntity<>(string.getBytes(), header, HttpStatus.OK);
+        }
+    }
+
+    public ResponseEntity<byte[]> exportExcel(List<OrderVO> orders) {
+
+        ByteArrayOutputStream output = null;
+        InputStream inputStream1 = null;
+        SXSSFWorkbook wb = new SXSSFWorkbook(1000);// 保留1000条数据在内存中
+        SXSSFSheet sheet = wb.createSheet();
+        // 设置报表头样式
+        CellStyle header = headSytle(wb);
+        // 报表体样式 cell样式
+        CellStyle content = contentStyle(wb);
+        // 每一列字段名
+        List<String> attributeList = orders.get(0).getHeaderList();
+        // 字段名所在表格的宽度
+        int[] ints = new int[attributeList.size()];
+        for (int i = 0; i < ints.length; i++) {
+            ints[i] = 5000;
+        }
+
+        // 设置表头样式
+        initTitleEX(sheet, header, attributeList, ints);
+        //写入表格
+        for (OrderVO orderVO : orders) {
+            SXSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1);
+            List<Object> cellContent = orderVO.getCellContent();
+            int columnNumber = 0;
+            for (Object item : cellContent) {
+                SXSSFCell cell = row.createCell(columnNumber++);
+                cell.setCellValue(String.valueOf(item));
+            }
+        }
+        
+        try {
+            //将wb中的数据以字节形式存到inputStream1中
+            output = new ByteArrayOutputStream();
+            wb.write(output);
+            inputStream1 = new ByteArrayInputStream(output.toByteArray());
+            output.flush();
+        } catch (Exception e) {
+            e.printStackTrace();
+        } finally {
+            try {
+                if (output != null) {
+                    output.close();
+                    if (inputStream1 != null) {
+                        inputStream1.close();
+                    }
+                }
+            } catch (IOException e) {
+                e.printStackTrace();
+            }
+        }
+
+        try {
+            return buildResponseEntity(inputStream1, "订单列表.xlsx");
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return null;
+
+    }
+}

+ 42 - 0
src/main/java/com/seecoder/BlueWhale/vo/OrderVO.java

@@ -1,6 +1,8 @@
 package com.seecoder.BlueWhale.vo;
 
+import java.util.ArrayList;
 import java.util.Date;
+import java.util.List;
 
 import com.seecoder.BlueWhale.enums.OrderStatusEnum;
 import com.seecoder.BlueWhale.enums.OrderTypeEnum;
@@ -58,4 +60,44 @@ public class OrderVO {
         order.setUserId(this.userId);
         return order;
     }
+
+    public List<String> getHeaderList() {
+        return new ArrayList<String>() {
+            {
+                add("订单编号");
+                add("用户编号");
+                add("商品编号");
+                add("商品数量");
+                add("付款额");
+                add("订单类型");
+                add("订单评价");
+                add("订单评分");
+                add("订单状态");
+                add("订单创建时间");
+                add("订单完成时间");
+                add("商品名称");
+                add("商店编号");
+                add("订单金额");
+            }
+        };
+    }
+
+    public List<Object> getCellContent() {
+        List<Object> content = new ArrayList<>();
+        content.add(this.id);
+        content.add(this.userId);
+        content.add(this.productId);
+        content.add(this.amount);
+        content.add(this.paid);
+        content.add(this.type);
+        content.add(this.content);
+        content.add(this.rating);
+        content.add(this.status);
+        content.add(this.createTime);
+        content.add(this.finishTime);
+        content.add(this.productName);
+        content.add(this.storeId);
+        content.add(this.price);
+        return content;
+    }
 }