读取excel进行分析

test
youys 3 years ago
parent e4f358dccb
commit f24ed58662

@ -62,7 +62,7 @@
<dependency> <dependency>
<groupId>org.apache.poi</groupId> <groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId> <artifactId>poi-ooxml</artifactId>
<version>3.14</version> <version>3.16</version>
</dependency> </dependency>
<!-- 处理excel和上面功能是一样的--> <!-- 处理excel和上面功能是一样的-->
<dependency> <dependency>

@ -41,4 +41,11 @@ public class MainController {
} }
@PostMapping(value = "/scanExcel")
public String scanExcel(@RequestParam String excelPath) throws Exception {
ecsonarService.scanExcel(excelPath);
return "success";
}
} }

@ -519,4 +519,8 @@ public class EcsonarService {
} }
public void scanExcel(String excelPath){
sonarService.scanExcel(excelPath);
}
} }

@ -4,11 +4,13 @@ import net.educoder.ecsonar.dao.ProjectDao;
import net.educoder.ecsonar.model.Metrics; import net.educoder.ecsonar.model.Metrics;
import net.educoder.ecsonar.model.Project; import net.educoder.ecsonar.model.Project;
import net.educoder.ecsonar.utils.ExcelUtil; import net.educoder.ecsonar.utils.ExcelUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException; import java.io.IOException;
@Service @Service
@ -62,8 +64,10 @@ public class ReportService {
* @param metrics * @param metrics
*/ */
public void writeToExcel(String stuId, String name, public void writeToExcel(String stuId, String name,
Metrics metrics, String excelPath, int index) throws IOException { Metrics metrics, String templatePath, String outPath, int index) throws Exception {
// ExcelUtil.writeMetrics(metrics, stuId, name, excelPath, index); Workbook workbook = ExcelUtil.getWorkbok(new File(templatePath));
ExcelUtil.writeMetrics(metrics, stuId, name,workbook , index);
ExcelUtil.saveExcel(workbook,outPath);
} }
/** /**

@ -1,17 +1,31 @@
package net.educoder.ecsonar.services; 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.SystemUtil;
import net.educoder.ecsonar.utils.UrlUtil; import net.educoder.ecsonar.utils.UrlUtil;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.*; import java.io.*;
import java.net.URL; import java.net.URL;
import java.net.URLConnection; 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 @Service
public class SonarService { public class SonarService {
@ -22,9 +36,15 @@ public class SonarService {
@Value("${sonar.url}") @Value("${sonar.url}")
String sonarUrl; String sonarUrl;
@Value("${sonar.token}")
String sonarToken;
@Value("${extract.path}") @Value("${extract.path}")
String extractProgramPath; String extractProgramPath;
@Autowired
private ExecutorService executorService;
/** /**
* *
* *
@ -99,16 +119,18 @@ public class SonarService {
} }
private void sonar(String projectPath, String key) { public void sonar(String projectPath, String key) {
SystemUtil.executeAndGetExitStatus("sonar-scanner " + String command = "source ~/.bash_profile && sonar-scanner " +
"-Dsonar.host.url=" + sonarUrl + " " + "-Dsonar.host.url=" + sonarUrl + " " +
"-Dsonar.sourceEncoding=utf-8 " + "-Dsonar.sourceEncoding=utf-8 " +
"-Dsonar.projectKey=" + key + " " + "-Dsonar.projectKey=" + key + " " +
"-Dsonar.java.binaries=./ "+ "-Dsonar.login=" + sonarToken + " " +
"-Dsonar.projectBaseDir=" + projectPath); "-Dsonar.java.binaries=./ " +
"-Dsonar.projectBaseDir=" + projectPath;
log.info("projectPath:{},key:{}, command: {}", projectPath,key, command);
SystemUtil.executeAndGetExitStatus(command);
} }
/** /**
* zip * zip
* *
@ -134,7 +156,7 @@ public class SonarService {
private void download(String zipUrl, String zipPath) throws IOException { private void download(String zipUrl, String zipPath) throws IOException {
log.info("下载文件: {}-{}", zipUrl, zipPath); log.info("下载文件: {}-{}", zipUrl, zipPath);
String cookie = "3567ffee09b5dd08ee05967e23ebf0137a2eeaa9"; String cookie = "_educoder_session=1f4bf34409fec2180b99aa1cbf0b7586";
URL url = new URL(zipUrl); URL url = new URL(zipUrl);
URLConnection conn = url.openConnection(); URLConnection conn = url.openConnection();
conn.setRequestProperty("Cookie", cookie); conn.setRequestProperty("Cookie", cookie);
@ -153,4 +175,43 @@ public class SonarService {
} }
} }
/**
* excel
* @param excelPath
*/
public void scanExcel(String excelPath){
int homeworkId = 20210101;
try {
List<Person> personList = ExcelUtil.readExcel(excelPath);
Map<String, List<Person>> collect = personList.stream().collect(Collectors.groupingBy(Person::getUid));
List<Future> 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();
}
}
} }

