Search in sources :

Example 6 with Sheet

use of com.alibaba.excel.metadata.Sheet in project Qualitis by WeBankFinTech.

the class RuleMetricServiceImpl method upload.

@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { RuntimeException.class, UnExpectedRequestException.class })
public GeneralResponse<?> upload(InputStream fileInputStream, FormDataContentDisposition fileDisposition) throws UnExpectedRequestException, IOException {
    // Check Arguments
    if (fileInputStream == null || fileDisposition == null) {
        throw new UnExpectedRequestException("{&FILE_CAN_NOT_BE_NULL_OR_EMPTY}");
    }
    // Check suffix name of file
    String fileName = fileDisposition.getFileName();
    String suffixName = fileName.substring(fileName.lastIndexOf('.'));
    if (!suffixName.equals(SUPPORT_EXCEL_SUFFIX_NAME)) {
        throw new UnExpectedRequestException("{&DO_NOT_SUPPORT_SUFFIX_NAME}: [" + suffixName + "]. {&ONLY_SUPPORT} [" + SUPPORT_EXCEL_SUFFIX_NAME + "]");
    }
    String userName = HttpUtils.getUserName(httpServletRequest);
    LOGGER.info(userName + " start to upload rule metrics.");
    ExcelRuleMetricListener listener = new ExcelRuleMetricListener();
    List<ExcelRuleMetric> excelRuleMetrics = listener.getRuleMetricContent();
    ExcelReader excelReader = new ExcelReader(fileInputStream, null, listener);
    List<Sheet> sheets = excelReader.getSheets();
    for (Sheet sheet : sheets) {
        if (sheet.getSheetName().equals(ExcelSheetName.RULE_METRIC_NAME)) {
            sheet.setClazz(ExcelRuleMetric.class);
            sheet.setHeadLineMun(1);
            excelReader.read(sheet);
        }
    }
    if (CollectionUtils.isEmpty(excelRuleMetrics)) {
        throw new UnExpectedRequestException("{&FILE_CAN_NOT_BE_EMPTY_OR_FILE_CAN_NOT_BE_RECOGNIZED}");
    }
    try {
        for (ExcelRuleMetric excelRuleMetric : excelRuleMetrics) {
            AddRuleMetricRequest addRuleMetricRequest = new AddRuleMetricRequest();
            addRuleMetric(addRuleMetricRequest);
        }
        LOGGER.info("Succeed to add all rule metrics");
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    } finally {
        fileInputStream.close();
    }
    return new GeneralResponse<>("200", "{&FAILED_TO_UPLOAD_RULE_METRIC}", null);
}
Also used : ExcelRuleMetric(com.webank.wedatasphere.qualitis.project.excel.ExcelRuleMetric) ExcelReader(com.alibaba.excel.ExcelReader) GeneralResponse(com.webank.wedatasphere.qualitis.response.GeneralResponse) UnExpectedRequestException(com.webank.wedatasphere.qualitis.exception.UnExpectedRequestException) ExcelRuleMetricListener(com.webank.wedatasphere.qualitis.excel.ExcelRuleMetricListener) AddRuleMetricRequest(com.webank.wedatasphere.qualitis.request.AddRuleMetricRequest) Sheet(com.alibaba.excel.metadata.Sheet) PermissionDeniedRequestException(com.webank.wedatasphere.qualitis.exception.PermissionDeniedRequestException) UnExpectedRequestException(com.webank.wedatasphere.qualitis.exception.UnExpectedRequestException) IOException(java.io.IOException) WriteExcelException(com.webank.wedatasphere.qualitis.rule.exception.WriteExcelException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 7 with Sheet

use of com.alibaba.excel.metadata.Sheet in project Qualitis by WeBankFinTech.

the class ApplicationServiceImpl method writeExcelFile.

private void writeExcelFile(File tmpFile, List<String> tables, UploadResultRequest request) throws UnExpectedRequestException {
    int sheetNo = 1;
    OutputStream tmpOutputStream = null;
    try {
        Path parentPath = Paths.get(tmpFile.getParent());
        if (Files.notExists(parentPath)) {
            tmpFile.getParentFile().mkdirs();
        }
        if (!tmpFile.exists()) {
            LOGGER.info("Start to create local file.");
            tmpFile.createNewFile();
        }
        tmpOutputStream = new FileOutputStream(tmpFile);
        ExcelWriter writer = new ExcelWriter(tmpOutputStream, ExcelTypeEnum.XLSX, true);
        // Find task with the start time and end time.
        for (String tableName : tables) {
            List<Task> tasks = taskDao.findWithSubmitTimeAndDatasource(request.getStartTime(), request.getEndTime(), request.getClusterName(), request.getDatabaseName(), tableName);
            List<TaskRuleSimple> taskRuleSimples = tasks.stream().map(Task::getTaskRuleSimples).flatMap(taskRuleSimpleSet -> taskRuleSimpleSet.stream()).distinct().collect(Collectors.toList());
            // Generate analysis result excel
            List<ExcelResult> results = new ArrayList<>(taskRuleSimples.size());
            for (TaskRuleSimple taskRuleSimple : taskRuleSimples) {
                ExcelResult excelResult = new ExcelResult();
                excelResult.setRuleName(taskRuleSimple.getRuleName());
                excelResult.setClusterName(request.getClusterName());
                excelResult.setDatabaseName(request.getDatabaseName());
                excelResult.setTableName(tableName);
                excelResult.setBeginTime(taskRuleSimple.getTask().getBeginTime());
                excelResult.setEndTime(taskRuleSimple.getTask().getEndTime());
                StringBuffer checkTemplateStr = new StringBuffer();
                StringBuffer resultStr = new StringBuffer();
                joinAlarmConfig(results, taskRuleSimple, excelResult, request, checkTemplateStr, resultStr);
                results.add(excelResult);
            }
            Sheet templateSheet = new Sheet(sheetNo++, 0, ExcelResult.class);
            templateSheet.setSheetName(tableName + "-" + ExcelSheetName.ANALYSIS_NAME);
            writer.write(results, templateSheet);
        }
        writer.finish();
    } catch (FileNotFoundException e) {
        LOGGER.error(e.getMessage(), e);
        throw new UnExpectedRequestException("{&FAILED_TO_CREATE_LOCAL_FILE}");
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        throw new UnExpectedRequestException("{&FAILED_TO_CREATE_LOCAL_FILE}");
    } finally {
        try {
            tmpOutputStream.close();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
}
Also used : Path(java.nio.file.Path) UnExpectedRequestException(com.webank.wedatasphere.qualitis.exception.UnExpectedRequestException) Task(com.webank.wedatasphere.qualitis.entity.Task) ExcelResult(com.webank.wedatasphere.qualitis.excel.ExcelResult) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ExcelWriter(com.alibaba.excel.ExcelWriter) ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) FileOutputStream(java.io.FileOutputStream) TaskRuleSimple(com.webank.wedatasphere.qualitis.entity.TaskRuleSimple) Sheet(com.alibaba.excel.metadata.Sheet)

Example 8 with Sheet

use of com.alibaba.excel.metadata.Sheet in project notes by menhuan.

the class OnirigiFrontApp1liactionTest method test1.

@Test
public void test1() throws FileNotFoundException {
    OutputStream out = new FileOutputStream("F:/vscode/78.xlsx");
    try {
        ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
        // 写第一个sheet, sheet1  数据全是List<String> 无模型映射关系
        Sheet sheet1 = new Sheet(1, 0, CustomerMessage.class);
        writer.write(getData(), sheet1);
        writer.finish();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Also used : OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) ExcelWriter(com.alibaba.excel.ExcelWriter) IOException(java.io.IOException) Sheet(com.alibaba.excel.metadata.Sheet) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 9 with Sheet

use of com.alibaba.excel.metadata.Sheet in project SpringBoot-Hello by ruiyeclub.

the class ExcelUtil method writeExcel.

/**
 * @param outputStream  Excel的输出流
 * @param data          要写入的以 模型 为单位的数据
 * @param clazz         模型的类
 * @param excelTypeEnum Excel的格式(XLS或XLSX)
 * @Description: 使用模型来写入Excel,单sheet,单table
 * @Date: 2020/1/16 21:43
 * @Return: byte[]
 * @Throws: Exception
 */
public static void writeExcel(OutputStream outputStream, List<? extends BaseRowModel> data, Class<? extends BaseRowModel> clazz, ExcelTypeEnum excelTypeEnum) throws Exception {
    // 这里指定需要表头,因为model通常包含表头信息
    ExcelWriter writer = new ExcelWriter(outputStream, excelTypeEnum, true);
    // 写第一个sheet, sheet1  数据全是List<String> 无模型映射关系
    Sheet sheet1 = new Sheet(1, 0, clazz);
    writer.write(data, sheet1);
    writer.finish();
}
Also used : ExcelWriter(com.alibaba.excel.ExcelWriter) Sheet(com.alibaba.excel.metadata.Sheet)

Example 10 with Sheet

use of com.alibaba.excel.metadata.Sheet in project SpringBoot-Hello by ruiyeclub.

the class ExcelUtil method writeExcel.

/**
 * @param outputStream  Excel的输出流
 * @param sheetName     sheet名集合
 * @param datas         要写入的以 模型 为单位的数据
 * @param clazzs        模型的类
 * @param excelTypeEnum Excel的格式(XLS或XLSX)
 * @Description: 使用模型来写入Excel,多sheet,单table (返回字节数组)
 * @Date: 2020/1/16 21:43
 * @Return: byte[]
 * @Throws: Exception
 */
public static byte[] writeExcel(ByteArrayOutputStream outputStream, List<String> sheetName, List<List<? extends BaseRowModel>> datas, List<Class<? extends BaseRowModel>> clazzs, ExcelTypeEnum excelTypeEnum) throws Exception {
    // 这里指定需要表头,因为model通常包含表头信息
    ExcelWriter writer = new ExcelWriter(outputStream, excelTypeEnum, true);
    if (sheetName.size() != datas.size() || datas.size() != clazzs.size()) {
        throw new ArrayIndexOutOfBoundsException();
    }
    int i = 0;
    // 写第一个sheet, sheet1  数据全是List<String> 无模型映射关系
    for (String name : sheetName) {
        Sheet sheet1 = new Sheet(1, 0, clazzs.get(i));
        sheet1.setSheetName(name);
        writer.write(datas.get(i), sheet1);
    }
    writer.finish();
    return outputStream.toByteArray();
}
Also used : ExcelWriter(com.alibaba.excel.ExcelWriter) Sheet(com.alibaba.excel.metadata.Sheet)

Aggregations

Sheet (com.alibaba.excel.metadata.Sheet)18 ExcelWriter (com.alibaba.excel.ExcelWriter)13 IOException (java.io.IOException)8 ExcelReader (com.alibaba.excel.ExcelReader)5 UnExpectedRequestException (com.webank.wedatasphere.qualitis.exception.UnExpectedRequestException)5 PermissionDeniedRequestException (com.webank.wedatasphere.qualitis.exception.PermissionDeniedRequestException)4 WriteExcelException (com.webank.wedatasphere.qualitis.rule.exception.WriteExcelException)4 OutputStream (java.io.OutputStream)4 ArrayList (java.util.ArrayList)4 MyCoordinate (com.summit.coordinates.entity.MyCoordinate)3 ApiOperation (io.swagger.annotations.ApiOperation)2 FileNotFoundException (java.io.FileNotFoundException)2 FileOutputStream (java.io.FileOutputStream)2 List (java.util.List)2 GetMapping (org.springframework.web.bind.annotation.GetMapping)2 ModelExcelListener (cn.ruiyeclub.listener.ModelExcelListener)1 BaseRowModel (com.alibaba.excel.metadata.BaseRowModel)1 Table (com.alibaba.excel.metadata.Table)1 ExcelListener (com.summit.coordinates.config.ExcelListener)1 Task (com.webank.wedatasphere.qualitis.entity.Task)1