diff --git a/pom.xml b/pom.xml index 8e3af44..9acfb63 100644 --- a/pom.xml +++ b/pom.xml @@ -62,7 +62,7 @@ org.apache.poi poi-ooxml - 3.14 + 3.16 diff --git a/src/main/java/net/educoder/ecsonar/controller/MainController.java b/src/main/java/net/educoder/ecsonar/controller/MainController.java index 4983581..0eb6f6f 100644 --- a/src/main/java/net/educoder/ecsonar/controller/MainController.java +++ b/src/main/java/net/educoder/ecsonar/controller/MainController.java @@ -41,4 +41,11 @@ public class MainController { } + @PostMapping(value = "/scanExcel") + public String scanExcel(@RequestParam String excelPath) throws Exception { + ecsonarService.scanExcel(excelPath); + return "success"; + } + + } diff --git a/src/main/java/net/educoder/ecsonar/services/EcsonarService.java b/src/main/java/net/educoder/ecsonar/services/EcsonarService.java index fb0e83b..1177bb4 100644 --- a/src/main/java/net/educoder/ecsonar/services/EcsonarService.java +++ b/src/main/java/net/educoder/ecsonar/services/EcsonarService.java @@ -519,4 +519,8 @@ public class EcsonarService { } + public void scanExcel(String excelPath){ + sonarService.scanExcel(excelPath); + } + } diff --git a/src/main/java/net/educoder/ecsonar/services/ReportService.java b/src/main/java/net/educoder/ecsonar/services/ReportService.java index f828324..219327d 100644 --- a/src/main/java/net/educoder/ecsonar/services/ReportService.java +++ b/src/main/java/net/educoder/ecsonar/services/ReportService.java @@ -4,11 +4,13 @@ import net.educoder.ecsonar.dao.ProjectDao; import net.educoder.ecsonar.model.Metrics; import net.educoder.ecsonar.model.Project; import net.educoder.ecsonar.utils.ExcelUtil; +import org.apache.poi.ss.usermodel.Workbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import java.io.File; import java.io.IOException; @Service @@ -62,8 +64,10 @@ public class ReportService { * @param metrics */ public void writeToExcel(String stuId, String name, - Metrics metrics, String excelPath, int index) throws IOException { -// ExcelUtil.writeMetrics(metrics, stuId, name, excelPath, index); + Metrics metrics, String templatePath, String outPath, int index) throws Exception { + Workbook workbook = ExcelUtil.getWorkbok(new File(templatePath)); + ExcelUtil.writeMetrics(metrics, stuId, name,workbook , index); + ExcelUtil.saveExcel(workbook,outPath); } /** diff --git a/src/main/java/net/educoder/ecsonar/services/SonarService.java b/src/main/java/net/educoder/ecsonar/services/SonarService.java index 468144a..c1eef9b 100644 --- a/src/main/java/net/educoder/ecsonar/services/SonarService.java +++ b/src/main/java/net/educoder/ecsonar/services/SonarService.java @@ -1,17 +1,31 @@ package net.educoder.ecsonar.services; +import net.educoder.ecsonar.model.api.Person; +import net.educoder.ecsonar.model.api.SonarRequest; +import net.educoder.ecsonar.task.ReadExcelRunnable; +import net.educoder.ecsonar.utils.ExcelUtil; +import net.educoder.ecsonar.utils.ExcelUtils; import net.educoder.ecsonar.utils.SystemUtil; import net.educoder.ecsonar.utils.UrlUtil; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.*; import java.net.URL; import java.net.URLConnection; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.stream.Collectors; +import java.util.stream.Stream; @Service public class SonarService { @@ -22,9 +36,15 @@ public class SonarService { @Value("${sonar.url}") String sonarUrl; + @Value("${sonar.token}") + String sonarToken; + @Value("${extract.path}") String extractProgramPath; + @Autowired + private ExecutorService executorService; + /** * 提交一个任务 * @@ -99,16 +119,18 @@ public class SonarService { } - private void sonar(String projectPath, String key) { - SystemUtil.executeAndGetExitStatus("sonar-scanner " + + public void sonar(String projectPath, String key) { + String command = "source ~/.bash_profile && sonar-scanner " + "-Dsonar.host.url=" + sonarUrl + " " + "-Dsonar.sourceEncoding=utf-8 " + "-Dsonar.projectKey=" + key + " " + - "-Dsonar.java.binaries=./ "+ - "-Dsonar.projectBaseDir=" + projectPath); + "-Dsonar.login=" + sonarToken + " " + + "-Dsonar.java.binaries=./ " + + "-Dsonar.projectBaseDir=" + projectPath; + log.info("projectPath:{},key:{}, command: {}", projectPath,key, command); + SystemUtil.executeAndGetExitStatus(command); } - /** * 解压zip文件 * @@ -134,7 +156,7 @@ public class SonarService { private void download(String zipUrl, String zipPath) throws IOException { log.info("下载文件: {}-{}", zipUrl, zipPath); - String cookie = "3567ffee09b5dd08ee05967e23ebf0137a2eeaa9"; + String cookie = "_educoder_session=1f4bf34409fec2180b99aa1cbf0b7586"; URL url = new URL(zipUrl); URLConnection conn = url.openConnection(); conn.setRequestProperty("Cookie", cookie); @@ -153,4 +175,43 @@ public class SonarService { } } + + + /** + * 扫描excel文件 + * @param excelPath + */ + public void scanExcel(String excelPath){ + + int homeworkId = 20210101; + + try { + List personList = ExcelUtil.readExcel(excelPath); + + Map> collect = personList.stream().collect(Collectors.groupingBy(Person::getUid)); + + + List list= new ArrayList<>(collect.size()); + collect.forEach((k,v)->{ + SonarRequest request = new SonarRequest(); + request.setHomeworkId(homeworkId); + request.setPersonList(v); + + // 开始调用sonar分析代码 + Future submit = executorService.submit(new ReadExcelRunnable(request, this)); + list.add(submit); + }); + + for (Future future : list) { + System.out.println(future.get()); + } + + } catch (Exception e) { + e.printStackTrace(); + } + + + } + + } diff --git a/src/main/java/net/educoder/ecsonar/task/ReadExcelRunnable.java b/src/main/java/net/educoder/ecsonar/task/ReadExcelRunnable.java new file mode 100644 index 0000000..c2022c2 --- /dev/null +++ b/src/main/java/net/educoder/ecsonar/task/ReadExcelRunnable.java @@ -0,0 +1,89 @@ +package net.educoder.ecsonar.task; + +import net.educoder.ecsonar.model.api.Person; +import net.educoder.ecsonar.model.api.SonarRequest; +import net.educoder.ecsonar.services.SonarService; +import net.educoder.ecsonar.utils.UrlUtil; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLDecoder; + +/** + * @Author: youys + * @Date: 2022/1/12 + * @Description: + */ +public class ReadExcelRunnable implements Runnable{ + + private final Logger log = LoggerFactory.getLogger(getClass()); + + private SonarRequest sonarRequest; + private SonarService sonarService; + + public ReadExcelRunnable(SonarRequest sonarRequest,SonarService sonarService){ + this.sonarRequest = sonarRequest; + this.sonarService = sonarService; + } + + + @Override + public void run() { + + String uid = sonarRequest.getPersonList().get(0).getUid(); + int homeworkId = sonarRequest.getHomeworkId(); + String path = String.format("/tmp/%d/%s/", homeworkId, uid); + File file = new File(path); + if(!file.exists()){ + file.mkdir(); + } + for (Person person : sonarRequest.getPersonList()) { + String[] split = StringUtils.split(person.getDownloadUrl(), "/"); + String zipFilename = UrlUtil.getURLDecoderString(split[split.length - 1]); + try { + download(person.getDownloadUrl(),path+zipFilename); + } catch (IOException e) { + e.printStackTrace(); + } + } + String key = String.format("%d-%s", homeworkId, uid); + log.info("开始调用sonar:{}",key); + sonarService.sonar(path,key); + } + + private void download(String zipUrl, String zipPath) throws IOException { + log.info("下载文件: {}-{}", zipUrl, zipPath); + + String cookie = "_educoder_session=1f4bf34409fec2180b99aa1cbf0b7586"; + URL url = new URL(zipUrl); + URLConnection conn = url.openConnection(); + conn.setRequestProperty("Cookie", cookie); + conn.setDoInput(true); + + String fileName = conn.getHeaderField("Content-Disposition"); + if(StringUtils.isNotEmpty(fileName)){ + fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8"); + fileName = fileName.substring(fileName.indexOf("filename=")+10,fileName.length()-1); + zipPath = zipPath.substring(0, zipPath.lastIndexOf("/")+1) + fileName; + } + try (BufferedInputStream in = new BufferedInputStream(conn.getInputStream()); + FileOutputStream fileOutputStream = new FileOutputStream(zipPath)) { + byte dataBuffer[] = new byte[1024]; + int bytesRead; + while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { + fileOutputStream.write(dataBuffer, 0, bytesRead); + } + } catch (IOException e) { + log.error("文件下载失败: {}-{}", zipUrl, zipPath); + throw e; + } + + } +} diff --git a/src/main/java/net/educoder/ecsonar/utils/ExcelUtil.java b/src/main/java/net/educoder/ecsonar/utils/ExcelUtil.java index d93d77f..300ddc6 100644 --- a/src/main/java/net/educoder/ecsonar/utils/ExcelUtil.java +++ b/src/main/java/net/educoder/ecsonar/utils/ExcelUtil.java @@ -1,15 +1,14 @@ package net.educoder.ecsonar.utils; import net.educoder.ecsonar.model.Metrics; +import net.educoder.ecsonar.model.api.Person; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.*; +import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -36,7 +35,7 @@ public class ExcelUtil { for (int i = 0; i < rowNumber + 1; ++i) { Row row = sheet.getRow(3 + i); Cell cell = row.getCell(1); - cell.setCellType(Cell.CELL_TYPE_STRING); + cell.setCellType(CellType.STRING); if (StringUtils.equals(cell.getStringCellValue(), uid)) { return true; } @@ -71,12 +70,12 @@ public class ExcelUtil { //从第三行开始 Row newRow = null; - for (int i = 0; i < rowNumber+1; ++i) { + for (int i = 3; i < rowNumber+1; ++i) { Row row = sheet.getRow(i); if (row != null) { Cell cell = row.getCell(1); - cell.setCellType(Cell.CELL_TYPE_STRING); + cell.setCellType(CellType.STRING); if (StringUtils.isEmpty(cell.getStringCellValue()) || StringUtils.equals(cell.getStringCellValue(), uid)) { @@ -93,11 +92,11 @@ public class ExcelUtil { //一直往下找,直到找到空的,或者与学号匹配的行,进行写入 //学号 Cell uidCell = newRow.createCell(1); - uidCell.setCellType(Cell.CELL_TYPE_STRING); + uidCell.setCellType(CellType.STRING); uidCell.setCellValue(uid); Cell cell2 = newRow.createCell(2); - cell2.setCellType(Cell.CELL_TYPE_STRING); + cell2.setCellType(CellType.STRING); cell2.setCellValue(name); int offset = 0; @@ -105,75 +104,75 @@ public class ExcelUtil { offset = 17; } Cell cell3 = newRow.createCell(3 + offset); - cell3.setCellType(Cell.CELL_TYPE_NUMERIC); + cell3.setCellType(CellType.NUMERIC); cell3.setCellValue(metrics.getBlock_bugs()); Cell cell4 = newRow.createCell(4 + offset); - cell4.setCellType(Cell.CELL_TYPE_NUMERIC); + cell4.setCellType(CellType.NUMERIC); cell4.setCellValue(metrics.getCritical_bugs()); cell4 = newRow.createCell(5 + offset); - cell4.setCellType(Cell.CELL_TYPE_NUMERIC); + cell4.setCellType(CellType.NUMERIC); cell4.setCellValue(metrics.getMajor_bugs()); cell4 = newRow.createCell(6 + offset); - cell4.setCellType(Cell.CELL_TYPE_NUMERIC); + cell4.setCellType(CellType.NUMERIC); cell4.setCellValue(metrics.getMinor_bugs()); cell4 = newRow.createCell(7 + offset); - cell4.setCellType(Cell.CELL_TYPE_STRING); + cell4.setCellType(CellType.STRING); cell4.setCellValue(metrics.getBugs()); cell4 = newRow.createCell(8 + offset); - cell4.setCellType(Cell.CELL_TYPE_NUMERIC); + cell4.setCellType(CellType.NUMERIC); cell4.setCellValue(metrics.getBlock_violations()); cell4 = newRow.createCell(9 + offset); - cell4.setCellType(Cell.CELL_TYPE_NUMERIC); + cell4.setCellType(CellType.NUMERIC); cell4.setCellValue(metrics.getCritical_violations()); cell4 = newRow.createCell(10 + offset); - cell4.setCellType(Cell.CELL_TYPE_NUMERIC); + cell4.setCellType(CellType.NUMERIC); cell4.setCellValue(metrics.getMajor_violations()); cell4 = newRow.createCell(11 + offset); - cell4.setCellType(Cell.CELL_TYPE_NUMERIC); + cell4.setCellType(CellType.NUMERIC); cell4.setCellValue(metrics.getMinor_violations()); cell4 = newRow.createCell(12 + offset); - cell4.setCellType(Cell.CELL_TYPE_STRING); + cell4.setCellType(CellType.STRING); cell4.setCellValue(metrics.getViolations()); cell4 = newRow.createCell(13 + offset); - cell4.setCellType(Cell.CELL_TYPE_NUMERIC); + cell4.setCellType(CellType.NUMERIC); cell4.setCellValue(metrics.getBlock_code_smells()); cell4 = newRow.createCell(14 + offset); - cell4.setCellType(Cell.CELL_TYPE_NUMERIC); + cell4.setCellType(CellType.NUMERIC); cell4.setCellValue(metrics.getCritical_code_smells()); cell4 = newRow.createCell(15 + offset); - cell4.setCellType(Cell.CELL_TYPE_NUMERIC); + cell4.setCellType(CellType.NUMERIC); cell4.setCellValue(metrics.getMajor_violations()); cell4 = newRow.createCell(16 + offset); - cell4.setCellType(Cell.CELL_TYPE_NUMERIC); + cell4.setCellType(CellType.NUMERIC); cell4.setCellValue(metrics.getMinor_code_smells()); cell4 = newRow.createCell(17 + offset); - cell4.setCellType(Cell.CELL_TYPE_STRING); + cell4.setCellType(CellType.STRING); cell4.setCellValue(metrics.getCode_smells()); cell4 = newRow.createCell(18 + offset); - cell4.setCellType(Cell.CELL_TYPE_NUMERIC); + cell4.setCellType(CellType.NUMERIC); cell4.setCellValue(metrics.getComplexity()); cell4 = newRow.createCell(19 + offset); - cell4.setCellType(Cell.CELL_TYPE_NUMERIC); + cell4.setCellType(CellType.NUMERIC); cell4.setCellValue(metrics.getLines()); @@ -216,10 +215,35 @@ public class ExcelUtil { return wb; } + /** + * 读取excel + * @param excelPath + * @return + */ + public static List readExcel(String excelPath) throws IOException { + Workbook workbook = getWorkbok(new File(excelPath)); + Sheet sheet = workbook.getSheetAt(0); + + int lastRowNum = sheet.getLastRowNum(); - // 去读Excel的方法readExcel,该方法的入口参数为一个File对象 - public List readExcel(File file) { + List personList = new ArrayList<>(lastRowNum+1); - return null; + // 从第二行开始读 + for (int i = 1; i <= lastRowNum; i++) { + Row row = sheet.getRow(i); + + String name = row.getCell(0).getStringCellValue(); + String uid = row.getCell(1).getStringCellValue(); + String downloadUrl = row.getCell(2).getStringCellValue(); + + Person person = new Person(); + person.setName(name); + person.setUid(uid); + person.setDownloadUrl(downloadUrl); + personList.add(person); + } + + return personList; } + } diff --git a/src/main/java/net/educoder/ecsonar/utils/ExcelUtils.java b/src/main/java/net/educoder/ecsonar/utils/ExcelUtils.java new file mode 100644 index 0000000..76799dc --- /dev/null +++ b/src/main/java/net/educoder/ecsonar/utils/ExcelUtils.java @@ -0,0 +1,431 @@ +package net.educoder.ecsonar.utils; + +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +import java.io.*; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ExcelUtils { + + //模板map + private Map tempWorkbook = new HashMap(); + //模板输入流map + private Map tempStream = new HashMap(); + + /** + *

+ * 描述:临时单元格数据 + *

+ * + * @author zq + * @version V1.0 + * @ClassName: Cell + * @date 2015年9月26日 + */ + class TempCell { + private int row; + private int column; + private CellStyle cellStyle; + private Object data; + //用于列表合并,表示几列合并 + private int columnSize = -1; + + public int getColumn() { + return column; + } + + public void setColumn(int column) { + this.column = column; + } + + public int getRow() { + return row; + } + + public void setRow(int row) { + this.row = row; + } + + public CellStyle getCellStyle() { + return cellStyle; + } + + public void setCellStyle(CellStyle cellStyle) { + this.cellStyle = cellStyle; + } + + public Object getData() { + return data; + } + + public void setData(Object data) { + this.data = data; + } + + public int getColumnSize() { + return columnSize; + } + + public void setColumnSize(int columnSize) { + this.columnSize = columnSize; + } + } + + /** + *

+ * 功能:按模板向Excel中相应地方填充数据 + *

+ * + * @param tempFilePath + * @param dataMap + * @param sheetNo + * @throws IOException + * @date 2015年9月26日 + * @author zq + */ + public void writeData(String tempFilePath, Map dataMap, int sheetNo) throws IOException { + //获取模板填充格式位置等数据 + // HashMap tem = getTemp(tempFilePath,sheet); + //读取模板 + Workbook wbModule = getTempWorkbook(tempFilePath); + //数据填充的sheet + Sheet wsheet = wbModule.getSheetAt(sheetNo); + + Iterator it = dataMap.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry entry = (Map.Entry) it.next(); + String point = entry.getKey(); + Object data = entry.getValue(); + + TempCell cell = getCell(point, data, wsheet); + //指定坐标赋值 + setCell(cell, wsheet); + } + //设置生成excel中公式自动计算 + wsheet.setForceFormulaRecalculation(true); + } + + /** + *

+ * 功能:按模板向Excel中列表填充数据。 只支持列合并 + *

+ * + * @param tempFilePath + * @param heads 列表头部位置集合 + * @param datalist + * @param sheetNo + * @throws FileNotFoundException + * @throws IOException + * @date 2015年9月27日 + * @author zq + */ + public void writeDateList(String tempFilePath, String[] heads, List> datalist, int sheetNo) throws FileNotFoundException, IOException { + //读取模板 + Workbook wbModule = getTempWorkbook(tempFilePath); + //数据填充的sheet + Sheet wsheet = wbModule.getSheetAt(sheetNo); + //列表数据模板cell + List tempCells = new ArrayList(); + for (int i = 0; i < heads.length; i++) { + String point = heads[i]; + TempCell tempCell = getCell(point, null, wsheet); + //取得合并单元格位置 -1:表示不是合并单元格 + int pos = isMergedRegion(wsheet, tempCell.getRow(), tempCell.getColumn()); + if (pos > -1) { + CellRangeAddress range = wsheet.getMergedRegion(pos); + tempCell.setColumnSize(range.getLastColumn() - range.getFirstColumn()); + } + tempCells.add(tempCell); + } + //赋值 + for (int i = 0; i < datalist.size(); i++) { + Map dataMap = datalist.get(i); + for (int j = 0; j < tempCells.size(); j++) { + TempCell tempCell = tempCells.get(j); + tempCell.setRow(tempCell.getRow() + 1); + tempCell.setData(dataMap.get(j + 1)); + setCell(tempCell, wsheet); + } + } + + + } + + + /** + *

+ * 功能:获取输入工作区 + *

+ * + * @param tempFilePath + * @return + * @throws FileNotFoundException + * @throws IOException + * @date 2015年9月26日 + * @author zq + */ + private Workbook getTempWorkbook(String tempFilePath) throws FileNotFoundException, IOException { + if (!tempWorkbook.containsKey(tempFilePath)) { + if (tempFilePath.endsWith(".xlsx")) { + tempWorkbook.put(tempFilePath, new XSSFWorkbook(getFileInputStream(tempFilePath))); + } else if (tempFilePath.endsWith(".xls")) { + tempWorkbook.put(tempFilePath, new HSSFWorkbook(getFileInputStream(tempFilePath))); + } + } + return tempWorkbook.get(tempFilePath); + } + + /** + *

+ * 功能:获得模板输入流 + *

+ * + * @param tempFilePath + * @return + * @throws FileNotFoundException + * @date 2015年9月26日 + * @author zq + */ + private FileInputStream getFileInputStream(String tempFilePath) throws FileNotFoundException { + if (!tempStream.containsKey(tempFilePath)) { + tempStream.put(tempFilePath, new FileInputStream(tempFilePath)); + } + return tempStream.get(tempFilePath); + } + + /** + *

+ * 功能:设置单元格数据,样式 (根据坐标:B3) + *

+ * + * @param point + * @param data + * @param sheet + * @return + * @date 2015年9月27日 + * @author zq + */ + private TempCell getCell(String point, Object data, Sheet sheet) { + TempCell tempCell = new TempCell(); + + //得到列 字母 + String lineStr = ""; + String reg = "[A-Z]+"; + Pattern p = Pattern.compile(reg); + Matcher m = p.matcher(point); + while (m.find()) { + lineStr = m.group(); + } + //将列字母转成列号 根据ascii转换 + char[] ch = lineStr.toCharArray(); + int column = 0; + for (int i = 0; i < ch.length; i++) { + char c = ch[i]; + int post = ch.length - i - 1; + int r = (int) Math.pow(10, post); + column = column + r * ((int) c - 65); + } + tempCell.setColumn(column); + + //得到行号 + reg = "[1-9]+"; + p = Pattern.compile(reg); + m = p.matcher(point); + while (m.find()) { + tempCell.setRow((Integer.parseInt(m.group()) - 1)); + } + + //获取模板指定单元格样式,设置到tempCell (写列表数据的时候用) + Row rowIn = sheet.getRow(tempCell.getRow()); + if (rowIn == null) { + rowIn = sheet.createRow(tempCell.getRow()); + } + Cell cellIn = rowIn.getCell(tempCell.getColumn()); + if (cellIn == null) { + cellIn = rowIn.createCell(tempCell.getColumn()); + } + tempCell.setCellStyle(cellIn.getCellStyle()); + + tempCell.setData(data); + return tempCell; + } + + /** + *

+ * 功能:给指定坐标赋值 + *

+ * + * @param tempCell + * @param sheet + * @date 2015年9月27日 + * @author zq + */ + private void setCell(TempCell tempCell, Sheet sheet) { + if (tempCell.getColumnSize() > -1) { + CellRangeAddress rangeAddress = mergeRegion(sheet, tempCell.getRow(), tempCell.getRow(), tempCell.getColumn(), tempCell.getColumn() + tempCell.getColumnSize()); + setRegionStyle(tempCell.getCellStyle(), rangeAddress, sheet); + } + + Row rowIn = sheet.getRow(tempCell.getRow()); + if (rowIn == null) { + rowIn = sheet.createRow(tempCell.getRow()); + } + Cell cellIn = rowIn.getCell(tempCell.getColumn()); + if (cellIn == null) { + cellIn = rowIn.createCell(tempCell.getColumn()); + } + //根据data类型给cell赋值 + if (tempCell.getData() instanceof String) { + cellIn.setCellValue((String) tempCell.getData()); + } else if (tempCell.getData() instanceof Integer) { + cellIn.setCellValue((int) tempCell.getData()); + } else if (tempCell.getData() instanceof Double) { + cellIn.setCellValue((double) tempCell.getData()); + } else { + cellIn.setCellValue((String) tempCell.getData()); + } + //样式 + if (tempCell.getCellStyle() != null && tempCell.getColumnSize() == -1) { + cellIn.setCellStyle(tempCell.getCellStyle()); + } + + + } + + /** + *

+ * 功能:写到输出流并移除资源 + *

+ * + * @param tempFilePath + * @param os + * @throws FileNotFoundException + * @throws IOException + * @date 2015年9月27日 + * @author zq + */ + public void writeAndClose(String tempFilePath, OutputStream os) throws FileNotFoundException, IOException { + if (getTempWorkbook(tempFilePath) != null) { + getTempWorkbook(tempFilePath).write(os); + tempWorkbook.remove(tempFilePath); + } + if (getFileInputStream(tempFilePath) != null) { + getFileInputStream(tempFilePath).close(); + tempStream.remove(tempFilePath); + } + } + + /** + *

+ * 功能:判断指定的单元格是否是合并单元格 + *

+ * + * @param sheet + * @param row + * @param column + * @return 0:不是合并单元格,i:合并单元格的位置 + * @date 2015年9月27日 + * @author zq + */ + private Integer isMergedRegion(Sheet sheet, int row, int column) { + int sheetMergeCount = sheet.getNumMergedRegions(); + for (int i = 0; i < sheetMergeCount; i++) { + CellRangeAddress range = sheet.getMergedRegion(i); + int firstColumn = range.getFirstColumn(); + int lastColumn = range.getLastColumn(); + int firstRow = range.getFirstRow(); + int lastRow = range.getLastRow(); + if (row >= firstRow && row <= lastRow) { + if (column >= firstColumn && column <= lastColumn) { + return i; + } + } + } + return -1; + } + + /** + *

+ * 功能:合并单元格 + *

+ * + * @param sheet + * @param firstRow + * @param lastRow + * @param firstCol + * @param lastCol + * @date 2015年9月27日 + * @author zq + */ + private CellRangeAddress mergeRegion(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) { + CellRangeAddress rang = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol); + sheet.addMergedRegion(rang); + return rang; + } + + /** + *

+ * 功能:设置合并单元格样式 + *

+ * + * @param cs + * @param region + * @param sheet + * @date 2015年9月27日 + * @author zq + */ + private static void setRegionStyle(CellStyle cs, CellRangeAddress region, Sheet sheet) { + for (int i = region.getFirstRow(); i <= region.getLastRow(); i++) { + Row row = sheet.getRow(i); + if (row == null) row = sheet.createRow(i); + for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++) { + Cell cell = row.getCell(j); + if (cell == null) { + cell = row.createCell(j); + cell.setCellValue(""); + } + cell.setCellStyle(cs); + } + } + } + + + public static void main(String[] args) throws FileNotFoundException, IOException { + String tempFilePath = ExcelUtil.class.getClassLoader().getResource("template1.xlsx").getPath(); +// String tempFilePath = "D:/demo.xlsx"; + File file = new File("/Users/youyongsheng/Desktop/data.xlsx"); + OutputStream os = new FileOutputStream(file); + + ExcelUtils excel = new ExcelUtils(); + Map dataMap = new HashMap(); + excel.writeData(tempFilePath, dataMap, 0); + + List> datalist = new ArrayList>(); + Map data = new HashMap(); + data.put(1, "defff"); + data.put(2, "男1"); + data.put(3, 45); + data.put(4, 111); + datalist.add(data); + data.put(1, "hhhhhh"); + data.put(2, "男2"); + data.put(3, 46); + data.put(4, 222); + datalist.add(data); + String[] heads = new String[]{"A5", "C5", "E5","D5"}; //必须为列表头部所有位置集合, 输出 数据单元格样式和头部单元格样式保持一致 + excel.writeDateList(tempFilePath, heads, datalist, 0); + + //写到输出流并移除资源 + excel.writeAndClose(tempFilePath, os); + + os.flush(); + os.close(); + } + + +} \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 2738522..0b02acd 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,7 +1,7 @@ -#spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/sonar -spring.datasource.url=jdbc:postgresql://117.50.14.123:5432/sonar -spring.datasource.username=sonar -spring.datasource.password=sonar +spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/sonar7.7 +#spring.datasource.url=jdbc:postgresql://117.50.14.123:5432/sonar +spring.datasource.username=root +spring.datasource.password=root spring.datasource.driver-class-name=org.postgresql.Driver @@ -18,16 +18,19 @@ spring.datasource.hikari.connection-test-query=SELECT 1 logging.config=classpath:logback-spring.xml -logging.level.root=DEBUG +logging.level.root=INFO zip.save.path=/tmp/ #excel.template.path=/Users/guange/work/java/ecsonar/src/main/resources/template.xlsx -excel.template.path=/Users/macbookpro/IdeaProjects/p9vymrkc8/src/main/resources/template.xlsx +excel.template.path=template.xlsx -#sonar.url=http://127.0.0.1:9000 -sonar.url=http://117.50.14.123:9000 +sonar.url=http://127.0.0.1:9000 +#sonar.url=http://117.50.14.123:9000 +# token令牌 +sonar.token=0253a518e824a976ea2f11aec17938cb0f8c0495 -extract.path=/usr/bin/unar +extract.path=/usr/local/bin/unar +#extract.path=/usr/bin/unar last.run.id=0 diff --git a/src/main/resources/template.xlsx b/src/main/resources/template.xlsx index 9f613f6..960d14c 100644 Binary files a/src/main/resources/template.xlsx and b/src/main/resources/template.xlsx differ diff --git a/src/main/resources/template1.xlsx b/src/main/resources/template1.xlsx new file mode 100644 index 0000000..85e6407 Binary files /dev/null and b/src/main/resources/template1.xlsx differ diff --git a/src/test/java/net/educoder/ecsonar/EcsonarApplicationTests.java b/src/test/java/net/educoder/ecsonar/EcsonarApplicationTests.java index a510faf..7f7d5cd 100644 --- a/src/test/java/net/educoder/ecsonar/EcsonarApplicationTests.java +++ b/src/test/java/net/educoder/ecsonar/EcsonarApplicationTests.java @@ -43,12 +43,23 @@ public class EcsonarApplicationTests { } @Test - public void testReport() throws IOException { - Metrics hello = reportService.getMetrics("hello"); - reportService.writeToExcel("111111111", - "11", + public void testReport() throws Exception { + + String templatePath = this.getClass().getClassLoader().getResource("template1.xlsx").getPath(); + String outPath = "/Users/youyongsheng/Desktop/222.xlsx"; + Metrics hello = reportService.getMetrics("202017-201705820610-1"); + reportService.writeToExcel("201705820610", + "李金全", hello, - "/tmp/11.xlsx", + templatePath, + outPath, 1); } + + @Test + public void scanExcel(){ +// String excelPath = "/Users/youyongsheng/Desktop/res.xls"; + String excelPath = "/Users/youyongsheng/Desktop/res-test.xlsx"; + sonarService.scanExcel(excelPath); + } }