@ -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;
}
}
}

@ -1,15 +1,14 @@
package net.educoder.ecsonar.utils; package net.educoder.ecsonar.utils;
import net.educoder.ecsonar.model.Metrics; import net.educoder.ecsonar.model.Metrics;
import net.educoder.ecsonar.model.api.Person;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.*;
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.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*; import java.io.*;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -36,7 +35,7 @@ public class ExcelUtil {
for (int i = 0; i < rowNumber + 1; ++i) { for (int i = 0; i < rowNumber + 1; ++i) {
Row row = sheet.getRow(3 + i); Row row = sheet.getRow(3 + i);
Cell cell = row.getCell(1); Cell cell = row.getCell(1);
cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellType(CellType.STRING);
if (StringUtils.equals(cell.getStringCellValue(), uid)) { if (StringUtils.equals(cell.getStringCellValue(), uid)) {
return true; return true;
} }
@ -71,12 +70,12 @@ public class ExcelUtil {
//从第三行开始 //从第三行开始
Row newRow = null; Row newRow = null;
for (int i = 0; i < rowNumber+1; ++i) { for (int i = 3; i < rowNumber+1; ++i) {
Row row = sheet.getRow(i); Row row = sheet.getRow(i);
if (row != null) { if (row != null) {
Cell cell = row.getCell(1); Cell cell = row.getCell(1);
cell.setCellType(Cell.CELL_TYPE_STRING); cell.setCellType(CellType.STRING);
if (StringUtils.isEmpty(cell.getStringCellValue()) if (StringUtils.isEmpty(cell.getStringCellValue())
|| StringUtils.equals(cell.getStringCellValue(), uid)) { || StringUtils.equals(cell.getStringCellValue(), uid)) {
@ -93,11 +92,11 @@ public class ExcelUtil {
//一直往下找,直到找到空的,或者与学号匹配的行,进行写入 //一直往下找,直到找到空的,或者与学号匹配的行,进行写入
//学号 //学号
Cell uidCell = newRow.createCell(1); Cell uidCell = newRow.createCell(1);
uidCell.setCellType(Cell.CELL_TYPE_STRING); uidCell.setCellType(CellType.STRING);
uidCell.setCellValue(uid); uidCell.setCellValue(uid);
Cell cell2 = newRow.createCell(2); Cell cell2 = newRow.createCell(2);
cell2.setCellType(Cell.CELL_TYPE_STRING); cell2.setCellType(CellType.STRING);
cell2.setCellValue(name); cell2.setCellValue(name);
int offset = 0; int offset = 0;
@ -105,75 +104,75 @@ public class ExcelUtil {
offset = 17; offset = 17;
} }
Cell cell3 = newRow.createCell(3 + offset); Cell cell3 = newRow.createCell(3 + offset);
cell3.setCellType(Cell.CELL_TYPE_NUMERIC); cell3.setCellType(CellType.NUMERIC);
cell3.setCellValue(metrics.getBlock_bugs()); cell3.setCellValue(metrics.getBlock_bugs());
Cell cell4 = newRow.createCell(4 + offset); Cell cell4 = newRow.createCell(4 + offset);
cell4.setCellType(Cell.CELL_TYPE_NUMERIC); cell4.setCellType(CellType.NUMERIC);
cell4.setCellValue(metrics.getCritical_bugs()); cell4.setCellValue(metrics.getCritical_bugs());
cell4 = newRow.createCell(5 + offset); cell4 = newRow.createCell(5 + offset);
cell4.setCellType(Cell.CELL_TYPE_NUMERIC); cell4.setCellType(CellType.NUMERIC);
cell4.setCellValue(metrics.getMajor_bugs()); cell4.setCellValue(metrics.getMajor_bugs());
cell4 = newRow.createCell(6 + offset); cell4 = newRow.createCell(6 + offset);
cell4.setCellType(Cell.CELL_TYPE_NUMERIC); cell4.setCellType(CellType.NUMERIC);
cell4.setCellValue(metrics.getMinor_bugs()); cell4.setCellValue(metrics.getMinor_bugs());
cell4 = newRow.createCell(7 + offset); cell4 = newRow.createCell(7 + offset);
cell4.setCellType(Cell.CELL_TYPE_STRING); cell4.setCellType(CellType.STRING);
cell4.setCellValue(metrics.getBugs()); cell4.setCellValue(metrics.getBugs());
cell4 = newRow.createCell(8 + offset); cell4 = newRow.createCell(8 + offset);
cell4.setCellType(Cell.CELL_TYPE_NUMERIC); cell4.setCellType(CellType.NUMERIC);
cell4.setCellValue(metrics.getBlock_violations()); cell4.setCellValue(metrics.getBlock_violations());
cell4 = newRow.createCell(9 + offset); cell4 = newRow.createCell(9 + offset);
cell4.setCellType(Cell.CELL_TYPE_NUMERIC); cell4.setCellType(CellType.NUMERIC);
cell4.setCellValue(metrics.getCritical_violations()); cell4.setCellValue(metrics.getCritical_violations());
cell4 = newRow.createCell(10 + offset); cell4 = newRow.createCell(10 + offset);
cell4.setCellType(Cell.CELL_TYPE_NUMERIC); cell4.setCellType(CellType.NUMERIC);
cell4.setCellValue(metrics.getMajor_violations()); cell4.setCellValue(metrics.getMajor_violations());
cell4 = newRow.createCell(11 + offset); cell4 = newRow.createCell(11 + offset);
cell4.setCellType(Cell.CELL_TYPE_NUMERIC); cell4.setCellType(CellType.NUMERIC);
cell4.setCellValue(metrics.getMinor_violations()); cell4.setCellValue(metrics.getMinor_violations());
cell4 = newRow.createCell(12 + offset); cell4 = newRow.createCell(12 + offset);
cell4.setCellType(Cell.CELL_TYPE_STRING); cell4.setCellType(CellType.STRING);
cell4.setCellValue(metrics.getViolations()); cell4.setCellValue(metrics.getViolations());
cell4 = newRow.createCell(13 + offset); cell4 = newRow.createCell(13 + offset);
cell4.setCellType(Cell.CELL_TYPE_NUMERIC); cell4.setCellType(CellType.NUMERIC);
cell4.setCellValue(metrics.getBlock_code_smells()); cell4.setCellValue(metrics.getBlock_code_smells());
cell4 = newRow.createCell(14 + offset); cell4 = newRow.createCell(14 + offset);
cell4.setCellType(Cell.CELL_TYPE_NUMERIC); cell4.setCellType(CellType.NUMERIC);
cell4.setCellValue(metrics.getCritical_code_smells()); cell4.setCellValue(metrics.getCritical_code_smells());
cell4 = newRow.createCell(15 + offset); cell4 = newRow.createCell(15 + offset);
cell4.setCellType(Cell.CELL_TYPE_NUMERIC); cell4.setCellType(CellType.NUMERIC);
cell4.setCellValue(metrics.getMajor_violations()); cell4.setCellValue(metrics.getMajor_violations());
cell4 = newRow.createCell(16 + offset); cell4 = newRow.createCell(16 + offset);
cell4.setCellType(Cell.CELL_TYPE_NUMERIC); cell4.setCellType(CellType.NUMERIC);
cell4.setCellValue(metrics.getMinor_code_smells()); cell4.setCellValue(metrics.getMinor_code_smells());
cell4 = newRow.createCell(17 + offset); cell4 = newRow.createCell(17 + offset);
cell4.setCellType(Cell.CELL_TYPE_STRING); cell4.setCellType(CellType.STRING);
cell4.setCellValue(metrics.getCode_smells()); cell4.setCellValue(metrics.getCode_smells());
cell4 = newRow.createCell(18 + offset); cell4 = newRow.createCell(18 + offset);
cell4.setCellType(Cell.CELL_TYPE_NUMERIC); cell4.setCellType(CellType.NUMERIC);
cell4.setCellValue(metrics.getComplexity()); cell4.setCellValue(metrics.getComplexity());
cell4 = newRow.createCell(19 + offset); cell4 = newRow.createCell(19 + offset);
cell4.setCellType(Cell.CELL_TYPE_NUMERIC); cell4.setCellType(CellType.NUMERIC);
cell4.setCellValue(metrics.getLines()); cell4.setCellValue(metrics.getLines());
@ -216,10 +215,35 @@ public class ExcelUtil {
return wb; return wb;
} }
/**
* excel
* @param excelPath
* @return
*/
public static List<Person> readExcel(String excelPath) throws IOException {
Workbook workbook = getWorkbok(new File(excelPath));
Sheet sheet = workbook.getSheetAt(0);
int lastRowNum = sheet.getLastRowNum();
// 去读Excel的方法readExcel该方法的入口参数为一个File对象 List<Person> personList = new ArrayList<>(lastRowNum+1);
public List readExcel(File file) {
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;
} }
} }

@ -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<String, Workbook> tempWorkbook = new HashMap<String, Workbook>();
//模板输入流map
private Map<String, FileInputStream> tempStream = new HashMap<String, FileInputStream>();
/**
* <p class="detail">
*
* </p>
*
* @author <a href="mailto:1435290472@qq.com">zq</a>
* @version V1.0
* @ClassName: Cell
* @date 2015926
*/
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;
}
}
/**
* <p class="detail">
* Excel
* </p>
*
* @param tempFilePath
* @param dataMap
* @param sheetNo
* @throws IOException
* @date 2015926
* @author <a href="mailto:1435290472@qq.com">zq</a>
*/
public void writeData(String tempFilePath, Map<String, Object> 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<String, Object> entry = (Map.Entry<String, Object>) it.next();
String point = entry.getKey();
Object data = entry.getValue();
TempCell cell = getCell(point, data, wsheet);
//指定坐标赋值
setCell(cell, wsheet);
}
//设置生成excel中公式自动计算
wsheet.setForceFormulaRecalculation(true);
}
/**
* <p class="detail">
* Excel
* </p>
*
* @param tempFilePath
* @param heads
* @param datalist
* @param sheetNo
* @throws FileNotFoundException
* @throws IOException
* @date 2015927
* @author <a href="mailto:1435290472@qq.com">zq</a>
*/
public void writeDateList(String tempFilePath, String[] heads, List<Map<Integer, Object>> datalist, int sheetNo) throws FileNotFoundException, IOException {
//读取模板
Workbook wbModule = getTempWorkbook(tempFilePath);
//数据填充的sheet
Sheet wsheet = wbModule.getSheetAt(sheetNo);
//列表数据模板cell
List<TempCell> tempCells = new ArrayList<TempCell>();
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<Integer, Object> 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);
}
}
}
/**
* <p class="detail">
*
* </p>
*
* @param tempFilePath
* @return
* @throws FileNotFoundException
* @throws IOException
* @date 2015926
* @author <a href="mailto:1435290472@qq.com">zq</a>
*/
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);
}
/**
* <p class="detail">
*
* </p>
*
* @param tempFilePath
* @return
* @throws FileNotFoundException
* @date 2015926
* @author <a href="mailto:1435290472@qq.com">zq</a>
*/
private FileInputStream getFileInputStream(String tempFilePath) throws FileNotFoundException {
if (!tempStream.containsKey(tempFilePath)) {
tempStream.put(tempFilePath, new FileInputStream(tempFilePath));
}
return tempStream.get(tempFilePath);
}
/**
* <p class="detail">
* , (B3)
* </p>
*
* @param point
* @param data
* @param sheet
* @return
* @date 2015927
* @author <a href="mailto:1435290472@qq.com">zq</a>
*/
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;
}
/**
* <p class="detail">
*
* </p>
*
* @param tempCell
* @param sheet
* @date 2015927
* @author <a href="mailto:1435290472@qq.com">zq</a>
*/
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());
}
}
/**
* <p class="detail">
*
* </p>
*
* @param tempFilePath
* @param os
* @throws FileNotFoundException
* @throws IOException
* @date 2015927
* @author <a href="mailto:1435290472@qq.com">zq</a>
*/
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);
}
}
/**
* <p class="detail">
*
* </p>
*
* @param sheet
* @param row
* @param column
* @return 0:i:
* @date 2015927
* @author <a href="mailto:1435290472@qq.com">zq</a>
*/
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;
}
/**
* <p class="detail">
*
* </p>
*
* @param sheet
* @param firstRow
* @param lastRow
* @param firstCol
* @param lastCol
* @date 2015927
* @author <a href="mailto:1435290472@qq.com">zq</a>
*/
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;
}
/**
* <p class="detail">
*
* </p>
*
* @param cs
* @param region
* @param sheet
* @date 2015927
* @author <a href="mailto:1435290472@qq.com">zq</a>
*/
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<String, Object> dataMap = new HashMap<String, Object>();
excel.writeData(tempFilePath, dataMap, 0);
List<Map<Integer, Object>> datalist = new ArrayList<Map<Integer, Object>>();
Map<Integer, Object> data = new HashMap<Integer, Object>();
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();
}
}

