Просмотр исходного кода

支持生成excel,但没有提供接口及完善

insomniaLee 6 лет назад
Родитель
Сommit
562066a7e7

+ 13 - 0
pom.xml

@@ -133,6 +133,19 @@
             <artifactId>spring-boot-starter-data-mongodb</artifactId>
         </dependency>
 
+        <!-- 基本依赖,仅操作 xls 格式只需引入此依赖 -->
+        <dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi</artifactId>
+            <version>3.14</version>
+        </dependency>
+        <!-- 使用 xlsx 格式需要额外引入此依赖 -->
+        <dependency>
+            <groupId>org.apache.poi</groupId>
+            <artifactId>poi-ooxml</artifactId>
+            <version>3.14</version>
+        </dependency>
+
 
     </dependencies>
 

+ 17 - 1
src/main/java/com/mooctest/controller/FinalReportController.java

@@ -6,6 +6,8 @@ import com.mooctest.data.TaskDTO;
 import com.mooctest.service.BugReportService;
 import com.mooctest.service.FinalReportService;
 import com.mooctest.service.TaskService;
+import com.mooctest.util.Report2Excel;
+import com.mooctest.util.Report2xls;
 import com.mooctest.util.ReportUtil;
 import org.apache.tomcat.util.http.fileupload.IOUtils;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -38,7 +40,7 @@ public class FinalReportController {
         return finalReportService.save(dto);
     }
 