@ -1,7 +1,7 @@
#spring.datasource.url=jdbc:postgresql://127.0.0.1:5432/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.url=jdbc:postgresql://117.50.14.123:5432/sonar
spring.datasource.username=sonar spring.datasource.username=root
spring.datasource.password=sonar spring.datasource.password=root
spring.datasource.driver-class-name=org.postgresql.Driver 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.config=classpath:logback-spring.xml
logging.level.root=DEBUG logging.level.root=INFO
zip.save.path=/tmp/ zip.save.path=/tmp/
#excel.template.path=/Users/guange/work/java/ecsonar/src/main/resources/template.xlsx #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://127.0.0.1:9000
sonar.url=http://117.50.14.123: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 last.run.id=0

Binary file not shown.

Binary file not shown.

@ -43,12 +43,23 @@ public class EcsonarApplicationTests {
} }
@Test @Test
public void testReport() throws IOException { public void testReport() throws Exception {
Metrics hello = reportService.getMetrics("hello");
reportService.writeToExcel("111111111", String templatePath = this.getClass().getClassLoader().getResource("template1.xlsx").getPath();
"11", String outPath = "/Users/youyongsheng/Desktop/222.xlsx";
Metrics hello = reportService.getMetrics("202017-201705820610-1");
reportService.writeToExcel("201705820610",
"李金全",
hello, hello,
"/tmp/11.xlsx", templatePath,
outPath,
1); 1);
} }
@Test
public void scanExcel(){
// String excelPath = "/Users/youyongsheng/Desktop/res.xls";
String excelPath = "/Users/youyongsheng/Desktop/res-test.xlsx";
sonarService.scanExcel(excelPath);
}
} }

Loading…
Cancel
Save