-    @GetMapping("final_reports")
+  @GetMapping("final_reports")
     public String getByExamIdAndCaseId(@RequestParam("examId") long examId,
                                        @RequestParam("caseId") long caseId,
                                        Model model) {
@@ -55,6 +57,20 @@ public class FinalReportController {
         return "final_report_list";
     }
 
+    @GetMapping("final_reports_export")
+    @ResponseBody
+    public String finalExport2Excel(@RequestParam("examId") long examId,
+                                       @RequestParam("caseId") long caseId,
+                                       Model model) {
+
+        List<FinalReportDTO> finalReports = finalReportService.getByExamIdAndCaseId(examId, caseId);
+        TaskDTO task = taskService.getByExamIdAndCaseId(examId, caseId);
+        Report2xls.report2excel(finalReports);
+//        Report2Excel.report2excel(finalReports);
+        return "hello";
+    }
+
+
 
 
     @DeleteMapping("final_report/{reportId}")

+ 154 - 0
src/main/java/com/mooctest/util/Report2Excel.java

@@ -0,0 +1,154 @@
+package com.mooctest.util;
+
+import com.mooctest.data.FinalReportDTO;
+import com.mooctest.model.FinalReport;
+import org.apache.poi.hssf.usermodel.*;
+import org.apache.poi.ss.usermodel.*;
+import org.apache.poi.ss.util.CellRangeAddress;
+
+import javax.imageio.ImageIO;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.List;
+
+import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
+import org.apache.poi.hssf.usermodel.HSSFPatriarch;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
+
+public class Report2Excel {
+    private static String []  theads  = {"报告ID","bug分类","级别","复现程度","描述",
+                                    "图片1","图片2","图片3","图片4","图片5","图片6","图片7","图片8",
+                                    "图片9","图片10","图片11","图片12","图片13","图片14","图片15"
+            ,"图片16","图片17","图片18","图片19"};
+
+
+
+    public static void  report2excel (List<FinalReportDTO> reports){
+        FileOutputStream out = null;
+        try {
+            out = new FileOutputStream("testXSSF.xlsx");
+            createExcel(reports,"org.apache.poi.xssf.usermodel.XSSFWorkbook").write(out);
+            out.close();
+        } catch (java.io.IOException e) {
+            e.printStackTrace();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    /**
+     * 构造 Workbook 对象,具体实例化哪种对象由 type 参数指定
+     * @param data 要导出的数据
+     * @param type Excel 生成方式
+     * @return 对应 type 的工作簿实例对象
+     * @throws Exception 反射生成对象时出现的异常
+     * <li>InstantiationException</li>
+     * <li>IllegalAccessException</li>
+     * <li>InstantiationException</li>
+     */
+    public static Workbook createExcel(List<FinalReportDTO> data, String type)
+            throws Exception{
+        //根据 type 参数生成工作簿实例对象
+        Workbook workbook = (Workbook) Class.forName(type).newInstance();
+        //这里还可以指定 sheet 的名字
+        //Sheet sheet = workbook.createSheet("sheetName");
+        Sheet sheet = workbook.createSheet();
+        sheet.setDefaultColumnWidth((short)60*256);
+        sheet.setDefaultRowHeight((short)(30*256));
+        Drawing patriarch = sheet.createDrawingPatriarch(); // ===
+
+        int maxImgLength = max(getMaxImgs(data),10); // 获得最大的图片列数
+        // 限定列数
+        int cols = 7+maxImgLength;
+        Row thead = sheet.createRow(0);//设置表头
+//        thead.setHeight((short)5000);//set height of table head
+//        CellStyle headStyle = getTheadStyle(workbook);//获得到表头的style
+//        thead.setRowStyle(headStyle); // 为表头设置style
+        for(int i =0;i<cols;i++){
+            Cell cell = thead.createCell(i);
+            cell.setCellValue(theads[i]);
+        }
+        //头部设置完毕
+
+        FileOutputStream fileOut = null;
+        BufferedImage bufferImg = null;
+        int tempWidth ;
+        int tempHeight;
+        ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
+        int fitSize [] ;
+
+        for (int rowNum = 0; rowNum < data.size()&&rowNum<8; rowNum++) {
+            Row row = sheet.createRow(rowNum+1);
+            row.setHeight((short)3000);//set height of table head
+            FinalReportDTO dto = data.get(rowNum);
+            row.createCell(0).setCellValue(rowNum+1);
+            row.createCell(1).setCellValue(ReportUtil.category2String.get(dto.getCategory()));
+            row.createCell(2).setCellValue(ReportUtil.severity2String.get(dto.getSeverity()));
+            row.createCell(3).setCellValue(ReportUtil.recurrent2String.get(dto.getRecurrent()));
+            row.createCell(4).setCellValue(dto.getDescription());
+            for(int photoIndex = 0;dto.getImgUrls()!=null&&photoIndex<maxImgLength&&photoIndex<dto.getImgUrls().length;photoIndex++){
+                URL url = new URL(dto.getImgUrls()[photoIndex]);
+                URLConnection connection = url.openConnection();
+                connection.setDoOutput(true);
+                bufferImg = ImageIO.read(connection.getInputStream());
+                tempWidth = bufferImg.getWidth();
+                tempHeight = bufferImg.getHeight();
+                fitSize = getFitHeightAndWidth(tempHeight,tempWidth);
+                ImageIO.write(bufferImg, "jpg", byteArrayOut);
+                XSSFClientAnchor anchor = new XSSFClientAnchor(fitSize[1]*4, fitSize[0], 0, 0,(short) (5+photoIndex), (rowNum+1), (short) (6+photoIndex), rowNum+2);
+                //插入图片 1
+                patriarch.createPicture(anchor, workbook.addPicture(byteArrayOut.toByteArray(), XSSFWorkbook.PICTURE_TYPE_JPEG));
+            }
+        }
+
+        return workbook;
+    }
+
+    /**
+     * 获得报告内的最大图片数量
+     * @param reports
+     * @return
+     */
+    private static int getMaxImgs (List<FinalReportDTO> reports ){
+        int res =0;
+        for (FinalReportDTO dto : reports){
+            if(dto.getImgUrls()!=null)
+                res = max(res,dto.getImgUrls().length);
+        }
+        return res;
+    }
+
+    private static int max(int a, int b) {
+        return a>b?a:b;
+    }
+
+    /**
+     * 0 is Height and 1 is width
+     * @param height
+     * @param width
+     * @return
+     */
+    private static int[] getFitHeightAndWidth(int height,int width){
+        //默认格子的大小是正方形的。
+        int [] res = new int[2];
+        int max = Math.max(height,width);
+        int min = Math.min(height,width);
+        min = (int)( (min*1.0/max)*255 );
+        if(height>width){
+            res[0] = 0;
+            res[1] = 255-min;
+        }else {
+            res[1] = 0;
+            res[0] = 255-min;
+        }
+        return res;
+    }
+}

+ 152 - 0
src/main/java/com/mooctest/util/Report2xls.java

@@ -0,0 +1,152 @@
+package com.mooctest.util;
+
+
+import com.mooctest.data.FinalReportDTO;
+import org.apache.poi.hssf.usermodel.*;
+import org.apache.poi.ss.usermodel.Cell;
+import org.apache.poi.ss.usermodel.Row;
+
+import javax.imageio.ImageIO;
+import java.awt.image.BufferedImage;
+import java.io.ByteArrayOutputStream;
+import java.io.FileOutputStream;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.List;
+
+public class Report2xls {
+    private static String []  theads  = {"报告ID","bug分类","级别","复现程度","描述",
+            "图片1","图片2","图片3","图片4","图片5","图片6","图片7","图片8",
+            "图片9","图片10","图片11","图片12","图片13","图片14","图片15"
+            ,"图片16","图片17","图片18","图片19"};
+
+
+
+    public static void  report2excel (List<FinalReportDTO> data){
+        FileOutputStream fileOut = null; // 为了输出excel 文件
+        BufferedImage bufferImg = null;
+        HSSFCellStyle desCellStyle ;
+        HSSFCellStyle lineCellStyle ;
+        try {
+            ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
+
+            int maxImgLength = max(getMaxImgs(data),10); // 获得最大的图片列数
+            // 限定列数
+//            int cols = 6+maxImgLength;
+
+            HSSFWorkbook wb = new HSSFWorkbook();
+            HSSFSheet sheet1 = wb.createSheet("sheet1");
+            for (int i =5;i<maxImgLength;i++){
+                sheet1.setColumnWidth((short)i,(short)60*256);
+
+            }
+            sheet1.setColumnWidth((short)4,(short)30*256); // 设置描述列的宽度
+            desCellStyle = wb.createCellStyle();
+            desCellStyle.setWrapText(true);
+            lineCellStyle = wb.createCellStyle();
+            lineCellStyle.setAlignment(HSSFCellStyle.VERTICAL_CENTER);//设置文字居中,垂直居中
+            sheet1.setDefaultRowHeight((short)(30*256));
+            HSSFPatriarch patriarch = sheet1.createDrawingPatriarch(); // 创建的用来画图的
+            HSSFClientAnchor anchor;
+            Cell cell1,cell2,cell3,cell4,cell0;
+
+            int tempWidth;
+            int tempHeight;
+            int fitSize [] ;
+            Row thead = sheet1.createRow(0);
+//            thead.setHeight((short)256);
+            thead.setHeight((short)480);
+            for(int i =0;i<4+maxImgLength&&i<20;i++){
+                thead.createCell(i).setCellValue(theads[i]);
+            }
+//            sheet1.setDefaultRowHeight((short)(30*256));
+            for (int rowNum = 0; rowNum < data.size()&&rowNum<588; rowNum++) {
+                Row row = sheet1.createRow(rowNum+1);
+                //row.setHeight((short)(30*256));
+                if(rowNum<580){
+                    continue;
+                }
+                FinalReportDTO dto = data.get(rowNum);
+                cell0 = row.createCell(0);
+                cell0.setCellValue(rowNum+1);
+                cell0.setCellStyle(lineCellStyle);
+                cell1 = row.createCell(1);
+                cell1.setCellValue(ReportUtil.category2String.get(dto.getCategory()));
+                cell1.setCellStyle(lineCellStyle);
+                cell2 =  row.createCell(2);
+                cell2.setCellValue(ReportUtil.severity2String.get(dto.getSeverity()));
+                cell2.setCellStyle(lineCellStyle);
+                cell3 = row.createCell(3);
+                cell3.setCellValue(ReportUtil.recurrent2String.get(dto.getRecurrent()));
+                cell3.setCellStyle(lineCellStyle);
+                cell4 = row.createCell(4);
+                cell4.setCellStyle(desCellStyle);
+                cell4.setCellValue(dto.getDescription());
+                if(dto.getImgUrls()!=null){
+                    row.setHeight((short)(30*256)); // 说明有图片,设置高度
+                    for(int photoIndex = 0;photoIndex<maxImgLength&&photoIndex<dto.getImgUrls().length;photoIndex++){
+                        URL url = new URL(dto.getImgUrls()[photoIndex]);
+                        URLConnection connection = url.openConnection();
+                        connection.setDoOutput(true);
+                        bufferImg = ImageIO.read(connection.getInputStream());
+                        tempWidth = bufferImg.getWidth();
+                        tempHeight = bufferImg.getHeight();
+                        fitSize = getFitHeightAndWidth(tempHeight,tempWidth);
+                        ImageIO.write(bufferImg, "jpg", byteArrayOut);
+                        anchor = new HSSFClientAnchor(fitSize[1]*4, fitSize[0], 0, 0,(short) (5+photoIndex), (rowNum+1), (short) (6+photoIndex), rowNum+2);
+                        //插入图片 1
+                        patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
+                        bufferImg = null;
+                        byteArrayOut = new ByteArrayOutputStream();
+                    }
+                }
+            }
+            fileOut = new FileOutputStream("excel.xls");
+            wb.write(fileOut);
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    /**
+     * 获得报告内的最大图片数量
+     * @param reports
+     * @return
+     */
+    private static int getMaxImgs (List<FinalReportDTO> reports ){
+        int res =0;
+        for (FinalReportDTO dto : reports){
+            if(dto.getImgUrls()!=null)
+                res = max(res,dto.getImgUrls().length);
+        }
+        return res;
+    }
+
+    private static int max(int a, int b) {
+        return a>b?a:b;
+    }
+
+    /**
+     * 0 is Height and 1 is width
+     * @param height
+     * @param width
+     * @return
+     */
+    private static int[] getFitHeightAndWidth(int height,int width){
+        //默认格子的大小是正方形的。
+        int [] res = new int[2];
+        int max = Math.max(height,width);
+        int min = Math.min(height,width);
+        min = (int)( (min*1.0/max)*255 );
+        if(height>width){
+            res[0] = 0;
+            res[1] = 255-min;
+        }else {
+            res[1] = 0;
+            res[0] = 255-min;
+        }
+        return res;
+    }
+
+
+}