初始代码

This commit is contained in:
wangmingwei
2026-04-21 17:22:24 +08:00
parent 1ebe0b6d7a
commit 41aa6607ef
222 changed files with 18009 additions and 0 deletions

76
.gitignore vendored Normal file
View File

@@ -0,0 +1,76 @@
# For Java
*.lck
target/
*.json
log/
logback-test.xml
# Compiled class file
*.class
# Log file
*.log
# BlueJ files
*.ctxt
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
# Image snapshot diff
__diff_output__/
/jest-stare
*.iml
.idea/
.ipr
.iws
*~
~*
*.diff
*.patch
*.bak
.DS_Store
Thumbs.db
.project
.*proj
.svn/
*.swp
*.swo
*.log
*.log.*
*.json.gzip
node_modules/
.buildpath
.settings
dist
npm-debug.log
nohup.out
_site
_data
report.html
/lib
/es
elasticsearch-*
config/base.yaml
/.vscode/
/coverage
/.history
*.tmp
!**/nacos/target
**/nacos/data/*
**/nacos/logs/*
**/seata/bin/*

0
README
View File

46
README.md Normal file
View File

@@ -0,0 +1,46 @@
> 特别说明源码、JDK、数据库、Redis等安装或存放路径禁止包含中文、空格、特殊字符等
## 一 环境要求
| 类目 | 版本说明或建议 |
| --- |------------------|
| 硬件 | 开发电脑建议使用I3及以上CPU16G及以上内存 |
| 操作系统 | Windows 10/11MacOS |
| JDK | 默认使用JDK 21如需要切换JDK 8/11/17版本请参考文档调整代码推荐使用 `OpenJDK`,如 `Liberica JDK``Eclipse Temurin``Alibaba Dragonwell``BiSheng`等发行版; |
| Maven | 依赖管理工具,推荐使用 `3.6.3` 及以上版本 |
| IDE | 代码集成开发环境,推荐使用 `IDEA2024` 及以上版本,兼容 `Eclipse``Spring Tool Suite` 等IDE工具 |
## 二 关联项目
> 为以下项目提供基础依赖
| 项目 | 分支 | 说明 |
|---------------|---------------|------------|
| yunzhupaas-common | v5.2.x-stable | 项目基础依赖源码 |
| yunzhupaas-java-datareport-univer | v5.2.x-stable | Univer报表源码 |
## 三 选择是否加密
> 是否加密将会影响 `yunzhupaas-java-datareport-univer` 项目的启动方式
> 如果此项目选择加密 `yunzhupaas-java-datareport-univer` 项目也需要选择加密
### 3.1 不使用加密
在IDEA中, 展开右侧 `Maven``Profiles` 去除勾选 `encrypted` 选项, 再点击Maven `刷新` 图标刷新 Maven
### 3.2 使用加密
在IDEA中, 展开右侧 `Maven``Profiles` 勾选 `encrypted` 选项, 再点击Maven `刷新` 图标刷新 Maven
#### 3.2.1 安装加密插件
在IDEA中双击右侧 `Maven``yunzhupaas-datareport-univer-core` > `clean` 将会自动安装加密打包插件
## 四 使用方式
### 4.1 本地安装
在IDEA中双击右侧 `Maven``yunzhupaas-datareport-univer-core` > `Lifecycle` > `install`,将 `yunzhupaas-datareport-univer-core` 包安装至本地
### 4.2 发布到私服
在IDEA中双击右侧 `Maven``yunzhupaas-datareport-univer-core` > `Lifecycle` > `deploy` 发布至私服。

36
allatori/allatori.xml Normal file
View File

@@ -0,0 +1,36 @@
<config>
<input>
<jar in="${project.build.finalName}.jar" out="${project.build.finalName}.jar"/>
</input>
<keep-names>
<class access="protected+">
<field access="protected+"/>
<method access="protected+"/>
</class>
</keep-names>
<ignore-classes>
<!-- 注意spring的框架相关的文件需要排除避免启动报错 -->
<class template="class com.yunzhupaas.properties.ReportProperties"/>
<class template="class com.yunzhupaas.univer.*"/>
</ignore-classes>
<!-- 混淆设置 -->
<!--随机类名保持小写-->
<property name="classes-naming" value="abc"/>
<!-- 接口形参名保持不变 -->
<property name="local-variables-naming" value="keep-parameters"/>
<!-- 字符串加密 -->
<property name="string-encryption" value="maximum"/>
<property name="string-encryption-type" value="strong"/>
<property name="string-encryption-version" value="v4"/>
<!-- 行数混淆 -->
<property name="line-numbers" value="obfuscate"/>
<!-- 成员重新排序 -->
<property name="member-reorder" value="enable"/>
<!-- 数据jar压缩等级 -->
<property name="output-jar-compression-level" value="9"/>
<property name="log-file" value="log.xml"/>
</config>

View File

@@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.idea-aedi</groupId>
<artifactId>class-winter-core</artifactId>
<version>enhance-2.9.4</version>
<dependencies>
<dependency>
<groupId>com.idea-aedi</groupId>
<artifactId>class-winter-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId>
<version>3.6.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-project</artifactId>
<version>2.2.1</version>
</dependency>
</dependencies>
</project>

114
pom.xml Normal file
View File

@@ -0,0 +1,114 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.yunzhupaas</groupId>
<artifactId>yunzhupaas-common</artifactId>
<version>5.2.0-RELEASE</version>
</parent>
<artifactId>yunzhupaas-datareport-univer-core</artifactId>
<version>5.2.0-RELEASE</version>
<packaging>pom</packaging>
<properties>
<maven-compiler-plugin.version>3.13.0</maven-compiler-plugin.version>
<maven-deploy-plugin.version>3.1.1</maven-deploy-plugin.version>
<maven-install-plugin.version>2.5.2</maven-install-plugin.version>
<maven-dependency-plugin.version>3.8.1</maven-dependency-plugin.version>
<maven-resources-plugin.version>2.6</maven-resources-plugin.version>
<exec-maven-plugin.version>1.2.1</exec-maven-plugin.version>
<class-winter-maven-plugin.version>enhance-2.9.4</class-winter-maven-plugin.version>
<poi.version>5.3.0</poi.version>
</properties>
<modules>
<module>yunzhupaas-datareport-univer-common</module>
<module>yunzhupaas-datareport-univer-model</module>
</modules>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>${maven-deploy-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>${maven-install-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>${maven-dependency-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>${maven-resources-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>${exec-maven-plugin.version}</version>
</plugin>
<plugin>
<groupId>com.idea-aedi</groupId>
<artifactId>class-winter-maven-plugin</artifactId>
<version>${class-winter-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<parameters>true</parameters>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
</plugin>
</plugins>
</build>
<!--私服仓库配置-->
<distributionManagement>
<repository>
<id>maven-releases</id>
<name>maven-releases</name>
<url>https://xadev.szlecheng.cn/nexus/repository/maven-public/</url>
</repository>
</distributionManagement>
</project>

View File

@@ -0,0 +1,57 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.yunzhupaas</groupId>
<artifactId>yunzhupaas-datareport-univer-core</artifactId>
<version>5.2.0-RELEASE</version>
</parent>
<artifactId>yunzhupaas-datareport-univer-common</artifactId>
<dependencies>
<dependency>
<groupId>com.yunzhupaas</groupId>
<artifactId>yunzhupaas-common-database</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.yunzhupaas</groupId>
<artifactId>yunzhupaas-common-swagger</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.yunzhupaas</groupId>
<artifactId>yunzhupaas-common-file</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-full</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>com.yunzhupaas</groupId>
<artifactId>yunzhupaas-datareport-univer-model</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
<profiles>
</profiles>
</project>

View File

@@ -0,0 +1,12 @@
package com.yunzhupaas.consts;
public class ApiConst {
public static String ME;
public static String DATASET_LIST;
public static String DATASET_SAVE;
public static String DATASET_DATA;
public static String SAVE_MENU;
public static String GET_MENU;
public static String PARAMETER_DATA;
}

View File

@@ -0,0 +1,208 @@
package com.yunzhupaas.exception;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.exception.SameTokenInvalidException;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.ActionResultCode;
import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author 云筑产品开发平台组
* @version V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/3/16 10:10
*/
@Slf4j
@Controller
@ControllerAdvice
public class ResultException extends BasicErrorController {
@Autowired
private ConfigValueUtil configValueUtil;
public ResultException() {
super(new DefaultErrorAttributes(), new ErrorProperties());
}
@ResponseBody
@ExceptionHandler(value = LoginException.class)
public ActionResult<Object> loginException(LoginException e) {
ActionResult<Object> result = ActionResult.fail(ActionResultCode.Fail.getCode(), e.getMessage());
result.setData(e.getData());
return result;
}
@ResponseBody
@ExceptionHandler(value = ImportException.class)
public ActionResult<Object> loginException(ImportException e) {
ActionResult<Object> result = ActionResult.fail(ActionResultCode.Fail.getCode(), e.getMessage());
return result;
}
/**
* 自定义异常内容返回
*
* @param e
* @return
*/
@ResponseBody
@ExceptionHandler(value = DataException.class)
public ActionResult<Object> dataException(DataException e) {
ActionResult<Object> result = ActionResult.fail(ActionResultCode.Fail.getCode(), e.getMessage());
return result;
}
/**
* 租户数据库异常
*
* @param e
* @return
*/
@ResponseBody
@ExceptionHandler(value = TenantDatabaseException.class)
public ActionResult<String> tenantDatabaseException(TenantDatabaseException e) {
String msg;
if (e.getMessage() == null) {
if (configValueUtil.getMultiTenancyUrl().contains("https")) {
// https 官网提示
msg = MsgCode.LOG109.get();
} else {
msg = MsgCode.LOG110.get();
}
} else {
msg = e.getMessage();
}
return ActionResult.fail(ActionResultCode.Fail.getCode(), msg);
}
@ResponseBody
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ActionResult<Object> methodArgumentNotValidException(MethodArgumentNotValidException e) {
Map<String, String> map = new HashMap<>(16);
List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
for (int i = 0; i < allErrors.size(); i++) {
String s = allErrors.get(i).getCodes()[0];
// 用分割的方法得到字段名
String[] parts = s.split("\\.");
String part1 = parts[parts.length - 1];
map.put(part1, allErrors.get(i).getDefaultMessage());
}
String json = JSON.toJSONString(map);
ActionResult<Object> result = ActionResult.fail(ActionResultCode.ValidateError.getCode(), json);
return result;
}
@ResponseBody
@ExceptionHandler(value = WorkFlowException.class)
public ActionResult<Object> workFlowException(WorkFlowException e) {
if (e.getCode() == 200) {
List<Map<String, Object>> list = JsonUtil.getJsonToListMap(e.getMessage());
return ActionResult.success(list);
} else {
return ActionResult.fail(e.getMessage());
}
}
@ResponseBody
@ExceptionHandler(value = WxErrorException.class)
public ActionResult<Object> wxErrorException(WxErrorException e) {
return ActionResult.fail(e.getError().getErrorCode(), MsgCode.AD103.get());
}
@ResponseBody
@ExceptionHandler(value = ServletException.class)
public void exception(ServletException e) throws Exception {
log.error("系统异常:" + e.getMessage(), e);
throw new Exception();
}
@ResponseBody
@ExceptionHandler(value = Exception.class)
public ActionResult<Object> exception(Exception e) {
log.error("系统异常:" + e.getMessage(), e);
if (e instanceof ConnectDatabaseException || e.getCause() instanceof ConnectDatabaseException) {
Throwable t = e;
if (e.getCause() instanceof ConnectDatabaseException) {
t = e.getCause();
}
return ActionResult.fail(ActionResultCode.Fail.getCode(), t.getMessage());
}
return ActionResult.fail(ActionResultCode.Fail.getCode(), MsgCode.AD102.get());
}
/**
* 权限码异常
*/
@ResponseBody
@ExceptionHandler(NotPermissionException.class)
public ActionResult<Void> handleNotPermissionException(NotPermissionException e) {
return ActionResult.fail(ActionResultCode.Fail.getCode(), MsgCode.AD104.get());
}
/**
* 角色权限异常
*/
@ResponseBody
@ExceptionHandler(NotRoleException.class)
public ActionResult<Void> handleNotRoleException(NotRoleException e) {
return ActionResult.fail(ActionResultCode.ValidateError.getCode(), MsgCode.AD104.get());
}
/**
* 认证失败
*/
@ResponseBody
@ExceptionHandler(NotLoginException.class)
public ActionResult<Void> handleNotLoginException(NotLoginException e) {
return ActionResult.fail(ActionResultCode.SessionOverdue.getCode(), MsgCode.AD105.get());
}
/**
* 无效认证
*/
@ResponseBody
@ExceptionHandler(SameTokenInvalidException.class)
public ActionResult<Void> handleIdTokenInvalidException(SameTokenInvalidException e) {
return ActionResult.fail(ActionResultCode.SessionOverdue.getCode(), MsgCode.AD106.get());
}
/**
* 覆盖默认的 JSON 响应
*/
@Override
@RequestMapping
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
HttpStatus status = getStatus(request);
if (status == HttpStatus.NOT_FOUND) {
return new ResponseEntity<>(status);
}
return super.error(request);
}
}

View File

@@ -0,0 +1,7 @@
package com.yunzhupaas.properties;
public class ReportProperties {
public static final String PREFIX = "report";
}

View File

@@ -0,0 +1,215 @@
package com.yunzhupaas.util;
import com.yunzhupaas.univer.chart.UniverChartField;
import com.yunzhupaas.univer.chart.UniverChartModel;
import com.yunzhupaas.univer.data.cell.UniverDataConfig;
import com.yunzhupaas.ureport.definition.value.AggregateType;
import com.yunzhupaas.ureport.definition.value.DatasetValue;
import com.yunzhupaas.ureport.utils.DataUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/9/10 下午3:18
*/
public class ChartUtil {
public static void chart(List<UniverChartModel> chartList, Map<String, List<Map<String, Object>>> dataListAll,
List<UniverDataConfig> echartsList) {
for (UniverDataConfig model : echartsList) {
UniverChartModel chartModel = new UniverChartModel();
chartModel.setDrawingId(model.getDrawingId());
chartModel.setSubUnitId(model.getSubUnitId());
chartModel.setUnitId(model.getUnitId());
UniverDataConfig config = model.getOption() != null ? model.getOption() : new UniverDataConfig();
// 数据
Set<String> datasetName = new HashSet<>();
String classifyNameField = config.getClassifyNameField();
config.setClassifyNameField(fieldName(classifyNameField, datasetName));
String seriesNameField = config.getSeriesNameField();
config.setSeriesNameField(fieldName(seriesNameField, datasetName));
String seriesDataField = config.getSeriesDataField();
config.setSeriesDataField(fieldName(seriesDataField, datasetName));
String maxField = config.getMaxField();
config.setMaxField(fieldName(maxField, datasetName));
List<Map<String, Object>> dataList = new ArrayList<>();
for (String dataName : datasetName) {
List<Map<String, Object>> data = dataListAll.get(dataName) != null ? dataListAll.get(dataName)
: new ArrayList<>();
dataList.addAll(data);
}
UniverChartField chartField = chart(dataList, config);
chartModel.setField(chartField);
chartList.add(chartModel);
}
}
private static UniverChartField chart(List<Map<String, Object>> dataList, UniverDataConfig dataConfig) {
String classifyName = dataConfig.getClassifyNameField();
String seriesName = dataConfig.getSeriesNameField();
String seriesData = dataConfig.getSeriesDataField();
String maxField = dataConfig.getMaxField();
Map<Object, Map<Object, List<Object>>> chartDataMap = new HashMap<>();
Map<Object, List<Object>> maxDatMap = new HashMap<>();
for (int i = 0; i < dataList.size(); i++) {
Map<String, Object> data = dataList.get(i);
Object classify = data.get(classifyName);
if (classify == null) {
continue;
}
Object value = data.get(seriesData);
if (value == null) {
continue;
}
Object series = data.get(seriesName) != null ? data.get(seriesName) : "";
Map<Object, List<Object>> categoryMap = chartDataMap.get(series) != null ? chartDataMap.get(series)
: new HashMap<>();
List<Object> valueList = categoryMap.get(classify) != null ? categoryMap.get(classify) : new ArrayList<>();
valueList.add(value);
categoryMap.put(classify, valueList);
chartDataMap.put(series, categoryMap);
Object max = data.get(maxField);
if (max != null) {
List<Object> maxData = maxDatMap.get(classify) != null ? maxDatMap.get(classify) : new ArrayList<>();
maxData.add(max);
maxDatMap.put(classify, maxData);
}
}
return chartData(chartDataMap, maxDatMap, dataConfig);
}
private static UniverChartField chartData(Map<Object, Map<Object, List<Object>>> seriesDataMap,
Map<Object, List<Object>> maxDataMap, UniverDataConfig dataConfig) {
UniverChartField chartField = new UniverChartField();
List<String> seriesNameList = new ArrayList<>();
Map<Object, List<List<String>>> classifyMap = new HashMap<>();
List<Integer> maxCount = new ArrayList<>();
maxCount.add(0);
for (Object series : seriesDataMap.keySet()) {
seriesNameList.add(String.valueOf(series));
Map<Object, List<Object>> classifyNameMap = seriesDataMap.get(series);
for (Object classify : classifyNameMap.keySet()) {
List<List<String>> categroyList = new ArrayList<>();
if (classifyMap.get(classify) != null) {
categroyList.addAll(classifyMap.get(classify));
}
List<Object> valueList = classifyNameMap.get(classify);
List<String> data = data(valueList, dataConfig);
for (int i = 0; i < data.size(); i++) {
List<String> classifyData = new ArrayList<>();
classifyData.add(data.get(i));
categroyList.add(classifyData);
}
classifyMap.put(classify, categroyList);
maxCount.add(categroyList.size());
}
}
if (StringUtil.isNotEmpty(dataConfig.getSeriesNameField())) {
chartField.setSeriesNameField(seriesNameList);
}
List<String> maxFieldList = new ArrayList<>();
List<String> classifyNameList = new ArrayList<>();
for (Object classify : classifyMap.keySet()) {
classifyNameList.add(String.valueOf(classify));
List<Object> objects = maxDataMap.get(classify) != null ? maxDataMap.get(classify) : new ArrayList<>();
if (objects.isEmpty()) {
objects.add(new BigDecimal(0));
}
dataConfig.setSummaryType(AggregateType.max.name());
List<String> data = data(objects, dataConfig);
maxFieldList.add(data.get(0));
}
List<List<String>> seriesDataList = new ArrayList<>();
for (int i = 0; i < Collections.max(maxCount); i++) {
List<String> seriesData = new ArrayList<>();
for (int k = 0; k < classifyNameList.size(); k++) {
String category = classifyNameList.get(k);
List<List<String>> categoryList = classifyMap.get(category) != null ? classifyMap.get(category)
: new ArrayList<>();
List<String> categoryData = categoryList.size() - 1 >= i ? categoryList.get(i) : new ArrayList<>();
String data = categoryData.size() > 0 ? categoryData.get(0) : "";
seriesData.add(data);
}
seriesDataList.add(seriesData);
}
chartField.setClassifyNameField(classifyNameList);
chartField.setSeriesDataField(seriesDataList);
if (StringUtil.isNotEmpty(dataConfig.getMaxField())) {
chartField.setMaxField(maxFieldList);
}
return chartField;
}
private static List<String> data(List<Object> list, UniverDataConfig dataConfig) {
List<String> result = new ArrayList<>();
if (list.isEmpty()) {
return result;
}
String chartType = AggregateType.value(dataConfig.getSummaryType()) != null ? dataConfig.getSummaryType()
: AggregateType.select.name();
DatasetValue expr = new DatasetValue();
expr.setProperty(chartType);
AggregateType value = AggregateType.value(chartType);
List<Map<String, Object>> dataList = new ArrayList<>();
for (Object data : list) {
Map<String, Object> dataMap = new HashMap<>();
dataMap.put(chartType, data);
dataList.add(dataMap);
}
List<BigDecimal> bindDataList = DataUtils.dataList(expr, dataList);
switch (value) {
case sum:
result.add(bindDataList.stream().reduce(BigDecimal.ZERO, BigDecimal::add).doubleValue() + "");
break;
case avg:
BigDecimal sumDecimal = bindDataList.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
if (bindDataList.isEmpty()) {
bindDataList.add(new BigDecimal(0));
}
result.add(sumDecimal.divide(new BigDecimal(bindDataList.size()), 8, RoundingMode.HALF_UP)
.doubleValue() + "");
break;
case max:
if (bindDataList.isEmpty()) {
bindDataList.add(new BigDecimal(0));
}
result.add(bindDataList.stream().reduce(bindDataList.get(0), BigDecimal::max).doubleValue() + "");
break;
case min:
if (bindDataList.isEmpty()) {
bindDataList.add(new BigDecimal(0));
}
result.add(bindDataList.stream().reduce(bindDataList.get(0), BigDecimal::min).doubleValue() + "");
break;
case count:
result.add(list.size() + "");
break;
default:
for (Object data : list) {
result.add(String.valueOf(data));
}
break;
}
return result;
}
private static String fieldName(String field, Set<String> datasetName) {
String fieldName = field;
if (StringUtil.isNotEmpty(fieldName)) {
String[] params = fieldName.split("\\.");
datasetName.add(params[0]);
fieldName = params.length == 2 ? params[1] : fieldName;
}
return fieldName;
}
}

View File

@@ -0,0 +1,96 @@
package com.yunzhupaas.util;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.consts.ApiConst;
import com.yunzhupaas.database.util.TenantDataSourceUtil;
import com.yunzhupaas.model.login.MeInfoVO;
import com.yunzhupaas.model.tenant.TenantVO;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
import java.util.Objects;
/**
* 报表工具类
*/
@Slf4j
public class ReportUtil {
public static UserInfo initUserInfo(String token) {
UserInfo userInfo = UserProvider.getLocalLoginUser();
if (userInfo == null) {
try {
HttpResponse response = HttpRequest.get(ApiConst.ME).header(Constants.AUTHORIZATION, token).execute();
if (response.isOk()) {
String result = response.body();
try {
ActionResult<MeInfoVO> out = JSONUtil.toBean(result,
new TypeReference<ActionResult<MeInfoVO>>() {
}, false);
if (Objects.equals(out.getCode(), Constants.SUCCESS)) {
MeInfoVO meInfoVO = out.getData();
if (StringUtil.isNotEmpty(meInfoVO.getUserId())) {
// 构造用户信息
String tenantId = meInfoVO.getTenantId();
userInfo = new UserInfo();
userInfo.setId(meInfoVO.getUserId());
userInfo.setUserId(meInfoVO.getUserId());
userInfo.setUserName(meInfoVO.getUserName());
userInfo.setUserAccount(meInfoVO.getUserAccount());
userInfo.setTenantId(tenantId);
UserProvider.setLocalLoginUser(userInfo);
// 设置租户信息
if (TenantDataSourceUtil.isMultiTenancy()) {
// 直接从租户系统获取租户信息
TenantVO tenantVO = TenantDataSourceUtil.getRemoteTenantInfo(tenantId);
TenantDataSourceUtil.switchTenant(tenantId, tenantVO);
userInfo.setTenantDbType(tenantVO.getType());
// tenantDbConnectionString 已废弃,不再设置
}
return userInfo;
}
if (log.isDebugEnabled()) {
log.debug("获取用户信息: {}", result);
}
} else {
log.error("主系统未成功返回用户信息: {}", out);
}
} catch (Exception e) {
log.error("用户信息解析失败:" + result, e);
}
}
} catch (Exception e) {
log.error("获取用户信息错误: {}", e.getMessage());
}
}
return userInfo;
}
public static String http(String url, Method method, Map<String, Object> params) {
HttpRequest request = HttpRequest.of(url).method(method);
switch (method) {
case GET:
request.form(params);
break;
default:
request.body(JsonUtil.getObjectToString(params));
break;
}
request.header(Constants.AUTHORIZATION, UserProvider.getToken());
request.setConnectionTimeout(50000);
request.setReadTimeout(60000);
String json = "{}";
try {
json = request.execute().body();
} catch (Exception e) {
log.error(e.getMessage());
}
return json;
}
}

View File

@@ -0,0 +1,949 @@
package com.yunzhupaas.util;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.Method;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.enums.*;
import com.yunzhupaas.exception.DataException;
import com.yunzhupaas.univer.chart.UniverChartModel;
import com.yunzhupaas.univer.data.resource.*;
import com.yunzhupaas.univer.model.UniverWorkBook;
import com.yunzhupaas.univer.properties.UniverProperties;
import com.yunzhupaas.univer.resources.UniverResource;
import com.yunzhupaas.univer.resources.UniverResourceData;
import com.yunzhupaas.univer.sheet.*;
import com.yunzhupaas.univer.style.UniverStyle;
import com.yunzhupaas.univer.style.UniverStyleBorder;
import com.yunzhupaas.univer.style.UniverStyleTextDecoration;
import com.yunzhupaas.univer.style.UniverStyleTextRotation;
import com.yunzhupaas.util.excel.ExcelParser;
import com.yunzhupaas.util.excel.UniverHSSFExcel;
import com.yunzhupaas.util.excel.UniverXSSFExcel;
import com.yunzhupaas.util.type.RequestType;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
import org.springframework.web.multipart.MultipartFile;
import java.awt.Color;
import java.io.IOException;
import java.util.List;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/9/29 下午5:17
*/
@Slf4j
public class UniverExcel {
private static Map<String, ExcelParser> excelMap = ImmutableMap.of(
"xlsx", new UniverXSSFExcel(),
"xls", new UniverHSSFExcel());
public static UniverWorkBook formFile(MultipartFile file) throws IOException {
// todo 推荐使用 xlsx 方法
@SuppressWarnings("null")
String fileName = file.getOriginalFilename();
if (fileName == null) {
throw new DataException("文件名不能为空");
}
String type = Files.getFileExtension(fileName);
ExcelParser excelParser = excelMap.get(type);
if (excelParser == null) {
throw new DataException(MsgCode.ETD110.get());
}
UniverWorkBook univerWorkBook = excelParser.formFile(file.getInputStream());
return univerWorkBook;
}
public static void downExcel(String snapshot, List<UniverChartModel> chartList, XSSFWorkbook workbook,
List<String> sheetList) {
Map<UniverStyle, XSSFCellStyle> styleMap = new HashMap<>();
UniverWorkBook univerWorkBook = JsonUtil.getJsonToBean(snapshot, UniverWorkBook.class);
List<UniverResource> resources = univerWorkBook.getResources() != null ? univerWorkBook.getResources()
: new ArrayList<>();
for (String sheetOrder : univerWorkBook.getSheetOrder()) {
UniverSheet univerSheet = univerWorkBook.getSheets().get(sheetOrder);
if (ObjectUtil.isNotEmpty(univerSheet)) {
if (!sheetList.contains(sheetOrder)) {
continue;
}
XSSFSheet sheet = workbook.createSheet(univerSheet.getName());
workbook.setSheetHidden(workbook.getSheetIndex(sheet), Objects.equals(univerSheet.getHidden(), 1));
Map<Integer, UniverSheetRowData> rowData = univerSheet.getRowData();
Map<Integer, UniverSheetColumnData> colData = univerSheet.getColumnData();
XSSFDrawing drawing = sheet.createDrawingPatriarch();
// 冻结位置
UniverSheetFreeze freeze = univerSheet.getFreeze() != null ? univerSheet.getFreeze()
: new UniverSheetFreeze();
sheet.createFreezePane(freeze.getStartColumn(), freeze.getStartRow());
// 遍历数据
univerSheet.getCellData().forEach((rowKey, sheetRow) -> {
XSSFRow row = sheet.createRow(rowKey);
UniverSheetRowData sheetRowData = rowData.get(rowKey);
if (ObjectUtil.isNotEmpty(sheetRowData)) {
row.setZeroHeight(Objects.equals(sheetRowData.getHd(), 1));
if (ObjectUtil.isNotEmpty(sheetRowData.getH())) {
row.setHeightInPoints(sheetRowData.getH());
}
}
sheetRow.forEach((colKey, sheetCol) -> {
UniverSheetRange range = univerSheet.getMergeData().stream()
.filter(t -> Objects.equals(t.getStartRow(), rowKey)
&& Objects.equals(t.getStartColumn(), colKey))
.findFirst().orElse(null);
Object value = sheetCol.getV();
Object formula = sheetCol.getF();
Object style = sheetCol.getS();
XSSFCell cell = row.createCell(colKey);
UniverSheetColumnData columnData = colData.get(colKey);
if (ObjectUtil.isNotEmpty(columnData)) {
if (ObjectUtil.isNotEmpty(columnData.getW())) {
sheet.setColumnWidth(colKey, (short) (columnData.getW() * 1.33 * 35));
}
sheet.setColumnHidden(colKey, Objects.equals(columnData.getHd(), 1));
}
if (ObjectUtil.isNotEmpty(sheetCol.getP())) {
UniverProperties properties = JsonUtil.getJsonToBean(sheetCol.getP(),
UniverProperties.class);
if (properties.getBody() != null) {
cell.setCellType(CellType.STRING);
cell.setCellValue(properties.getBody().getDataStream());
}
}
if (ObjectUtil.isNotEmpty(value) && ObjectUtil.isEmpty(formula)) {
if (Objects.equals(sheetCol.getT(), 2)) {
cell.setCellType(CellType.NUMERIC);
cell.setCellValue(Double.valueOf(value.toString()));
} else if (Objects.equals(sheetCol.getT(), 3)) {
cell.setCellType(CellType.BOOLEAN);
cell.setCellValue(Boolean.valueOf(value.toString()));
} else {
cell.setCellType(CellType.STRING);
cell.setCellValue(value.toString());
}
}
if (ObjectUtil.isNotEmpty(formula)) {
try {
cell.setCellFormula(formula.toString().substring(1));
} catch (Exception e) {
cell.setCellType(CellType.STRING);
cell.setCellValue(formula.toString());
}
}
if (ObjectUtil.isNotEmpty(style)) {
UniverStyle basicStyle = univerWorkBook.getStyles().get(style);
if (ObjectUtil.isNotEmpty(basicStyle)) {
UniverStyleBorder bd = basicStyle.getBd();
if (ObjectUtil.isNotEmpty(styleMap.get(basicStyle))) {
bdAnchor(bd, rowKey, colKey, range, drawing);
cell.setCellStyle(styleMap.get(basicStyle));
} else {
XSSFCellStyle cellStyle = workbook.createCellStyle();
if (ObjectUtil.isNotEmpty(basicStyle.getBg())
&& ObjectUtil.isNotEmpty(basicStyle.getBg().getRgb())) {
String bgGrb = basicStyle.getBg().getRgb();
XSSFColor color = color(bgGrb);
if (color != null) {
cellStyle.setFillForegroundColor(color);
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
}
}
if (ObjectUtil.isNotEmpty(bd)) {
if (ObjectUtil.isNotEmpty(bd.getT())
&& ObjectUtil.isNotEmpty(bd.getT().getCl())) {
String bdt = bd.getT().getCl().getRgb();
if (ObjectUtil.isNotEmpty(bdt)) {
XSSFColor color = color(bdt);
if (color != null) {
cellStyle.setTopBorderColor(color);
}
}
StyleTypeEnum bdStyle = StyleTypeEnum.getStyle(bd.getT().getS());
if (ObjectUtil.isNotEmpty(bdStyle)) {
cellStyle.setBorderTop(bdStyle.getBorderStyle());
}
}
if (ObjectUtil.isNotEmpty(bd.getL())
&& ObjectUtil.isNotEmpty(bd.getL().getCl())) {
String bdl = bd.getL().getCl().getRgb();
if (ObjectUtil.isNotEmpty(bdl)) {
XSSFColor color = color(bdl);
if (color != null) {
cellStyle.setLeftBorderColor(color);
}
}
StyleTypeEnum bdStyle = StyleTypeEnum.getStyle(bd.getL().getS());
if (ObjectUtil.isNotEmpty(bdStyle)) {
cellStyle.setBorderLeft(bdStyle.getBorderStyle());
}
}
if (ObjectUtil.isNotEmpty(bd.getB())
&& ObjectUtil.isNotEmpty(bd.getB().getCl())) {
String bdb = bd.getB().getCl().getRgb();
if (ObjectUtil.isNotEmpty(bdb)) {
XSSFColor color = color(bdb);
if (color != null) {
cellStyle.setBottomBorderColor(color);
}
}
StyleTypeEnum bdStyle = StyleTypeEnum.getStyle(bd.getB().getS());
if (ObjectUtil.isNotEmpty(bdStyle)) {
cellStyle.setBorderBottom(bdStyle.getBorderStyle());
}
}
if (ObjectUtil.isNotEmpty(bd.getR())
&& ObjectUtil.isNotEmpty(bd.getR().getCl())) {
String bdr = bd.getR().getCl().getRgb();
if (ObjectUtil.isNotEmpty(bdr)) {
XSSFColor color = color(bdr);
if (color != null) {
cellStyle.setRightBorderColor(color);
}
}
StyleTypeEnum bdStyle = StyleTypeEnum.getStyle(bd.getR().getS());
if (ObjectUtil.isNotEmpty(bdStyle)) {
cellStyle.setBorderRight(bdStyle.getBorderStyle());
}
}
bdAnchor(bd, rowKey, colKey, range, drawing);
}
HorizontalAlignment alignment = ObjectUtil.isNotEmpty(basicStyle.getHt())
? HorizontalEnum.getHorizontalValue(basicStyle.getHt())
: null;
if (ObjectUtil.isNotEmpty(alignment)) {
cellStyle.setAlignment(alignment);
}
VerticalAlignment verticalValue = ObjectUtil.isNotEmpty(basicStyle.getVt())
? VerticalEnum.getVerticalValue(basicStyle.getVt())
: null;
if (ObjectUtil.isNotEmpty(verticalValue)) {
cellStyle.setVerticalAlignment(verticalValue);
}
if (ObjectUtil.isNotEmpty(basicStyle.getN())
&& ObjectUtil.isNotEmpty(basicStyle.getN().getPattern())) {
DataFormat format = workbook.createDataFormat();
cellStyle.setDataFormat(format.getFormat(basicStyle.getN().getPattern()));
}
if (ObjectUtil.isNotEmpty(basicStyle.getTb())
&& Objects.equals(basicStyle.getTb(), 3)) {
cellStyle.setWrapText(true);
}
if (ObjectUtil.isNotEmpty(basicStyle.getTr())) {
UniverStyleTextRotation tr = basicStyle.getTr();
int v = tr.getV();
int rotation = tr.getA();
if (Objects.equals(v, 1)) {
rotation = -255;
}
cellStyle.setRotation((short) -rotation);
}
XSSFFont font = workbook.createFont();
if (ObjectUtil.isNotEmpty(basicStyle.getFf())) {
font.setFontName(basicStyle.getFf());
}
if (ObjectUtil.isNotEmpty(basicStyle.getFs())) {
font.setFontHeight(basicStyle.getFs());
}
if (ObjectUtil.isNotEmpty(basicStyle.getIt())) {
font.setItalic(Objects.equals(basicStyle.getIt(), 1));
}
if (ObjectUtil.isNotEmpty(basicStyle.getBl())) {
font.setBold(Objects.equals(basicStyle.getBl(), 1));
}
if (ObjectUtil.isNotEmpty(basicStyle.getCl())
&& ObjectUtil.isNotEmpty(basicStyle.getCl().getRgb())) {
XSSFColor color = color(basicStyle.getCl().getRgb());
if (color != null) {
font.setColor(color);
}
}
if (ObjectUtil.isNotEmpty(basicStyle.getUl())
&& ObjectUtil.isNotEmpty(basicStyle.getUl().getS())) {
font.setUnderline(Objects.equals(basicStyle.getUl().getS(), 1) ? Font.U_SINGLE
: Font.U_NONE);
}
if (ObjectUtil.isNotEmpty(basicStyle.getSt())
&& ObjectUtil.isNotEmpty(basicStyle.getSt().getS())) {
font.setStrikeout(Objects.equals(basicStyle.getSt().getS(), 1));
}
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);
styleMap.put(basicStyle, cellStyle);
}
}
}
});
});
// 合并单元格
for (UniverSheetRange region : new HashSet<>(univerSheet.getMergeData())) {
sheet.addMergedRegion(new CellRangeAddress(region.getStartRow(), region.getEndRow(),
region.getStartColumn(), region.getEndColumn()));
}
// 图片
drawing(sheetOrder, resources, chartList, drawing, workbook);
// 条件
format(sheetOrder, resources, sheet);
// 数据管理
dataValidation(sheetOrder, resources, sheet);
// 筛选
filter(sheetOrder, resources, sheet);
}
}
}
private static void bdAnchor(UniverStyleBorder bd, int rowKey, int colKey, UniverSheetRange range,
XSSFDrawing drawing) {
if (ObjectUtil.isNotEmpty(bd)) {
if (ObjectUtil.isNotEmpty(bd.getTl_br()) && ObjectUtil.isNotEmpty(bd.getTl_br().getCl())) {
int startRow = rowKey;
int startCol = colKey;
int endRow = rowKey + 1;
int endCol = colKey + 1;
if (range != null) {
endRow = range.getEndRow() + 1;
endCol = range.getEndColumn() + 1;
}
XSSFClientAnchor anchor = new XSSFClientAnchor();
anchor.setRow1(startRow);
anchor.setCol1(startCol);
anchor.setRow2(endRow);
anchor.setCol2(endCol);
XSSFSimpleShape shape = drawing.createSimpleShape(anchor);
StyleTypeEnum bdStyle = StyleTypeEnum.getStyle(bd.getTl_br().getS());
if (ObjectUtil.isNotEmpty(bdStyle)) {
shape.setShapeType(bdStyle.getBorderStyle().getCode());
}
String bdr = bd.getTl_br().getCl().getRgb();
if (ObjectUtil.isNotEmpty(bdr)) {
XSSFColor color = color(bdr);
if (color != null) {
shape.setLineStyleColor(color.getRGB()[0], color.getRGB()[1], color.getRGB()[2]);
}
}
shape.setShapeType(ShapeTypes.LINE);
}
if (ObjectUtil.isNotEmpty(bd.getTl_mr()) && ObjectUtil.isNotEmpty(bd.getTl_mr().getCl())) {
if (range != null) {
int startRow = rowKey;
int startCol = colKey;
int endRow = (rowKey + range.getEndRow() + 1) / 2;
int endCol = range.getEndColumn() + 1;
XSSFClientAnchor anchor = new XSSFClientAnchor();
anchor.setRow1(startRow);
anchor.setCol1(startCol);
anchor.setRow2(endRow);
anchor.setCol2(endCol);
XSSFSimpleShape shape = drawing.createSimpleShape(anchor);
StyleTypeEnum bdStyle = StyleTypeEnum.getStyle(bd.getTl_mr().getS());
if (ObjectUtil.isNotEmpty(bdStyle)) {
shape.setShapeType(bdStyle.getBorderStyle().getCode());
}
String bdr = bd.getTl_mr().getCl().getRgb();
if (ObjectUtil.isNotEmpty(bdr)) {
XSSFColor color = color(bdr);
if (color != null) {
shape.setLineStyleColor(color.getRGB()[0], color.getRGB()[1], color.getRGB()[2]);
}
}
shape.setShapeType(ShapeTypes.LINE);
}
}
if (ObjectUtil.isNotEmpty(bd.getTl_bc()) && ObjectUtil.isNotEmpty(bd.getTl_bc().getCl())) {
if (range != null) {
int startRow = rowKey;
int startCol = colKey;
int endRow = range.getEndRow() + 1;
int endCol = (colKey + range.getEndColumn() + 1) / 2;
XSSFClientAnchor anchor = new XSSFClientAnchor();
anchor.setRow1(startRow);
anchor.setCol1(startCol);
anchor.setRow2(endRow);
anchor.setCol2(endCol);
XSSFSimpleShape shape = drawing.createSimpleShape(anchor);
StyleTypeEnum bdStyle = StyleTypeEnum.getStyle(bd.getTl_bc().getS());
if (ObjectUtil.isNotEmpty(bdStyle)) {
shape.setShapeType(bdStyle.getBorderStyle().getCode());
}
String bdr = bd.getTl_bc().getCl().getRgb();
if (ObjectUtil.isNotEmpty(bdr)) {
XSSFColor color = color(bdr);
if (color != null) {
shape.setLineStyleColor(color.getRGB()[0], color.getRGB()[1], color.getRGB()[2]);
}
}
shape.setShapeType(ShapeTypes.LINE);
}
}
if (ObjectUtil.isNotEmpty(bd.getBl_tr()) && ObjectUtil.isNotEmpty(bd.getBl_tr().getCl())) {
int startRow = rowKey;
int startCol = colKey;
int endRow = rowKey + 1;
int endCol = colKey + 1;
if (range != null) {
endRow = range.getEndRow() + 1;
endCol = range.getEndColumn() + 1;
}
XSSFClientAnchor anchor = new XSSFClientAnchor();
anchor.setRow1(startRow);
anchor.setCol1(startCol);
anchor.setRow2(endRow);
anchor.setCol2(endCol);
XSSFSimpleShape shape = drawing.createSimpleShape(anchor);
StyleTypeEnum bdStyle = StyleTypeEnum.getStyle(bd.getBl_tr().getS());
if (ObjectUtil.isNotEmpty(bdStyle)) {
shape.setShapeType(bdStyle.getBorderStyle().getCode());
}
String bdr = bd.getBl_tr().getCl().getRgb();
if (ObjectUtil.isNotEmpty(bdr)) {
XSSFColor color = color(bdr);
if (color != null) {
shape.setLineStyleColor(color.getRGB()[0], color.getRGB()[1], color.getRGB()[2]);
}
}
shape.setShapeType(ShapeTypes.LINE_INV);
}
if (ObjectUtil.isNotEmpty(bd.getBc_tr()) && ObjectUtil.isNotEmpty(bd.getBc_tr().getCl())) {
if (range != null) {
int startRow = rowKey;
int startCol = range.getStartColumn();
int endRow = (rowKey + range.getEndRow() + 1) / 2;
int endCol = range.getEndColumn() + 1;
XSSFClientAnchor anchor = new XSSFClientAnchor();
anchor.setRow1(startRow);
anchor.setCol1(startCol);
anchor.setRow2(endRow);
anchor.setCol2(endCol);
XSSFSimpleShape shape = drawing.createSimpleShape(anchor);
StyleTypeEnum bdStyle = StyleTypeEnum.getStyle(bd.getBc_tr().getS());
if (ObjectUtil.isNotEmpty(bdStyle)) {
shape.setShapeType(bdStyle.getBorderStyle().getCode());
}
String bdr = bd.getBc_tr().getCl().getRgb();
if (ObjectUtil.isNotEmpty(bdr)) {
XSSFColor color = color(bdr);
if (color != null) {
shape.setLineStyleColor(color.getRGB()[0], color.getRGB()[1], color.getRGB()[2]);
}
}
shape.setShapeType(ShapeTypes.LINE_INV);
}
}
if (ObjectUtil.isNotEmpty(bd.getMl_tr()) && ObjectUtil.isNotEmpty(bd.getMl_tr().getCl())) {
if (range != null) {
int startRow = rowKey;
int startCol = (colKey + range.getEndColumn() + 1) / 2;
int endRow = range.getEndRow() + 1;
int endCol = range.getEndColumn() + 1;
XSSFClientAnchor anchor = new XSSFClientAnchor();
anchor.setRow1(startRow);
anchor.setCol1(startCol);
anchor.setRow2(endRow);
anchor.setCol2(endCol);
XSSFSimpleShape shape = drawing.createSimpleShape(anchor);
StyleTypeEnum bdStyle = StyleTypeEnum.getStyle(bd.getMl_tr().getS());
if (ObjectUtil.isNotEmpty(bdStyle)) {
shape.setShapeType(bdStyle.getBorderStyle().getCode());
}
String bdr = bd.getMl_tr().getCl().getRgb();
if (ObjectUtil.isNotEmpty(bdr)) {
XSSFColor color = color(bdr);
if (color != null) {
shape.setLineStyleColor(color.getRGB()[0], color.getRGB()[1], color.getRGB()[2]);
}
}
shape.setShapeType(ShapeTypes.LINE_INV);
}
}
}
}
private static XSSFColor color(String rgbCole) {
byte[] rgb = null;
try {
Color color = new Color(Integer.parseInt(rgbCole.substring(1), 16));
rgb = new byte[] { (byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue() };
} catch (Exception e) {
try {
rgbCole = rgbCole.replaceAll("rgb\\(", "").replaceAll("\\)", "");
String[] split = rgbCole.split(",");
if (split.length >= 3) {
int red = Integer.parseInt(split[0]);
int green = Integer.parseInt(split[1]);
int blue = Integer.parseInt(split[2]);
rgb = new byte[] { (byte) red, (byte) green, (byte) blue };
}
} catch (Exception e1) {
}
}
XSSFColor xssfColor = rgb == null ? null : new XSSFColor(rgb, new DefaultIndexedColorMap());
return xssfColor;
}
private static void drawing(String sheetOrder, List<UniverResource> resources, List<UniverChartModel> chartList,
XSSFDrawing drawing, XSSFWorkbook workbook) {
UniverResource univerResource = resources.stream()
.filter(t -> ResourceEnum.SHEET_DRAWING_PLUGIN.name().equals(t.getName())).findFirst().orElse(null);
Map<String, UniverResourceData> drawingMap = new HashMap<>();
if (ObjectUtil.isNotEmpty(univerResource) && ObjectUtil.isNotEmpty(univerResource.getData())) {
Map<String, Object> data = JsonUtil.stringToMap(univerResource.getData());
data.forEach((key, value) -> {
drawingMap.put(key, JsonUtil.getJsonToBean(value, UniverResourceData.class));
});
}
// 导出图片
UniverResourceData resourceData = drawingMap.get(sheetOrder);
if (ObjectUtil.isNotEmpty(resourceData)) {
List<String> orderList = resourceData.getOrder();
Map<String, UniverDrawing> data = resourceData.getData();
for (String order : orderList) {
try {
UniverDrawing univerDrawing = data.get(order);
if (ObjectUtil.isNotEmpty(univerDrawing)) {
String source = univerDrawing.getSource();
String imageType = univerDrawing.getImageSourceType();
byte[] bytes = null;
if (Objects.equals(ImageEnum.BASE64.name(), imageType)) {
String regex = "data:image/\\w+;base64,";
String base64Img = source;
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(source);
if (matcher.find()) {
base64Img = source.replace(matcher.group(), "");
}
bytes = Base64.decode(base64Img);
} else {
if (source.startsWith(RequestType.HTTP)) {
HttpRequest request = HttpRequest.of(source).method(Method.GET);
bytes = request.execute().bodyBytes();
} else {
String[] split = source.split("=");
String fileNameAll = DesUtil.aesDecode(split[split.length - 1]);
String[] fileData = fileNameAll.split("#");
String fileName = fileData.length > 1 ? fileData[1] : "";
String type = fileData.length > 2 ? fileData[2] : "";
String typePath = FilePathUtil.getFilePath(type.toLowerCase());
bytes = FileUploadUtils.downloadFileByte(typePath, fileName, false);
}
}
if (bytes != null && bytes.length > 0) {
UniverTransform sheetTransform = univerDrawing.getSheetTransform();
UniverOffset from = sheetTransform.getFrom();
UniverOffset to = sheetTransform.getTo();
// 图片导出
XSSFClientAnchor anchor = new XSSFClientAnchor();
anchor.setRow1(from.getRow());
anchor.setCol1(from.getColumn());
anchor.setRow2(to.getRow());
anchor.setCol2(to.getColumn());
anchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_DO_RESIZE);
int imageIndex = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
drawing.createPicture(anchor, imageIndex);
}
}
} catch (Exception e) {
log.error("图片导出失败:{}", e.getMessage());
}
}
}
}
private static void format(String sheetOrder, List<UniverResource> resources, XSSFSheet sheet) {
StylesTable styles = sheet.getWorkbook().getStylesSource();
UniverResource univerResource = resources.stream()
.filter(t -> ResourceEnum.SHEET_CONDITIONAL_FORMATTING_PLUGIN.name().equals(t.getName())).findFirst()
.orElse(null);
Map<String, List<UniverResourceData>> foramtMap = new HashMap<>();
if (ObjectUtil.isNotEmpty(univerResource) && ObjectUtil.isNotEmpty(univerResource.getData())) {
Map<String, Object> data = JsonUtil.stringToMap(univerResource.getData());
data.forEach((key, value) -> {
foramtMap.put(key, JsonUtil.getJsonToList(value, UniverResourceData.class));
});
}
List<UniverResourceData> data = foramtMap.get(sheetOrder) != null ? foramtMap.get(sheetOrder)
: new ArrayList<>();
CTWorksheet ctWorksheet = sheet.getCTWorksheet();
List<CTConditionalFormatting> conditionalList = new ArrayList<>();
for (UniverResourceData resourceData : data) {
UniverRule rule = resourceData.getRule();
Boolean stopIfTrue = resourceData.getStopIfTrue();
List<UniverSheetRange> ranges = resourceData.getRanges();
if (ObjectUtil.isNotEmpty(rule)) {
List<CTCfRule> ruleList = new ArrayList<>();
List<UniverConfig> configList = new ArrayList<>();
Object ruleConfig = rule.getConfig();
if (ObjectUtil.isNotEmpty(ruleConfig)) {
if (ruleConfig instanceof List) {
configList.addAll(JsonUtil.getJsonToList(ruleConfig, UniverConfig.class));
} else if (ruleConfig instanceof Map) {
configList.add(JsonUtil.getJsonToBean(ruleConfig, UniverConfig.class));
}
}
List<String> regions = new ArrayList<>();
for (UniverSheetRange range : ranges) {
regions.add(new CellRangeAddress(range.getStartRow(), range.getEndRow(), range.getStartColumn(),
range.getEndColumn()).formatAsString());
}
String type = rule.getType();
String subType = rule.getSubType();
Boolean showValue = rule.getIsShowValue();
String operator = rule.getOperator();
FormatTypeEnum formatTypeEnum = FormatTypeEnum.getFormat(type);
CTCfRule cfRule = CTCfRule.Factory.newInstance();
cfRule.setStopIfTrue(stopIfTrue);
STCfType.Enum typeEnum = STCfType.Enum.forString(type);
cfRule.setType(typeEnum);
switch (formatTypeEnum) {
case colorScale:
CTColorScale scale = cfRule.addNewColorScale();
for (UniverConfig univerConfig : configList) {
UniverValue univerValue = univerConfig.getValue();
if (univerValue == null) {
continue;
}
String valueType = univerValue.getType();
String value = univerValue.getValue() != null ? univerValue.getValue().toString() : "";
if (Objects.equals(SubTypeEnum.expression.getCode(), valueType)) {
value = value.replace("=", "");
}
CTCfvo ctCfvo = scale.addNewCfvo();
ctCfvo.setType(STCfvoType.Enum.forString(valueType));
ctCfvo.setVal(value);
XSSFColor color = color(univerConfig.getColor());
if (color != null) {
CTColor ctColor = scale.addNewColor();
ctColor.setRgb(color.getRGB());
}
}
ruleList.add(cfRule);
break;
case iconSet:
CTIconSet icons = cfRule.addNewIconSet();
icons.setShowValue(showValue);
for (int i = configList.size() - 1; i >= 0; i--) {
UniverConfig univerConfig = configList.get(i);
UniverValue value = univerConfig.getValue();
if (value == null) {
continue;
}
String iconType = value.getType();
String icon = univerConfig.getIconType();
String valueOperator = univerConfig.getOperator();
String iconValue = value.getValue() != null ? value.getValue().toString() : "";
if (Objects.equals(SubTypeEnum.expression.getCode(), iconType)) {
iconValue = iconValue.replace("=", "");
}
CTCfvo ctCfvo = icons.addNewCfvo();
ctCfvo.setVal(iconValue);
ctCfvo.setGte(Objects.equals(valueOperator, OperatorEnum.greaterThanOrEqual.name()));
ctCfvo.setType(STCfvoType.Enum.forString(iconType));
icons.setIconSet(STIconSetType.Enum.forString(icon));
}
boolean reverse = configList.size() > 0 && !Objects.equals(configList.get(0).getIconId(), "0");
icons.setReverse(reverse);
ruleList.add(cfRule);
break;
case dataBar:
CTDataBar bar = cfRule.addNewDataBar();
bar.setShowValue(showValue);
for (UniverConfig config : configList) {
UniverValue min = config.getMin();
UniverValue max = config.getMax();
if (min != null && max != null) {
String minType = min.getType();
String minValue = min.getValue() != null ? min.getValue().toString() : "";
if (Objects.equals(SubTypeEnum.expression.getCode(), minType)) {
minValue = minValue.replace("=", "");
}
String maxType = max.getType();
String maxValue = max.getValue() != null ? max.getValue().toString() : "";
if (Objects.equals(SubTypeEnum.expression.getCode(), maxType)) {
maxValue = maxValue.replace("=", "");
}
List<String> dataBarType = Lists.newArrayList(OperatorEnum.min.name(),
OperatorEnum.max.name());
for (int i = 0; i < dataBarType.size(); i++) {
String barType = i == 0 ? minType : maxType;
String barValue = i == 0 ? minValue : maxValue;
CTCfvo ctCfvo = bar.addNewCfvo();
ctCfvo.setType(STCfvoType.Enum.forString(barType));
ctCfvo.setVal(barValue);
XSSFColor positiveColor = color(config.getPositiveColor());
if (positiveColor != null) {
CTColor ctColor = bar.addNewColor();
ctColor.setRgb(positiveColor.getRGB());
}
XSSFColor nativeColor = color(config.getNativeColor());
if (nativeColor != null) {
CTColor ctColor = bar.addNewColor();
ctColor.setRgb(nativeColor.getRGB());
}
}
}
}
ruleList.add(cfRule);
break;
default:
List<String> cell = Lists.newArrayList(SubTypeEnum.cellIs.getCode(),
SubTypeEnum.equal.getCode(),
SubTypeEnum.notEqual.getCode());
boolean isNumber = cell.contains(subType) || cell.contains(operator);
// 平均值
boolean isAverage = Objects.equals(SubTypeEnum.aboveAverage.getCode(), subType);
// TOP
boolean isRank = Objects.equals(SubTypeEnum.top10.getCode(), subType);
// 公式
boolean isFormula = Objects.equals(SubTypeEnum.expression.getCode(), subType);
// 日期
boolean isTime = Objects.equals(SubTypeEnum.timePeriod.getCode(), subType);
String ruleType = operator;
if (isNumber) {
ruleType = SubTypeEnum.cellIs.getType();
} else if (isAverage) {
ruleType = SubTypeEnum.aboveAverage.getType();
} else if (isRank) {
ruleType = SubTypeEnum.top10.getType();
} else if (isFormula) {
ruleType = SubTypeEnum.expression.getType();
} else if (isTime) {
ruleType = SubTypeEnum.timePeriod.getType();
}
if (StringUtil.isEmpty(ruleType)) {
ruleType = subType;
}
Object value = rule.getValue();
String data1 = null;
String data2 = null;
String text = null;
Long rank = null;
Boolean bottom = null;
Boolean percent = null;
if (value != null) {
if (isNumber) {
if (value instanceof List) {
@SuppressWarnings("unchecked")
List<Object> valueList = (List<Object>) value;
for (int i = 0; i < valueList.size(); i++) {
Object numberValu = valueList.get(i);
if (numberValu != null) {
if (i == 0) {
data1 = valueList.get(i).toString();
} else {
data2 = valueList.get(i).toString();
}
}
}
} else {
data1 = value.toString();
}
} else if (isRank) {
rank = Long.valueOf(value.toString());
bottom = rule.getIsBottom();
percent = rule.getIsPercent();
} else if (isFormula) {
data1 = value.toString().replace("=", "");
} else {
text = value.toString();
}
}
cfRule.setType(STCfType.Enum.forString(ruleType));
if (data1 != null) {
cfRule.addFormula(data1);
}
if (data2 != null) {
cfRule.addFormula(data2);
}
if (operator != null) {
STConditionalFormattingOperator.Enum anOperator = STConditionalFormattingOperator.Enum
.forString(operator);
if (anOperator != null) {
cfRule.setOperator(anOperator);
}
STTimePeriod.Enum timePeriod = STTimePeriod.Enum.forString(operator);
if (timePeriod != null) {
cfRule.setTimePeriod(timePeriod);
}
}
if (text != null) {
cfRule.setText(text);
}
if (rank != null) {
cfRule.setRank(rank);
}
if (bottom != null) {
cfRule.setBottom(bottom);
}
if (percent != null) {
cfRule.setPercent(percent);
}
if (isAverage) {
cfRule.setAboveAverage(Objects.equals(OperatorEnum.greaterThan.name(), operator));
}
UniverStyle style = rule.getStyle();
if (style != null) {
CTDxf ctDxf = CTDxf.Factory.newInstance();
XSSFColor bgColor = color(style.getBg().getRgb() != null ? style.getBg().getRgb() : "");
if (bgColor != null) {
CTFill ctFill = CTFill.Factory.newInstance();
CTPatternFill patternFill = CTPatternFill.Factory.newInstance();
patternFill.setBgColor(bgColor.getCTColor());
ctFill.setPatternFill(patternFill);
ctDxf.setFill(ctFill);
}
CTFont ctFont = CTFont.Factory.newInstance();
XSSFColor fontColor = color(style.getCl().getRgb() != null ? style.getCl().getRgb() : "");
if (fontColor != null) {
CTColor ctColor = fontColor.getCTColor();
ctFont.setColorArray(new CTColor[] { ctColor });
}
CTUnderlineProperty underline = CTUnderlineProperty.Factory.newInstance();
underline.setVal(style.getUl() != null && Objects.equals(style.getUl().getS(), 1)
? STUnderlineValues.SINGLE
: STUnderlineValues.NONE);
ctFont.setUArray(new CTUnderlineProperty[] { underline });
CTBooleanProperty italic = CTBooleanProperty.Factory.newInstance();
italic.setVal(Objects.equals(style.getIt(), 1));
ctFont.setIArray(new CTBooleanProperty[] { italic });
CTBooleanProperty bold = CTBooleanProperty.Factory.newInstance();
bold.setVal(Objects.equals(style.getBl(), 1));
ctFont.setBArray(new CTBooleanProperty[] { bold });
UniverStyleTextDecoration st = style.getSt();
CTBooleanProperty strike = CTBooleanProperty.Factory.newInstance();
strike.setVal(st != null && Objects.equals(st.getS(), 1));
ctFont.setStrikeArray(new CTBooleanProperty[] { strike });
ctDxf.setFont(ctFont);
int dxfId = styles.putDxf(ctDxf);
cfRule.setDxfId(dxfId - 1);
}
ruleList.add(cfRule);
break;
}
CTConditionalFormatting conditionalFormatting = ctWorksheet.addNewConditionalFormatting();
conditionalFormatting.setCfRuleArray(ruleList.toArray(new CTCfRule[ruleList.size()]));
conditionalFormatting.setSqref(regions);
conditionalList.add(conditionalFormatting);
}
}
ctWorksheet.setConditionalFormattingArray(
conditionalList.toArray(new CTConditionalFormatting[conditionalList.size()]));
}
private static void dataValidation(String sheetOrder, List<UniverResource> resources, XSSFSheet sheet) {
UniverResource univerResource = resources.stream()
.filter(t -> ResourceEnum.SHEET_DATA_VALIDATION_PLUGIN.name().equals(t.getName())).findFirst()
.orElse(null);
Map<String, List<UniverResourceData>> dataValidationMap = new HashMap<>();
if (ObjectUtil.isNotEmpty(univerResource) && ObjectUtil.isNotEmpty(univerResource.getData())) {
Map<String, Object> data = JsonUtil.stringToMap(univerResource.getData());
data.forEach((key, value) -> {
dataValidationMap.put(key, JsonUtil.getJsonToList(value, UniverResourceData.class));
});
}
XSSFDataValidationHelper dataValidation = new XSSFDataValidationHelper(sheet);
List<UniverResourceData> data = dataValidationMap.get(sheetOrder) != null ? dataValidationMap.get(sheetOrder)
: new ArrayList<>();
for (UniverResourceData resourceData : data) {
CellRangeAddressList addressList = new CellRangeAddressList();
for (UniverSheetRange range : resourceData.getRanges()) {
addressList.addCellRangeAddress(new CellRangeAddress(range.getStartRow(), range.getEndRow(),
range.getStartColumn(), range.getEndColumn()));
}
String formula1 = resourceData.getFormula1() != null ? resourceData.getFormula1() : "";
String formula2 = resourceData.getFormula2() != null ? resourceData.getFormula2() : "";
ValidationType validationType = ValidationType.getValidationType(resourceData.getType());
String value1 = Objects.equals(validationType, ValidationType.checkbox) ? formula1 + "," + formula2
: formula1;
String value2 = formula2;
operatorTypeEnum operator = operatorTypeEnum.getOperator(resourceData.getOperator());
XSSFDataValidationConstraint constraint = new XSSFDataValidationConstraint(
validationType.getValidationType(), operator.getOperator(), value1, value2);
constraint.setExplicitListValues(value1.split(","));
DataValidation validation = dataValidation.createValidation(constraint, addressList);
validation.setErrorStyle(resourceData.getErrorStyle() != null ? 0 : 1);
validation.setEmptyCellAllowed(resourceData.getAllowBlank() != null ? resourceData.getAllowBlank() : true);
if (resourceData.getError() != null) {
validation.createErrorBox(resourceData.getError(), "");
}
if (resourceData.getRenderMode() != null) {
validation.setSuppressDropDownArrow(!Objects.equals(resourceData.getRenderMode(), 0));
}
validation.setShowErrorBox(
resourceData.getShowErrorMessage() != null ? resourceData.getShowErrorMessage() : false);
sheet.addValidationData(validation);
}
}
private static void filter(String sheetOrder, List<UniverResource> resources, XSSFSheet sheet) {
UniverResource univerResource = resources.stream()
.filter(t -> ResourceEnum.SHEET_FILTER_PLUGIN.name().equals(t.getName())).findFirst().orElse(null);
Map<String, UniverResourceData> filterMap = new HashMap<>();
if (ObjectUtil.isNotEmpty(univerResource) && ObjectUtil.isNotEmpty(univerResource.getData())) {
Map<String, Object> data = JsonUtil.stringToMap(univerResource.getData());
data.forEach((key, value) -> {
filterMap.put(key, JsonUtil.getJsonToBean(value, UniverResourceData.class));
});
}
UniverResourceData data = filterMap.get(sheetOrder) != null ? filterMap.get(sheetOrder)
: new UniverResourceData();
UniverSheetRange ref = data.getRef();
if (ref != null) {
sheet.setAutoFilter(
new CellRangeAddress(ref.getStartRow(), ref.getEndRow(), ref.getStartColumn(), ref.getEndColumn()));
List<CTFilterColumn> filterColumns = new ArrayList<>();
CTAutoFilter autoFilter = sheet.getCTWorksheet().getAutoFilter();
for (UniverFilters filters : data.getFilterColumns()) {
Long colId = filters.getColId();
UniverCustomFilters customFilters = filters.getCustomFilters();
// poi方法
CTFilterColumn column = autoFilter.addNewFilterColumn();
column.setColId(colId);
CTCustomFilters ctCustomFilters = column.addNewCustomFilters();
ctCustomFilters.setAnd(Objects.equals(customFilters.getAnd(), 1));
for (UniverCustomFilters customFilter : customFilters.getCustomFilters()) {
CTCustomFilter ctCustomFilter = ctCustomFilters.addNewCustomFilter();
String val = customFilter.getVal();
if (val != null) {
ctCustomFilter.setVal(val);
}
String operator = customFilter.getOperator();
if (operator != null) {
ctCustomFilter.setOperator(STFilterOperator.Enum.forString(operator));
}
}
filterColumns.add(column);
}
// 筛选隐藏
List<Integer> cachedFilteredOut = data.getCachedFilteredOut();
for (Integer rowIndex : cachedFilteredOut) {
XSSFRow row = sheet.getRow(rowIndex);
row.setZeroHeight(true);
}
autoFilter.setFilterColumnArray(filterColumns.toArray(new CTFilterColumn[filterColumns.size()]));
}
}
}

View File

@@ -0,0 +1,16 @@
package com.yunzhupaas.util.excel;
import com.yunzhupaas.univer.model.UniverWorkBook;
import java.io.IOException;
import java.io.InputStream;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/9/30 下午3:10
*/
public abstract class ExcelParser {
public abstract UniverWorkBook formFile(InputStream inputStream) throws IOException;
}

View File

@@ -0,0 +1,597 @@
package com.yunzhupaas.util.excel;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.ImmutableList;
import com.yunzhupaas.enums.*;
import com.yunzhupaas.univer.data.resource.*;
import com.yunzhupaas.univer.model.UniverWorkBook;
import com.yunzhupaas.univer.resources.UniverResource;
import com.yunzhupaas.univer.resources.UniverResourceData;
import com.yunzhupaas.univer.sheet.*;
import com.yunzhupaas.univer.style.*;
import org.apache.poi.hssf.model.HSSFFormulaParser;
import org.apache.poi.hssf.model.InternalWorkbook;
import org.apache.poi.hssf.record.NameRecord;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.formula.ptg.Ptg;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.ss.util.PaneInformation;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/6/20 下午4:30
*/
public class UniverHSSFExcel extends ExcelParser {
@Override
public UniverWorkBook formFile(InputStream inputStream) throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
UniverWorkBook univerWorkBook = new UniverWorkBook();
String unitId = RandomUtil.randomString(10);
univerWorkBook.setId(unitId);
univerWorkBook.setName("");
Map<UniverStyle, String> styleMap = new HashMap<>();
Map<String, UniverSheet> sheets = new HashMap<>();
List<String> sheetOrder = new ArrayList<>();
Map<String, UniverResourceData> drawingMap = new HashMap<>();
Map<String, List<UniverResourceData>> formattingMap = new HashMap<>();
Map<String, List<UniverResourceData>> dataValidationMap = new HashMap<>();
Map<String, UniverResourceData> filterMap = new HashMap<>();
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
String sheetId = RandomUtil.randomString(10);
sheetOrder.add(sheetId);
HSSFSheet sheet = workbook.getSheetAt(i);
UniverSheet univerSheet = new UniverSheet();
univerSheet.setId(sheetId);
univerSheet.setName(sheet.getSheetName());
univerSheet.setHidden(!workbook.isSheetHidden(i) ? 0 : 1);
univerSheet.setTabColor("");
// 冻结位置
UniverSheetFreeze sheetFreeze = new UniverSheetFreeze();
PaneInformation freeze = sheet.getPaneInformation();
if (freeze != null) {
int freezeColumn = freeze.getVerticalSplitLeftColumn();
int freezeRow = freeze.getHorizontalSplitTopRow();
if (freezeColumn > 0) {
sheetFreeze.setStartColumn(freezeColumn);
sheetFreeze.setXSplit(freezeColumn);
}
if (freezeRow > 0) {
sheetFreeze.setStartRow(freezeRow);
sheetFreeze.setYSplit(freezeRow);
}
}
univerSheet.setFreeze(sheetFreeze);
Map<Integer, UniverSheetRowData> rowData = new HashMap<>();
Map<Integer, UniverSheetColumnData> columnData = new HashMap<>();
Map<Integer, Map<Integer, UniverSheetCellData>> cellData = new HashMap<>();
for (int rowCount = 0; rowCount <= sheet.getLastRowNum(); rowCount++) {
HSSFRow row = sheet.getRow(rowCount);
Map<Integer, UniverSheetCellData> cells = new HashMap<>();
if (null != row) {
for (int columnCount = 0; columnCount <= row.getLastCellNum(); columnCount++) {
HSSFCell cell = row.getCell(columnCount);
UniverSheetCellData univerSheetCellData = new UniverSheetCellData();
if (null != cell) {
// 数据
Object value = "";
String formula = null;
CellType cellType = cell.getCellType();
Integer type = null;
switch (cellType) {
case STRING:
value = cell.getStringCellValue();
type = 1;
break;
case BOOLEAN:
value = cell.getBooleanCellValue();
type = 3;
break;
case NUMERIC:
value = cell.getNumericCellValue();
type = 2;
break;
case FORMULA:
value = cell.getCellFormula();
formula = "=" + value;
type = 4;
break;
case BLANK:
value = "";
type = 1;
break;
case ERROR:
value = "#ERROR";
type = 1;
break;
case _NONE:
value = "";
type = 1;
break;
}
univerSheetCellData.setV(value);
univerSheetCellData.setF(formula);
univerSheetCellData.setT(type);
// 样式
HSSFCellStyle cellStyle = cell.getCellStyle();
UniverStyle style = getUniverStyle(cellStyle, workbook);
String styleName = styleMap.get(style) != null ? styleMap.get(style)
: RandomUtil.randomString(6);
if (styleMap.get(style) == null) {
styleMap.put(style, styleName);
}
univerSheetCellData.setS(styleName);
cells.put(columnCount, univerSheetCellData);
UniverSheetColumnData univerSheetColumnData = new UniverSheetColumnData();
univerSheetColumnData.setHd(!sheet.isColumnHidden(columnCount) ? 0 : 1);
List<Integer> colHeight = new ArrayList<>();
colHeight.add(100);
colHeight.add((int) sheet.getColumnWidthInPixels(columnCount));
univerSheetColumnData.setW(Collections.max(colHeight));
columnData.put(columnCount, univerSheetColumnData);
}
}
cellData.put(rowCount, cells);
UniverSheetRowData univerSheetRowData = new UniverSheetRowData();
univerSheetRowData.setHd(!row.getZeroHeight() ? 0 : 1);
List<Integer> rowHeight = new ArrayList<>();
rowHeight.add(50);
rowHeight.add((int) row.getHeightInPoints());
univerSheetRowData.setH(Collections.max(rowHeight));
univerSheetRowData.setIa(0);
rowData.put(rowCount, univerSheetRowData);
}
}
univerSheet.setCellData(cellData);
univerSheet.setRowData(rowData);
univerSheet.setColumnData(columnData);
List<UniverSheetRange> mergeData = new ArrayList<>();
for (CellRangeAddress region : sheet.getMergedRegions()) {
UniverSheetRange univerSheetRange = new UniverSheetRange();
univerSheetRange.setStartRow(region.getFirstRow());
univerSheetRange.setStartColumn(region.getFirstColumn());
univerSheetRange.setEndRow(region.getLastRow());
univerSheetRange.setEndColumn(region.getLastColumn());
mergeData.add(univerSheetRange);
}
univerSheet.setMergeData(mergeData);
// 图片
drawing(sheet, sheetId, unitId, drawingMap);
// 条件
format(sheet, sheetId, unitId, formattingMap);
// 数据管理
dataValidation(sheet, sheetId, unitId, dataValidationMap);
// 筛选器
filter(sheet, sheetId, unitId, filterMap);
UniverSheetRowHeader univerSheetRowHeader = new UniverSheetRowHeader();
univerSheetRowHeader.setHidden(0);
univerSheetRowHeader.setWidth(46);
univerSheet.setRowHeader(univerSheetRowHeader);
UniverSheetColumnHeader univerSheetColumnHeader = new UniverSheetColumnHeader();
univerSheetColumnHeader.setHidden(0);
univerSheetColumnHeader.setHeight(20);
univerSheet.setColumnHeader(univerSheetColumnHeader);
univerSheet.setZoomRatio(1);
univerSheet.setScrollTop(0);
univerSheet.setScrollLeft(0);
univerSheet.setDefaultColumnWidth(88);
univerSheet.setDefaultRowHeight(24);
List<Integer> rowCount = new ArrayList<>();
rowCount.add(100);
rowCount.add(rowData.size());
univerSheet.setRowCount(Collections.max(rowCount));
List<Integer> columnCount = new ArrayList<>();
columnCount.add(30);
columnCount.add(columnData.size());
univerSheet.setColumnCount(Collections.max(columnCount));
univerSheet.setShowGridlines(sheet.isDisplayGridlines() ? 1 : 0);
univerSheet.setSelections(ImmutableList.of("A1"));
univerSheet.setRightToLeft(0);
sheets.put(sheetId, univerSheet);
}
Map<String, UniverStyle> styles = styleMap.entrySet().stream()
.collect(Collectors.toMap(t -> t.getValue(), t -> t.getKey()));
univerWorkBook.setStyles(styles);
univerWorkBook.setSheetOrder(sheetOrder);
univerWorkBook.setSheets(sheets);
Map<String, String> resourceMap = new HashMap<>();
resourceMap.put(ResourceEnum.SHEET_DRAWING_PLUGIN.name(), JSONUtil.toJsonStr(drawingMap));
resourceMap.put(ResourceEnum.SHEET_CONDITIONAL_FORMATTING_PLUGIN.name(), JSONUtil.toJsonStr(formattingMap));
resourceMap.put(ResourceEnum.SHEET_DATA_VALIDATION_PLUGIN.name(), JSONUtil.toJsonStr(dataValidationMap));
resourceMap.put(ResourceEnum.SHEET_FILTER_PLUGIN.name(), JSONUtil.toJsonStr(filterMap));
univerWorkBook.setResources(getUniverResources(resourceMap));
return univerWorkBook;
}
private UniverStyle getUniverStyle(HSSFCellStyle cellStyle, HSSFWorkbook workbook) {
UniverStyle univerStyle = new UniverStyle();
univerStyle.setHt(HorizontalEnum.getHorizontalCode(cellStyle.getAlignment()));
univerStyle.setVt(VerticalEnum.getVerticalCode(cellStyle.getVerticalAlignment()));
HSSFFont font = cellStyle.getFont(workbook);
if (null != font) {
univerStyle.setFf(font.getFontName());
univerStyle.setFs((int) font.getFontHeightInPoints());
univerStyle.setIt(font.getItalic() ? 1 : 0);
univerStyle.setBl(font.getBold() ? 1 : 0);
HSSFColor color = font.getHSSFColor(workbook);
if (null != color) {
UniverStyleColor cl = new UniverStyleColor();
cl.setRgb(rgb(color.getTriplet()));
univerStyle.setCl(cl);
}
if (Objects.equals(font.getUnderline(), Font.U_SINGLE)) {
UniverStyleTextDecoration ul = new UniverStyleTextDecoration();
ul.setS(1);
univerStyle.setUl(ul);
}
if (font.getStrikeout()) {
UniverStyleTextDecoration st = new UniverStyleTextDecoration();
st.setS(1);
univerStyle.setSt(st);
}
}
if (null != cellStyle.getDataFormatString()) {
UniverStylePattern pattern = new UniverStylePattern();
pattern.setPattern(cellStyle.getDataFormatString());
univerStyle.setN(pattern);
}
univerStyle.setBd(getUniverStyleBorder(cellStyle, workbook));
HSSFColor bgColor = cellStyle.getFillForegroundColorColor();
FillPatternType pattern = cellStyle.getFillPattern();
if (null != bgColor && Objects.equals(pattern, FillPatternType.SOLID_FOREGROUND)) {
UniverStyleColor background = new UniverStyleColor();
background.setRgb(rgb(bgColor.getTriplet()));
univerStyle.setBg(background);
}
UniverStyleTextRotation univerStyleTextRotation = new UniverStyleTextRotation();
univerStyleTextRotation.setA(cellStyle.getRotation());
univerStyle.setTr(univerStyleTextRotation);
return univerStyle;
}
private String rgb(short[] color) {
String rgb = null;
if (null != color && color.length == 3) {
rgb = String.format("#%02X%02X%02X", color[0], color[1], color[2]);
}
return rgb;
}
private String rgb(byte[] color) {
String rgb = null;
if (ObjectUtil.isNotEmpty(color)) {
rgb = String.format("#%02X%02X%02X", color[0], color[1], color[2]);
}
return rgb;
}
private UniverStyleBorder getUniverStyleBorder(HSSFCellStyle cellStyle, HSSFWorkbook workbook) {
UniverStyleBorder univerStyleBorder = new UniverStyleBorder();
int num = 0;
HSSFPalette palette = workbook.getCustomPalette();
HSSFColor leftBorder = palette.getColor(cellStyle.getLeftBorderColor());
if (null != leftBorder) {
UniverStyleBorderStyle left = new UniverStyleBorderStyle();
UniverStyleColor leftColor = new UniverStyleColor();
leftColor.setRgb(rgb(leftBorder.getTriplet()));
left.setCl(leftColor);
univerStyleBorder.setL(left);
num++;
}
HSSFColor topBorder = palette.getColor(cellStyle.getTopBorderColor());
if (null != topBorder) {
UniverStyleBorderStyle top = new UniverStyleBorderStyle();
UniverStyleColor topColor = new UniverStyleColor();
topColor.setRgb(rgb(topBorder.getTriplet()));
top.setCl(topColor);
univerStyleBorder.setT(top);
num++;
}
HSSFColor rightBorder = palette.getColor(cellStyle.getRightBorderColor());
if (null != rightBorder) {
UniverStyleBorderStyle right = new UniverStyleBorderStyle();
UniverStyleColor rightColor = new UniverStyleColor();
rightColor.setRgb(rgb(rightBorder.getTriplet()));
right.setCl(rightColor);
univerStyleBorder.setR(right);
num++;
}
HSSFColor bottomBorder = palette.getColor(cellStyle.getBottomBorderColor());
if (null != bottomBorder) {
UniverStyleBorderStyle bottom = new UniverStyleBorderStyle();
UniverStyleColor bottomColor = new UniverStyleColor();
bottomColor.setRgb(rgb(bottomBorder.getTriplet()));
bottom.setCl(bottomColor);
univerStyleBorder.setB(bottom);
num++;
}
return num > 0 ? univerStyleBorder : null;
}
private List<UniverResource> getUniverResources(Map<String, String> resourceMap) {
List<UniverResource> resourcesList = new ArrayList<>();
for (ResourceEnum resource : ResourceEnum.values()) {
UniverResource model = new UniverResource();
String name = resource.name();
model.setName(name);
model.setData(resourceMap.get(name) != null ? resourceMap.get(name) : "{}");
resourcesList.add(model);
}
return resourcesList;
}
private void drawing(HSSFSheet sheet, String sheetId, String unitId, Map<String, UniverResourceData> drawingMap) {
List<String> order = new ArrayList<>();
Map<String, UniverDrawing> data = new HashMap<>();
HSSFPatriarch drawing = sheet.getDrawingPatriarch();
if (drawing != null) {
List<HSSFShape> shapes = drawing.getChildren();
for (HSSFShape shape : shapes) {
if (shape instanceof HSSFPicture) {
HSSFPicture picture = (HSSFPicture) shape;
byte[] pictureData = picture.getPictureData().getData();
if (pictureData.length > 0) {
String drawingId = RandomUtil.randomString(10);
order.add(drawingId);
BufferedImage image = ImgUtil.toImage(pictureData);
UniverTransform sheetTransform = new UniverTransform();
HSSFClientAnchor anchor = picture.getClientAnchor();
UniverOffset univerFrom = new UniverOffset();
univerFrom.setRow(anchor.getRow1());
univerFrom.setColumn((int) anchor.getCol1());
sheetTransform.setFrom(univerFrom);
UniverOffset univerTo = new UniverOffset();
univerTo.setRow(anchor.getRow2());
univerTo.setColumn((int) anchor.getCol2());
sheetTransform.setTo(univerTo);
UniverDrawing univerDrawing = new UniverDrawing();
univerDrawing.setSheetTransform(sheetTransform);
univerDrawing.setDrawingType(0);
univerDrawing.setUnitId(unitId);
univerDrawing.setSubUnitId(sheetId);
univerDrawing.setDrawingId(drawingId);
univerDrawing.setImageSourceType(ImageEnum.BASE64.name());
univerDrawing.setSource("data:image/jpeg;base64," + ImgUtil.toBase64(image, "jpeg"));
data.put(drawingId, univerDrawing);
}
}
}
}
if (!order.isEmpty()) {
UniverResourceData resourceData = new UniverResourceData();
resourceData.setData(data);
resourceData.setOrder(order);
drawingMap.put(sheetId, resourceData);
}
}
private void format(HSSFSheet sheet, String sheetId, String unitId,
Map<String, List<UniverResourceData>> formattingMap) {
// todo 提供色阶、数据条、色阶方法,其他方法获取的数据有问题
List<UniverResourceData> formatList = new ArrayList<>();
HSSFSheetConditionalFormatting formatting = sheet.getSheetConditionalFormatting();
if (null != formatting) {
for (int i = 0; i < formatting.getNumConditionalFormattings(); i++) {
HSSFConditionalFormatting format = formatting.getConditionalFormattingAt(i);
UniverResourceData resourceData = new UniverResourceData();
resourceData.setCfId(RandomUtil.randomString(10));
CellRangeAddress[] formattingRanges = format.getFormattingRanges();
List<UniverSheetRange> ranges = new ArrayList<>();
resourceData.setRanges(ranges);
for (CellRangeAddress rangeAddress : formattingRanges) {
UniverSheetRange range = new UniverSheetRange();
range.setStartRow(rangeAddress.getFirstRow());
range.setStartColumn(rangeAddress.getFirstColumn());
range.setEndRow(rangeAddress.getLastRow());
range.setEndColumn(rangeAddress.getLastColumn());
range.setUnitId(unitId);
range.setSheetId(sheetId);
ranges.add(range);
}
for (int num = 0; num < format.getNumberOfRules(); num++) {
HSSFConditionalFormattingRule formatRule = format.getRule(num);
HSSFIconMultiStateFormatting iconSet = formatRule.getMultiStateFormatting();
if (iconSet != null) {
boolean reverse = iconSet.isReversed();
UniverRule rule = new UniverRule();
List<UniverConfig> univerConfig = new ArrayList<>();
rule.setType(FormatTypeEnum.iconSet.name());
rule.setConfig(univerConfig);
// 显示数据条没有属性
rule.setIsShowValue(false);
String iconType = iconSet.getIconSet().name;
HSSFConditionalFormattingThreshold[] cfvoList = iconSet.getThresholds();
int iconId = 0;
for (int k = cfvoList.length - 1; k >= 0; k--) {
HSSFConditionalFormattingThreshold cfvo = cfvoList[k];
UniverValue value = new UniverValue();
String type = cfvo.getRangeType().name;
String val = Objects.equals(SubTypeEnum.expression.getCode(), type)
? "=" + cfvo.getFormula().replaceAll("\"", "")
: cfvo.getValue() + "";
value.setValue(val);
value.setType(type);
UniverConfig config = new UniverConfig();
config.setOperator(OperatorEnum.greaterThan.name());
config.setIconId((reverse ? k : iconId) + "");
config.setIconType(iconType);
config.setValue(value);
univerConfig.add(config);
iconId++;
}
resourceData.setRule(rule);
}
HSSFDataBarFormatting dataBar = formatRule.getDataBarFormatting();
if (dataBar != null) {
UniverRule rule = new UniverRule();
UniverConfig config = new UniverConfig();
rule.setConfig(config);
rule.setType(FormatTypeEnum.dataBar.name());
// 显示数据条没有属性
rule.setIsShowValue(false);
HSSFConditionalFormattingThreshold minThreshold = dataBar.getMinThreshold();
UniverValue min = new UniverValue();
min.setType(minThreshold.getRangeType().name);
min.setValue(Objects.equals(SubTypeEnum.expression.getCode(), min.getType())
? "=" + minThreshold.getFormula().replaceAll("\"", "")
: minThreshold.getValue() + "");
config.setMin(min);
HSSFConditionalFormattingThreshold maxThreshold = dataBar.getMaxThreshold();
UniverValue max = new UniverValue();
max.setType(maxThreshold.getRangeType().name);
max.setValue(Objects.equals(SubTypeEnum.expression.getCode(), max.getType())
? "=" + maxThreshold.getFormula().replaceAll("\"", "")
: maxThreshold.getValue() + "");
config.setMax(max);
config.setIsGradient(true);
byte[] rgb = dataBar.getColor().getRGB();
config.setPositiveColor(rgb(rgb));
config.setNativeColor(rgb(rgb));
resourceData.setRule(rule);
}
HSSFColorScaleFormatting colorScale = formatRule.getColorScaleFormatting();
if (colorScale != null) {
UniverRule rule = new UniverRule();
List<UniverConfig> univerConfig = new ArrayList<>();
rule.setType(FormatTypeEnum.colorScale.name());
rule.setConfig(univerConfig);
Map<Integer, UniverValue> colorValue = new HashMap<>();
HSSFConditionalFormattingThreshold[] cfvoList = colorScale.getThresholds();
for (int k = 0; k < cfvoList.length; k++) {
HSSFConditionalFormattingThreshold cfvo = cfvoList[k];
UniverValue value = new UniverValue();
String type = cfvo.getRangeType().name;
String val = Objects.equals(SubTypeEnum.expression.getCode(), type)
? "=" + cfvo.getFormula().replaceAll("\"", "")
: cfvo.getValue() + "";
value.setType(type);
value.setValue(val);
colorValue.put(k, value);
}
HSSFExtendedColor[] colorList = colorScale.getColors();
Map<Integer, String> colorColor = new HashMap<>();
for (int k = 0; k < colorList.length; k++) {
HSSFExtendedColor ctColor = colorList[k];
colorColor.put(k, rgb(ctColor.getRGB()));
}
for (Integer k : colorValue.keySet()) {
UniverConfig config = new UniverConfig();
config.setValue(colorValue.get(k));
config.setColor(colorColor.get(k));
config.setIndex(k);
univerConfig.add(config);
}
resourceData.setRule(rule);
}
resourceData.setStopIfTrue(formatRule.getStopIfTrue());
if (resourceData.getRule() == null) {
continue;
}
formatList.add(resourceData);
}
}
}
formattingMap.put(sheetId, formatList);
}
private void filter(HSSFSheet sheet, String sheetId, String unitId, Map<String, UniverResourceData> filterMap) {
// todo 只有获取筛选的格子,没有提供筛选的内容
int sheetIndex = sheet.getWorkbook().getSheetIndex(sheet) + 1;
UniverResourceData data = new UniverResourceData();
InternalWorkbook workbook = sheet.getWorkbook().getWorkbook();
if (workbook != null) {
NameRecord name = workbook.getSpecificBuiltinRecord((byte) 13, sheetIndex);
if (name != null) {
Ptg[] nameDefinition = name.getNameDefinition();
String formulaString = HSSFFormulaParser.toFormulaString(sheet.getWorkbook(), nameDefinition);
CellRangeAddress addresses = CellRangeAddress.valueOf(formulaString);
UniverSheetRange ref = new UniverSheetRange();
ref.setStartRow(addresses.getFirstRow());
ref.setStartColumn(addresses.getFirstColumn());
ref.setEndRow(addresses.getLastRow());
ref.setEndColumn(addresses.getLastColumn());
data.setRef(ref);
List<UniverFilters> filterColumns = new ArrayList<>();
data.setFilterColumns(filterColumns);
List<Integer> cachedFilteredOut = new ArrayList<>();
data.setCachedFilteredOut(cachedFilteredOut);
filterMap.put(sheetId, data);
}
}
}
private static void dataValidation(HSSFSheet sheet, String sheetId, String unitId,
Map<String, List<UniverResourceData>> dataValidationMap) {
List<UniverResourceData> dataValidationList = new ArrayList<>();
List<HSSFDataValidation> dataValidations = sheet.getDataValidations();
for (HSSFDataValidation dataValidation : dataValidations) {
UniverResourceData resourceData = new UniverResourceData();
List<UniverSheetRange> ranges = new ArrayList<>();
resourceData.setRanges(ranges);
resourceData.setUid(RandomUtil.randomString(10));
CellRangeAddressList addressList = dataValidation.getRegions();
for (CellRangeAddress address : addressList.getGenericChildren()) {
UniverSheetRange sheetRange = new UniverSheetRange();
sheetRange.setStartRow(address.getFirstRow());
sheetRange.setStartColumn(address.getFirstColumn());
sheetRange.setEndRow(address.getLastRow());
sheetRange.setEndColumn(address.getLastColumn());
sheetRange.setSheetId(sheetId);
sheetRange.setUnitId(unitId);
ranges.add(sheetRange);
}
DVConstraint constraint = (DVConstraint) dataValidation.getValidationConstraint();
ValidationType validationType = ValidationType.getType(constraint.getValidationType());
resourceData.setType(validationType.getType());
operatorTypeEnum operator = Objects.equals(validationType, ValidationType.none) ? null
: operatorTypeEnum.getOperator(constraint.getOperator());
resourceData.setOperator(operator != null ? operator.getOperatorType() : null);
String value1 = constraint.getValue1() != null ? constraint.getValue1().toString()
: constraint.getFormula1();
String value2 = constraint.getValue2() != null ? constraint.getValue2().toString()
: constraint.getFormula2();
resourceData.setFormula1(value1 != null ? value1.replaceAll("\"", "") : value1);
resourceData.setFormula2(value2 != null ? value2.replaceAll("\"", "") : value2);
if (dataValidation.getShowErrorBox()) {
resourceData.setShowErrorMessage(true);
resourceData.setError(dataValidation.getErrorBoxTitle());
resourceData.setErrorStyle(Objects.equals(dataValidation.getErrorStyle(), 0) ? 1 : 2);
}
resourceData.setAllowBlank(dataValidation.getEmptyCellAllowed());
resourceData.setRenderMode(dataValidation.getSuppressDropDownArrow() ? null : 0);
dataValidationList.add(resourceData);
}
dataValidationMap.put(sheetId, dataValidationList);
}
}

View File

@@ -0,0 +1,728 @@
package com.yunzhupaas.util.excel;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.ImmutableList;
import com.yunzhupaas.enums.*;
import com.yunzhupaas.univer.data.resource.*;
import com.yunzhupaas.univer.model.UniverWorkBook;
import com.yunzhupaas.univer.resources.UniverResource;
import com.yunzhupaas.univer.resources.UniverResourceData;
import com.yunzhupaas.univer.sheet.*;
import com.yunzhupaas.univer.style.*;
import com.yunzhupaas.util.StringUtil;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.ss.util.PaneInformation;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/6/20 下午4:30
*/
public class UniverXSSFExcel extends ExcelParser {
@Override
public UniverWorkBook formFile(InputStream inputStream) throws IOException {
try (XSSFWorkbook workbook = new XSSFWorkbook(inputStream)) {
UniverWorkBook univerWorkBook = new UniverWorkBook();
String unitId = RandomUtil.randomString(10);
univerWorkBook.setId(unitId);
univerWorkBook.setName("");
Map<UniverStyle, String> styleMap = new HashMap<>();
Map<String, UniverSheet> sheets = new HashMap<>();
List<String> sheetOrder = new ArrayList<>();
Map<String, UniverResourceData> drawingMap = new HashMap<>();
Map<String, List<UniverResourceData>> formattingMap = new HashMap<>();
Map<String, List<UniverResourceData>> dataValidationMap = new HashMap<>();
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
String sheetId = RandomUtil.randomString(10);
sheetOrder.add(sheetId);
XSSFSheet sheet = workbook.getSheetAt(i);
UniverSheet univerSheet = new UniverSheet();
univerSheet.setId(sheetId);
univerSheet.setName(sheet.getSheetName());
univerSheet.setHidden(!workbook.isSheetHidden(i) ? 0 : 1);
univerSheet.setTabColor("");
// 冻结位置
UniverSheetFreeze sheetFreeze = new UniverSheetFreeze();
PaneInformation freeze = sheet.getPaneInformation();
if (freeze != null) {
int freezeColumn = freeze.getVerticalSplitLeftColumn();
if (freezeColumn > 0) {
sheetFreeze.setStartColumn(freezeColumn);
sheetFreeze.setXSplit(freezeColumn);
}
int freezeRow = freeze.getHorizontalSplitTopRow();
if (freezeRow > 0) {
sheetFreeze.setStartRow(freezeRow);
sheetFreeze.setYSplit(freezeRow);
}
}
univerSheet.setFreeze(sheetFreeze);
Map<Integer, UniverSheetRowData> rowData = new HashMap<>();
Map<Integer, UniverSheetColumnData> columnData = new HashMap<>();
Map<Integer, Map<Integer, UniverSheetCellData>> cellData = new HashMap<>();
for (int rowCount = 0; rowCount <= sheet.getLastRowNum(); rowCount++) {
XSSFRow row = sheet.getRow(rowCount);
Map<Integer, UniverSheetCellData> cells = new HashMap<>();
if (null != row) {
for (int columnCount = 0; columnCount <= row.getLastCellNum(); columnCount++) {
XSSFCell cell = row.getCell(columnCount);
UniverSheetCellData univerSheetCellData = new UniverSheetCellData();
if (null != cell) {
// 数据
Object value = "";
String formula = null;
CellType cellType = cell.getCellType();
Integer type = null;
switch (cellType) {
case STRING:
value = cell.getStringCellValue();
type = 1;
break;
case BOOLEAN:
value = cell.getBooleanCellValue();
type = 3;
break;
case NUMERIC:
value = cell.getNumericCellValue();
type = 2;
break;
case FORMULA:
value = cell.getCellFormula();
formula = "=" + value;
type = 4;
break;
case BLANK:
value = "";
type = 1;
break;
case ERROR:
value = cell.getErrorCellValue();
type = 5;
break;
case _NONE:
value = "";
type = 1;
break;
}
univerSheetCellData.setV(value);
univerSheetCellData.setF(formula);
univerSheetCellData.setT(type);
// 样式
XSSFCellStyle cellStyle = cell.getCellStyle();
UniverStyle style = getUniverStyle(cellStyle);
String styleName = styleMap.get(style) != null ? styleMap.get(style)
: RandomUtil.randomString(6);
if (styleMap.get(style) == null) {
styleMap.put(style, styleName);
}
univerSheetCellData.setS(styleName);
cells.put(columnCount, univerSheetCellData);
UniverSheetColumnData univerSheetColumnData = new UniverSheetColumnData();
univerSheetColumnData.setHd(!sheet.isColumnHidden(columnCount) ? 0 : 1);
List<Integer> colHeight = new ArrayList<>();
colHeight.add(100);
colHeight.add((int) sheet.getColumnWidthInPixels(columnCount));
univerSheetColumnData.setW(Collections.max(colHeight));
columnData.put(columnCount, univerSheetColumnData);
}
}
cellData.put(rowCount, cells);
UniverSheetRowData univerSheetRowData = new UniverSheetRowData();
univerSheetRowData.setHd(!row.getZeroHeight() ? 0 : 1);
List<Integer> rowHeight = new ArrayList<>();
rowHeight.add(50);
rowHeight.add((int) row.getHeightInPoints());
univerSheetRowData.setH(Collections.max(rowHeight));
univerSheetRowData.setIa(0);
rowData.put(rowCount, univerSheetRowData);
}
}
univerSheet.setCellData(cellData);
univerSheet.setRowData(rowData);
univerSheet.setColumnData(columnData);
List<UniverSheetRange> mergeData = new ArrayList<>();
for (CellRangeAddress region : sheet.getMergedRegions()) {
UniverSheetRange univerSheetRange = new UniverSheetRange();
univerSheetRange.setStartRow(region.getFirstRow());
univerSheetRange.setStartColumn(region.getFirstColumn());
univerSheetRange.setEndRow(region.getLastRow());
univerSheetRange.setEndColumn(region.getLastColumn());
mergeData.add(univerSheetRange);
}
univerSheet.setMergeData(mergeData);
// 图片
drawing(sheet, sheetId, unitId, drawingMap);
// 条件
format(sheet, sheetId, unitId, formattingMap);
// 数据管理
dataValidation(sheet, sheetId, unitId, dataValidationMap);
// 筛选
filter(sheet, sheetId, unitId, drawingMap);
UniverSheetRowHeader univerSheetRowHeader = new UniverSheetRowHeader();
univerSheetRowHeader.setHidden(0);
univerSheetRowHeader.setWidth(46);
univerSheet.setRowHeader(univerSheetRowHeader);
UniverSheetColumnHeader univerSheetColumnHeader = new UniverSheetColumnHeader();
univerSheetColumnHeader.setHidden(0);
univerSheetColumnHeader.setHeight(20);
univerSheet.setColumnHeader(univerSheetColumnHeader);
univerSheet.setZoomRatio(1);
univerSheet.setScrollTop(0);
univerSheet.setScrollLeft(0);
univerSheet.setDefaultColumnWidth(88);
univerSheet.setDefaultRowHeight(24);
List<Integer> rowCount = new ArrayList<>();
rowCount.add(100);
rowCount.add(rowData.size());
univerSheet.setRowCount(Collections.max(rowCount));
List<Integer> columnCount = new ArrayList<>();
columnCount.add(30);
columnCount.add(columnData.size());
univerSheet.setColumnCount(Collections.max(columnCount));
univerSheet.setShowGridlines(sheet.isDisplayGridlines() ? 1 : 0);
univerSheet.setSelections(ImmutableList.of("A1"));
univerSheet.setRightToLeft(0);
sheets.put(sheetId, univerSheet);
}
Map<String, UniverStyle> styles = styleMap.entrySet().stream()
.collect(Collectors.toMap(t -> t.getValue(), t -> t.getKey()));
univerWorkBook.setStyles(styles);
univerWorkBook.setSheetOrder(sheetOrder);
univerWorkBook.setSheets(sheets);
Map<String, String> resourceMap = new HashMap<>();
resourceMap.put(ResourceEnum.SHEET_DRAWING_PLUGIN.name(), JSONUtil.toJsonStr(drawingMap));
resourceMap.put(ResourceEnum.SHEET_CONDITIONAL_FORMATTING_PLUGIN.name(), JSONUtil.toJsonStr(formattingMap));
resourceMap.put(ResourceEnum.SHEET_DATA_VALIDATION_PLUGIN.name(), JSONUtil.toJsonStr(dataValidationMap));
univerWorkBook.setResources(getUniverResources(resourceMap));
return univerWorkBook;
}
}
private UniverStyle getUniverStyle(XSSFCellStyle cellStyle) {
UniverStyle univerStyle = new UniverStyle();
univerStyle.setHt(HorizontalEnum.getHorizontalCode(cellStyle.getAlignment()));
univerStyle.setVt(VerticalEnum.getVerticalCode(cellStyle.getVerticalAlignment()));
XSSFFont font = cellStyle.getFont();
if (null != font) {
univerStyle.setFf(font.getFontName());
univerStyle.setFs((int) font.getFontHeightInPoints());
univerStyle.setIt(font.getItalic() ? 1 : 0);
univerStyle.setBl(font.getBold() ? 1 : 0);
if (null != font.getXSSFColor()) {
UniverStyleColor cl = new UniverStyleColor();
cl.setRgb(rgb(font.getXSSFColor().getARGBHex()));
univerStyle.setCl(cl);
}
if (Objects.equals(font.getUnderline(), Font.U_SINGLE)) {
UniverStyleTextDecoration ul = new UniverStyleTextDecoration();
ul.setS(1);
univerStyle.setUl(ul);
}
if (font.getStrikeout()) {
UniverStyleTextDecoration st = new UniverStyleTextDecoration();
st.setS(1);
univerStyle.setSt(st);
}
}
if (null != cellStyle.getDataFormatString()) {
UniverStylePattern pattern = new UniverStylePattern();
pattern.setPattern(cellStyle.getDataFormatString());
univerStyle.setN(pattern);
}
univerStyle.setBd(getUniverStyleBorder(cellStyle));
XSSFColor bgColor = cellStyle.getFillForegroundColorColor();
FillPatternType pattern = cellStyle.getFillPattern();
if (null != bgColor && Objects.equals(pattern, FillPatternType.SOLID_FOREGROUND)) {
UniverStyleColor background = new UniverStyleColor();
background.setRgb(rgb(cellStyle.getFillForegroundColorColor().getARGBHex()));
univerStyle.setBg(background);
}
UniverStyleTextRotation univerStyleTextRotation = new UniverStyleTextRotation();
univerStyleTextRotation.setA(cellStyle.getRotation());
univerStyle.setTr(univerStyleTextRotation);
return univerStyle;
}
private String rgb(String color) {
String rgb = null;
if (StringUtil.isNotEmpty(color)) {
rgb = "#" + color.substring(2, 8);
}
return rgb;
}
private String rgb(byte[] color) {
String rgb = null;
if (ObjectUtil.isNotEmpty(color)) {
XSSFColor xssfColor = new XSSFColor(color);
rgb = rgb(xssfColor.getARGBHex());
}
return rgb;
}
private UniverStyleBorder getUniverStyleBorder(XSSFCellStyle cellStyle) {
UniverStyleBorder univerStyleBorder = new UniverStyleBorder();
int num = 0;
if (null != cellStyle.getLeftBorderXSSFColor()) {
UniverStyleBorderStyle left = new UniverStyleBorderStyle();
UniverStyleColor leftColor = new UniverStyleColor();
leftColor.setRgb(rgb(cellStyle.getLeftBorderXSSFColor().getARGBHex()));
left.setCl(leftColor);
univerStyleBorder.setL(left);
num++;
}
if (null != cellStyle.getTopBorderXSSFColor()) {
UniverStyleBorderStyle top = new UniverStyleBorderStyle();
UniverStyleColor topColor = new UniverStyleColor();
topColor.setRgb(rgb(cellStyle.getTopBorderXSSFColor().getARGBHex()));
top.setCl(topColor);
univerStyleBorder.setT(top);
num++;
}
if (null != cellStyle.getRightBorderXSSFColor()) {
UniverStyleBorderStyle right = new UniverStyleBorderStyle();
UniverStyleColor rightColor = new UniverStyleColor();
rightColor.setRgb(rgb(cellStyle.getRightBorderXSSFColor().getARGBHex()));
right.setCl(rightColor);
univerStyleBorder.setR(right);
num++;
}
if (null != cellStyle.getBottomBorderXSSFColor()) {
UniverStyleBorderStyle bottom = new UniverStyleBorderStyle();
UniverStyleColor bottomColor = new UniverStyleColor();
bottomColor.setRgb(rgb(cellStyle.getBottomBorderXSSFColor().getARGBHex()));
bottom.setCl(bottomColor);
univerStyleBorder.setB(bottom);
num++;
}
return num > 0 ? univerStyleBorder : null;
}
private List<UniverResource> getUniverResources(Map<String, String> resourceMap) {
List<UniverResource> resourcesList = new ArrayList<>();
for (ResourceEnum resource : ResourceEnum.values()) {
UniverResource model = new UniverResource();
String name = resource.name();
model.setName(name);
model.setData(resourceMap.get(name) != null ? resourceMap.get(name) : "{}");
resourcesList.add(model);
}
return resourcesList;
}
private void drawing(XSSFSheet sheet, String sheetId, String unitId, Map<String, UniverResourceData> drawingMap) {
List<String> order = new ArrayList<>();
Map<String, UniverDrawing> data = new HashMap<>();
XSSFDrawing drawing = sheet.getDrawingPatriarch();
if (drawing != null) {
List<XSSFShape> shapes = drawing.getShapes();
for (XSSFShape shape : shapes) {
if (shape instanceof XSSFPicture) {
XSSFPicture picture = (XSSFPicture) shape;
byte[] pictureData = picture.getPictureData().getData();
if (pictureData.length > 0) {
String drawingId = RandomUtil.randomString(10);
order.add(drawingId);
BufferedImage image = ImgUtil.toImage(pictureData);
UniverTransform sheetTransform = new UniverTransform();
XSSFClientAnchor anchor = picture.getClientAnchor();
UniverOffset univerFrom = new UniverOffset();
univerFrom.setRow(anchor.getRow1());
univerFrom.setColumn((int) anchor.getCol1());
sheetTransform.setFrom(univerFrom);
UniverOffset univerTo = new UniverOffset();
univerTo.setRow(anchor.getRow2());
univerTo.setColumn((int) anchor.getCol2());
sheetTransform.setTo(univerTo);
UniverDrawing univerDrawing = new UniverDrawing();
univerDrawing.setSheetTransform(sheetTransform);
univerDrawing.setDrawingType(0);
univerDrawing.setUnitId(unitId);
univerDrawing.setSubUnitId(sheetId);
univerDrawing.setDrawingId(drawingId);
univerDrawing.setImageSourceType(ImageEnum.BASE64.name());
univerDrawing.setSource("data:image/jpeg;base64," + ImgUtil.toBase64(image, "jpeg"));
data.put(drawingId, univerDrawing);
}
}
}
}
if (!order.isEmpty()) {
UniverResourceData resourceData = new UniverResourceData();
resourceData.setData(data);
resourceData.setOrder(order);
drawingMap.put(sheetId, resourceData);
}
}
private void format(XSSFSheet sheet, String sheetId, String unitId,
Map<String, List<UniverResourceData>> formattingMap) {
StylesTable styles = sheet.getWorkbook().getStylesSource();
List<UniverResourceData> formatList = new ArrayList<>();
List<CTConditionalFormatting> conditionalFormatting = sheet.getCTWorksheet().getConditionalFormattingList();
for (CTConditionalFormatting conditional : conditionalFormatting) {
UniverResourceData resourceData = new UniverResourceData();
resourceData.setCfId(RandomUtil.randomString(10));
List<UniverSheetRange> ranges = new ArrayList<>();
resourceData.setRanges(ranges);
@SuppressWarnings("unchecked")
List<String> formattingRanges = conditional.getSqref();
for (String range : formattingRanges) {
UniverSheetRange sheetRange = new UniverSheetRange();
CellRangeAddress rangeAddress = CellRangeAddress.valueOf(range);
sheetRange.setStartRow(rangeAddress.getFirstRow());
sheetRange.setStartColumn(rangeAddress.getFirstColumn());
sheetRange.setEndRow(rangeAddress.getLastRow());
sheetRange.setEndColumn(rangeAddress.getLastColumn());
sheetRange.setUnitId(unitId);
sheetRange.setSheetId(sheetId);
ranges.add(sheetRange);
}
List<CTCfRule> cfRuleList = conditional.getCfRuleList();
for (CTCfRule cfRule : cfRuleList) {
CTIconSet iconSet = cfRule.getIconSet();
if (iconSet != null) {
boolean reverse = iconSet.getReverse();
UniverRule rule = new UniverRule();
List<UniverConfig> univerConfig = new ArrayList<>();
rule.setType(FormatTypeEnum.iconSet.name());
rule.setConfig(univerConfig);
rule.setIsShowValue(iconSet.getShowValue());
String iconType = iconSet.getIconSet().toString();
List<CTCfvo> cfvoList = iconSet.getCfvoList();
int iconId = 0;
for (int k = cfvoList.size() - 1; k >= 0; k--) {
CTCfvo cfvo = cfvoList.get(k);
UniverValue value = new UniverValue();
String type = cfvo.getType().toString();
String cfValue = cfvo.getVal() != null ? cfvo.getVal().toString() : "";
String val = (Objects.equals(SubTypeEnum.expression.getType(), type) ? "=" : "")
+ cfValue.replaceAll("\"", "");
value.setValue(val);
value.setType(type);
UniverConfig config = new UniverConfig();
config.setOperator(cfvo.getGte() ? OperatorEnum.greaterThanOrEqual.name()
: OperatorEnum.greaterThan.name());
config.setIconId((reverse ? k : iconId) + "");
config.setIconType(iconType);
config.setValue(value);
univerConfig.add(config);
iconId++;
}
resourceData.setRule(rule);
}
CTDataBar dataBar = cfRule.getDataBar();
if (dataBar != null) {
UniverRule rule = new UniverRule();
UniverConfig config = new UniverConfig();
rule.setConfig(config);
rule.setType(FormatTypeEnum.dataBar.name());
rule.setIsShowValue(dataBar.getShowValue());
List<CTCfvo> cfvoList = dataBar.getCfvoList();
UniverValue min = new UniverValue();
min.setType(OperatorEnum.min.name());
config.setMin(min);
UniverValue max = new UniverValue();
max.setType(OperatorEnum.max.name());
config.setMax(max);
for (int k = 0; k < cfvoList.size(); k++) {
CTCfvo cfvo = cfvoList.get(k);
String type = cfvo.getType().toString();
String cfValue = cfvo.getVal() != null ? cfvo.getVal().toString() : "";
String val = (Objects.equals(SubTypeEnum.expression.getType(), type) ? "=" : "")
+ cfValue.replaceAll("\"", "");
if (k == 0) {
min.setValue(val);
min.setType(type);
} else {
max.setValue(val);
max.setType(Objects.equals(type, OperatorEnum.min.name()) ? max.getType() : type);
}
}
config.setIsGradient(false);
CTColor color = dataBar.getColor();
if (color != null) {
String colorRgb = rgb(color.getRgb());
config.setPositiveColor(colorRgb);
config.setNativeColor(colorRgb);
}
resourceData.setRule(rule);
}
CTColorScale colorScale = cfRule.getColorScale();
if (colorScale != null) {
UniverRule rule = new UniverRule();
List<UniverConfig> univerConfig = new ArrayList<>();
rule.setType(FormatTypeEnum.colorScale.name());
rule.setConfig(univerConfig);
Map<Integer, UniverValue> colorValue = new HashMap<>();
List<CTCfvo> cfvoList = colorScale.getCfvoList();
for (int k = 0; k < cfvoList.size(); k++) {
CTCfvo cfvo = cfvoList.get(k);
UniverValue value = new UniverValue();
String type = cfvo.getType().toString();
String cfValue = cfvo.getVal() != null ? cfvo.getVal().toString() : "";
String val = (Objects.equals(SubTypeEnum.expression.getType(), type) ? "=" : "")
+ cfValue.replaceAll("\"", "");
value.setType(type);
value.setValue(val);
colorValue.put(k, value);
}
List<CTColor> colorList = colorScale.getColorList();
Map<Integer, String> colorColor = new HashMap<>();
for (int k = 0; k < colorList.size(); k++) {
CTColor color = colorList.get(k);
String colorRgb = rgb(color.getRgb());
colorColor.put(k, colorRgb);
}
for (Integer k : colorValue.keySet()) {
UniverConfig config = new UniverConfig();
config.setValue(colorValue.get(k));
config.setColor(colorColor.get(k));
config.setIndex(k);
univerConfig.add(config);
}
resourceData.setRule(rule);
}
CTCfRule highlightCell = cfRule;
if (highlightCell != null) {
String type = highlightCell.getType().toString();
SubTypeEnum subTypeEnum = SubTypeEnum.getType(type);
if (subTypeEnum != null) {
UniverRule rule = new UniverRule();
rule.setType(FormatTypeEnum.highlightCell.name());
boolean isUnique = Arrays
.asList(SubTypeEnum.uniqueValues.getType(), SubTypeEnum.duplicateValues.getType())
.contains(subTypeEnum.getType());
boolean isNumber = Objects.equals(SubTypeEnum.cellIs.getType(), subTypeEnum.getType());
boolean isAverage = Objects.equals(SubTypeEnum.aboveAverage.getType(), subTypeEnum.getType());
boolean isRank = Objects.equals(SubTypeEnum.top10.getType(), subTypeEnum.getType());
boolean isFormula = Objects.equals(SubTypeEnum.expression.getType(), subTypeEnum.getType());
boolean isTime = Objects.equals(SubTypeEnum.timePeriod.getType(), subTypeEnum.getType());
List<String> dataList = highlightCell.getFormulaList() != null ? highlightCell.getFormulaList()
: new ArrayList<>();
List<BigDecimal> numberDataList = new ArrayList<>();
BigDecimal numberData = null;
String textValue = "";
for (String data : dataList) {
try {
BigDecimal bigDecimal = new BigDecimal(data);
numberDataList.add(bigDecimal);
numberData = bigDecimal;
} catch (Exception e) {
textValue = data;
}
}
if (isNumber) {
if (highlightCell.getOperator() != null) {
rule.setOperator(highlightCell.getOperator().toString());
}
boolean isText = numberDataList.isEmpty();
rule.setSubType(isText ? SubTypeEnum.text.getCode() : SubTypeEnum.cellIs.getCode());
rule.setValue(isText ? textValue : numberDataList.size() > 1 ? numberDataList : numberData);
} else if (isAverage) {
rule.setSubType(subTypeEnum.getCode());
rule.setOperator(highlightCell.getAboveAverage() ? OperatorEnum.greaterThan.name()
: OperatorEnum.lessThan.name());
} else if (isRank) {
rule.setSubType(subTypeEnum.getCode());
rule.setIsPercent(highlightCell.getPercent());
rule.setIsBottom(highlightCell.getBottom());
rule.setValue(highlightCell.getRank() + "");
} else if (isFormula) {
rule.setSubType(SubTypeEnum.expression.getCode());
rule.setValue("=" + textValue.replaceAll("\"", ""));
} else if (isTime) {
rule.setSubType(subTypeEnum.getCode());
rule.setOperator(highlightCell.getTimePeriod().toString());
} else if (isUnique) {
rule.setSubType(subTypeEnum.getType());
} else {
rule.setSubType(SubTypeEnum.text.getCode());
rule.setOperator(
highlightCell.getOperator() != null ? highlightCell.getOperator().toString()
: subTypeEnum.getType());
if (highlightCell.getText() != null) {
rule.setValue(highlightCell.getText());
}
}
UniverStyle style = new UniverStyle();
CTDxf dxf = highlightCell.isSetDxfId() ? styles.getDxfAt((int) highlightCell.getDxfId()) : null;
if (dxf != null) {
CTFill ctFill = dxf.getFill();
if (ctFill != null) {
CTPatternFill patternFill = ctFill.getPatternFill();
if (patternFill != null) {
XSSFColor baColor = XSSFColor.from(patternFill.getBgColor());
if (baColor != null) {
UniverStyleColor bg = new UniverStyleColor();
bg.setRgb(rgb(baColor.getARGBHex()));
style.setBg(bg);
}
}
}
CTFont ctFont = dxf.getFont();
if (ctFont != null) {
XSSFColor fontColor = ctFont.sizeOfColorArray() > 0
? XSSFColor.from(ctFont.getColorArray(0))
: null;
if (fontColor != null) {
UniverStyleColor cl = new UniverStyleColor();
cl.setRgb(rgb(fontColor.getARGBHex()));
style.setCl(cl);
}
STUnderlineValues.Enum underlineType = ctFont.sizeOfUArray() == 1
? ctFont.getUArray(0).getVal()
: STUnderlineValues.NONE;
if (Objects.equals(underlineType, STUnderlineValues.SINGLE)) {
UniverStyleTextDecoration ul = new UniverStyleTextDecoration();
ul.setS(1);
style.setUl(ul);
}
boolean strike = ctFont.sizeOfStrikeArray() > 0 && ctFont.getStrikeArray(0).getVal();
if (strike) {
UniverStyleTextDecoration st = new UniverStyleTextDecoration();
st.setS(1);
style.setSt(st);
}
boolean isItalic = ctFont.sizeOfIArray() == 1 && ctFont.getIArray(0).getVal();
boolean isBold = ctFont.sizeOfBArray() == 1 && ctFont.getBArray(0).getVal();
style.setIt(isItalic ? 1 : 0);
style.setBl(isBold ? 1 : 0);
}
}
rule.setStyle(style);
resourceData.setRule(rule);
}
}
resourceData.setStopIfTrue(cfRule.getStopIfTrue());
if (resourceData.getRule() == null) {
continue;
}
formatList.add(resourceData);
}
}
formattingMap.put(sheetId, formatList);
}
private static void dataValidation(XSSFSheet sheet, String sheetId, String unitId,
Map<String, List<UniverResourceData>> dataValidationMap) {
List<UniverResourceData> dataValidationList = new ArrayList<>();
List<XSSFDataValidation> dataValidations = sheet.getDataValidations();
for (XSSFDataValidation dataValidation : dataValidations) {
UniverResourceData resourceData = new UniverResourceData();
List<UniverSheetRange> ranges = new ArrayList<>();
resourceData.setRanges(ranges);
resourceData.setUid(RandomUtil.randomString(10));
CellRangeAddressList addressList = dataValidation.getRegions();
for (CellRangeAddress address : addressList.getGenericChildren()) {
UniverSheetRange sheetRange = new UniverSheetRange();
sheetRange.setStartRow(address.getFirstRow());
sheetRange.setStartColumn(address.getFirstColumn());
sheetRange.setEndRow(address.getLastRow());
sheetRange.setEndColumn(address.getLastColumn());
sheetRange.setSheetId(sheetId);
sheetRange.setUnitId(unitId);
ranges.add(sheetRange);
}
DataValidationConstraint constraint = dataValidation.getValidationConstraint();
ValidationType validationType = ValidationType.getType(constraint.getValidationType());
resourceData.setType(validationType.getType());
operatorTypeEnum operator = Objects.equals(validationType, ValidationType.none) ? null
: operatorTypeEnum.getOperator(constraint.getOperator());
resourceData.setOperator(operator != null ? operator.getOperatorType() : null);
String value1 = constraint.getFormula1();
String value2 = constraint.getFormula2();
resourceData.setFormula1(value1 != null ? value1.replaceAll("\"", "") : value1);
resourceData.setFormula2(value2 != null ? value2.replaceAll("\"", "") : value2);
if (dataValidation.getShowErrorBox()) {
resourceData.setShowErrorMessage(true);
resourceData.setError(dataValidation.getErrorBoxTitle());
resourceData.setErrorStyle(Objects.equals(dataValidation.getErrorStyle(), 0) ? 1 : 2);
}
resourceData.setAllowBlank(dataValidation.getEmptyCellAllowed());
resourceData.setRenderMode(dataValidation.getSuppressDropDownArrow() ? null : 0);
dataValidationList.add(resourceData);
}
dataValidationMap.put(sheetId, dataValidationList);
}
private void filter(XSSFSheet sheet, String sheetId, String unitId, Map<String, UniverResourceData> filterMap) {
CTAutoFilter autoFilter = sheet.getCTWorksheet().getAutoFilter();
UniverResourceData data = new UniverResourceData();
if (autoFilter != null && StringUtil.isNotEmpty(autoFilter.getRef())) {
CellRangeAddress addresses = CellRangeAddress.valueOf(autoFilter.getRef());
UniverSheetRange ref = new UniverSheetRange();
ref.setStartRow(addresses.getFirstRow());
ref.setStartColumn(addresses.getFirstColumn());
ref.setEndRow(addresses.getLastRow());
ref.setEndColumn(addresses.getLastColumn());
data.setRef(ref);
List<Integer> cachedFilteredOut = new ArrayList<>();
// 隐藏行
for (int rowIndex = addresses.getFirstRow(); rowIndex <= addresses.getLastRow(); rowIndex++) {
XSSFRow row = sheet.getRow(rowIndex);
if (row != null && row.getZeroHeight()) {
cachedFilteredOut.add(rowIndex);
}
}
// 筛选条件
List<CTFilterColumn> filterColumnList = autoFilter.getFilterColumnList();
List<UniverFilters> filterColumns = new ArrayList<>();
for (CTFilterColumn filterColumn : filterColumnList) {
UniverFilters univerFilters = new UniverFilters();
univerFilters.setColId(filterColumn.getColId());
UniverCustomFilters customFilters = new UniverCustomFilters();
univerFilters.setCustomFilters(customFilters);
List<UniverCustomFilters> customFilterList = new ArrayList<>();
customFilters.setCustomFilters(customFilterList);
// poi方法
CTCustomFilters filters = filterColumn.getCustomFilters();
customFilters.setAnd(filters.getAnd() ? 1 : null);
List<CTCustomFilter> filterList = filters.getCustomFilterList();
for (CTCustomFilter filter : filterList) {
UniverCustomFilters univerCustomFilters = new UniverCustomFilters();
univerCustomFilters.setVal(filter.getVal());
univerCustomFilters
.setOperator(filter.getOperator() != null ? filter.getOperator().toString() : null);
customFilterList.add(univerCustomFilters);
}
filterColumns.add(univerFilters);
}
data.setFilterColumns(filterColumns);
data.setCachedFilteredOut(cachedFilteredOut);
filterMap.put(sheetId, data);
}
}
}

View File

@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.yunzhupaas</groupId>
<artifactId>yunzhupaas-datareport-univer-core</artifactId>
<version>5.2.0-RELEASE</version>
</parent>
<artifactId>yunzhupaas-datareport-univer-model</artifactId>
<dependencies>
<dependency>
<groupId>com.yunzhupaas</groupId>
<artifactId>yunzhupaas-common-core</artifactId>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4-runtime</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>${zxing.version}</version>
</dependency>
</dependencies>
<profiles>
</profiles>
</project>

View File

@@ -0,0 +1,11 @@
package com.yunzhupaas.enums;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/9/10 下午4:28
*/
public enum CellDataEnum {
text, chart, dataSource, parameter, expression
}

View File

@@ -0,0 +1,22 @@
package com.yunzhupaas.enums;
import java.util.Objects;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/11/26 下午12:06
*/
public enum FormatTypeEnum {
highlightCell, colorScale, iconSet, dataBar;
public static FormatTypeEnum getFormat(String name) {
for (FormatTypeEnum status : FormatTypeEnum.values()) {
if (Objects.equals(status.name(), name)) {
return status;
}
}
return FormatTypeEnum.highlightCell;
}
}

View File

@@ -0,0 +1,46 @@
package com.yunzhupaas.enums;
import lombok.Getter;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import java.util.Objects;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2025/1/6 下午6:00
*/
@Getter
public enum HorizontalEnum {
GENERAL(0, HorizontalAlignment.GENERAL),
LEFT(1, HorizontalAlignment.LEFT),
CENTER(2, HorizontalAlignment.CENTER),
RIGHT(3, HorizontalAlignment.RIGHT);
private Integer code;
private HorizontalAlignment horizontal;
HorizontalEnum(Integer code, HorizontalAlignment horizontal) {
this.code = code;
this.horizontal = horizontal;
}
public static HorizontalAlignment getHorizontalValue(Integer code) {
for (HorizontalEnum status : HorizontalEnum.values()) {
if (Objects.equals(status.getCode(), code)) {
return status.getHorizontal();
}
}
return HorizontalAlignment.GENERAL;
}
public static Integer getHorizontalCode(HorizontalAlignment horizontal) {
for (HorizontalEnum status : HorizontalEnum.values()) {
if (Objects.equals(status.getHorizontal(), horizontal)) {
return status.getCode();
}
}
return null;
}
}

View File

@@ -0,0 +1,11 @@
package com.yunzhupaas.enums;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/11/25 下午3:29
*/
public enum ImageEnum {
BASE64, URL
}

View File

@@ -0,0 +1,11 @@
package com.yunzhupaas.enums;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/12/4 下午4:40
*/
public enum OperatorEnum {
lessThan, greaterThan, greaterThanOrEqual, min, max, middle
}

View File

@@ -0,0 +1,56 @@
package com.yunzhupaas.enums;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/6/20 下午5:12
*/
public enum ResourceEnum {
/**
* 注释
*/
SHEET_THREAD_COMMENT_PLUGIN,
/**
* 工作表权限
*/
SHEET_WORKSHEET_PROTECTION_PLUGIN,
/**
* 工作表单元权限
*/
SHEET_WORKSHEET_PROTECTION_POINT_PLUGIN,
/**
* 区域保护
*/
SHEET_RANGE_PROTECTION_PLUGIN,
/**
* 图片
*/
SHEET_DRAWING_PLUGIN,
/**
* 条件格式
*/
SHEET_CONDITIONAL_FORMATTING_PLUGIN,
/**
* 超链接
*/
SHEET_HYPER_LINK_PLUGIN,
/**
* 名称定义
*/
SHEET_DEFINED_NAME_PLUGIN,
/**
* 数据验证
*/
SHEET_DATA_VALIDATION_PLUGIN,
/**
* 过滤器
*/
SHEET_FILTER_PLUGIN,
/**
* 授权服务
*/
SHEET_AuthzIoMockService_PLUGIN
}

View File

@@ -0,0 +1,43 @@
package com.yunzhupaas.enums;
import lombok.Getter;
import org.apache.poi.ss.usermodel.BorderStyle;
import java.util.Objects;
@Getter
public enum StyleTypeEnum {
NONE(0, BorderStyle.NONE),
THIN(1, BorderStyle.THIN),
HAIR(2, BorderStyle.HAIR),
DOTTED(3, BorderStyle.DOTTED),
DASHED(4, BorderStyle.DASHED),
DASH_DOT(5, BorderStyle.DASH_DOT),
DASH_DOT_DOT(6, BorderStyle.DASH_DOT_DOT),
DOUBLE(7, BorderStyle.DOUBLE),
MEDIUM(8, BorderStyle.MEDIUM),
MEDIUM_DASHED(9, BorderStyle.MEDIUM_DASHED),
MEDIUM_DASH_DOT(10, BorderStyle.MEDIUM_DASH_DOT),
MEDIUM_DASH_DOT_DOT(11, BorderStyle.MEDIUM_DASH_DOT_DOT),
SLANT_DASH_DOT(12, BorderStyle.SLANTED_DASH_DOT),
THICK(13, BorderStyle.THICK);
private Integer code;
private BorderStyle borderStyle;
StyleTypeEnum(Integer code, BorderStyle borderStyle) {
this.code = code;
this.borderStyle = borderStyle;
}
public static StyleTypeEnum getStyle(Integer code) {
for (StyleTypeEnum status : StyleTypeEnum.values()) {
if (Objects.equals(status.getCode(), code)) {
return status;
}
}
return null;
}
}

View File

@@ -0,0 +1,51 @@
package com.yunzhupaas.enums;
import lombok.Getter;
import java.util.Objects;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/11/27 上午11:46
*/
@Getter
public enum SubTypeEnum {
cellIs("number", "cellIs"),
equal("equal", "equal"),
notEqual("notEqual", "notEqual"),
top10("rank", "top10"),
uniqueValues("uniqueValues", "uniqueValues"),
duplicateValues("duplicateValues", "duplicateValues"),
containsText("containsText", "containsText"),
notContainsText("notContainsText", "notContainsText"),
beginsWith("beginsWith", "beginsWith"),
endsWith("endsWith", "endsWith"),
containsBlanks("containsBlanks", "containsBlanks"),
notContainsBlanks("notContainsBlanks", "notContainsBlanks"),
containsErrors("containsErrors", "containsErrors"),
notContainsErrors("notContainsErrors", "notContainsErrors"),
expression("formula", "expression"),
aboveAverage("average", "aboveAverage"),
timePeriod("timePeriod", "timePeriod"),
text("text", "text");
private String code;
private String type;
SubTypeEnum(String code, String type) {
this.code = code;
this.type = type;
}
public static SubTypeEnum getType(String type) {
for (SubTypeEnum status : SubTypeEnum.values()) {
if (Objects.equals(status.getType(), type)) {
return status;
}
}
return null;
}
}

View File

@@ -0,0 +1,45 @@
package com.yunzhupaas.enums;
import lombok.Getter;
import java.util.Objects;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/11/21 下午3:15
*/
@Getter
public enum UniverDataEnum {
// 汇总方式
none(0, ""),
select(1, "列表"),
group(2, "分组"),
summary(3, "汇总"),
// 填充方向
cellDirection(4, "portrait"),
cellDefault(5, "default"),
cellNone(6, "none"),
cellCustom(7, "custom"),
cellRoot(8, "root");
private Integer code;
private String name;
UniverDataEnum(Integer code, String name) {
this.code = code;
this.name = name;
}
public static UniverDataEnum getData(String name) {
for (UniverDataEnum status : UniverDataEnum.values()) {
if (Objects.equals(status.getName(), name)) {
return status;
}
}
return null;
}
}

View File

@@ -0,0 +1,52 @@
package com.yunzhupaas.enums;
import lombok.Getter;
import java.util.Objects;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/12/11 上午9:41
*/
@Getter
public enum ValidationType {
none("any", 0),
whole("whole", 1),
decimal("decimal", 2),
list("list", 3),
checkbox("checkbox", 3),
listMultiple("listMultiple", 3),
date("date", 4),
textLength("textLength", 6),
custom("custom", 7);
private String type;
private Integer validationType;
ValidationType(String type, Integer validationType) {
this.type = type;
this.validationType = validationType;
}
public static ValidationType getValidationType(String type) {
for (ValidationType status : ValidationType.values()) {
if (Objects.equals(status.getType(), type)) {
return status;
}
}
return ValidationType.none;
}
public static ValidationType getType(Integer validationType) {
for (ValidationType status : ValidationType.values()) {
if (Objects.equals(status.getValidationType(), validationType)) {
return status;
}
}
return ValidationType.none;
}
}

View File

@@ -0,0 +1,46 @@
package com.yunzhupaas.enums;
import lombok.Getter;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import java.util.Objects;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2025/1/6 下午5:54
*/
@Getter
public enum VerticalEnum {
TOP(1, VerticalAlignment.TOP),
CENTER(2, VerticalAlignment.CENTER),
BOTTOM(3, VerticalAlignment.BOTTOM);
private Integer code;
private VerticalAlignment vertical;
VerticalEnum(Integer code, VerticalAlignment vertical) {
this.code = code;
this.vertical = vertical;
}
public static VerticalAlignment getVerticalValue(Integer code) {
for (VerticalEnum status : VerticalEnum.values()) {
if (Objects.equals(status.getCode(), code)) {
return status.getVertical();
}
}
return null;
}
public static Integer getVerticalCode(VerticalAlignment vertical) {
for (VerticalEnum status : VerticalEnum.values()) {
if (Objects.equals(status.getVertical(), vertical)) {
return status.getCode();
}
}
return null;
}
}

View File

@@ -0,0 +1,51 @@
package com.yunzhupaas.enums;
import lombok.Getter;
import java.util.Objects;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/12/11 下午3:15
*/
@Getter
public enum operatorTypeEnum {
none("none", -1),
between("between", 0),
notBetween("notBetween", 1),
equal("equal", 2),
NOT_EQUAL("notEqual", 3),
greaterThan("greaterThan", 4),
lessThan("lessThan", 5),
greaterThanOrEqual("greaterThanOrEqual", 6),
lessThanOrEqual("lessThanOrEqual", 7);
private String operatorType;
private Integer operator;
operatorTypeEnum(String operatorType, Integer operator) {
this.operatorType = operatorType;
this.operator = operator;
}
public static operatorTypeEnum getOperator(String operatorType) {
for (operatorTypeEnum status : operatorTypeEnum.values()) {
if (Objects.equals(status.getOperatorType(), operatorType)) {
return status;
}
}
return operatorTypeEnum.none;
}
public static operatorTypeEnum getOperator(Integer operator) {
for (operatorTypeEnum status : operatorTypeEnum.values()) {
if (Objects.equals(status.getOperator(), operator)) {
return status;
}
}
return null;
}
}

View File

@@ -0,0 +1,20 @@
package com.yunzhupaas.model;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/11/26 上午11:31
*/
@Data
public class DataQuery {
private String sheet;
private String sheetName;
private List<Object> queryList = new ArrayList<>();
private List<DataSortModel> sortList = new ArrayList<>();
}

View File

@@ -0,0 +1,16 @@
package com.yunzhupaas.model;
import lombok.Data;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/12/6 下午2:12
*/
@Data
public class DataSortModel {
private String id;
private String vModel;
private String type;
}

View File

@@ -0,0 +1,25 @@
package com.yunzhupaas.univer.chart;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/9/10 下午1:29
*/
@Data
public class UniverChartField {
// 维度
private List<String> seriesNameField = new ArrayList<>();
// 系列
private List<String> classifyNameField = new ArrayList<>();
// 值
private List<List<String>> seriesDataField = new ArrayList<>();
// 最大值
private List<String> maxField = new ArrayList<>();
}

View File

@@ -0,0 +1,18 @@
package com.yunzhupaas.univer.chart;
import lombok.Data;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/9/10 下午1:26
*/
@Data
public class UniverChartModel {
private String unitId;
private String subUnitId;
private String drawingId;
private UniverChartField field = new UniverChartField();
private String source;
}

View File

@@ -0,0 +1,20 @@
package com.yunzhupaas.univer.data.cell;
import lombok.Data;
import java.io.Serializable;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/8/1 下午8:54
*/
@Data
public class UniverCell implements Serializable {
private String sheet;
private Integer row;
private Integer col;
private String drawingId;
private String domId;
}

View File

@@ -0,0 +1,45 @@
package com.yunzhupaas.univer.data.cell;
import com.yunzhupaas.enums.CellDataEnum;
import com.yunzhupaas.enums.UniverDataEnum;
import com.yunzhupaas.ureport.definition.value.AggregateType;
import lombok.Data;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverDataConfig {
// dataSource
private Integer col;
private Integer row;
private String sheet;
private String type = CellDataEnum.text.name();
private UniverDataConfig custom;
private String field;
// 0.无 1.列表 2. 分组 3.汇总
private Integer polymerizationType = 1;
// 汇总方式
private String summaryType = AggregateType.sum.name();
private String fillDirection = UniverDataEnum.cellDirection.getName();
private String leftParentCellType = UniverDataEnum.cellNone.getName();
private String leftParentCellCustomRowName;
private String leftParentCellCustomColName;
private String topParentCellType = UniverDataEnum.cellNone.getName();
private String topParentCellCustomRowName;
private String topParentCellCustomColName;
// echarts
private String drawingId;
private String unitId;
private String subUnitId;
private UniverDataConfig option;
private String classifyNameField;
private String seriesNameField;
private String seriesDataField;
private String maxField;
}

View File

@@ -0,0 +1,19 @@
package com.yunzhupaas.univer.data.custom;
import com.yunzhupaas.univer.data.cell.UniverDataConfig;
import lombok.Data;
import java.util.*;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/11/25 下午2:49
*/
@Data
public class UniverCustom {
private List<UniverDataConfig> cells = new ArrayList<>();
private Map<String, UniverDataConfig> floatEcharts = new HashMap<>();
private Map<String, UniverDataConfig> floatImages = new HashMap<>();
}

View File

@@ -0,0 +1,26 @@
package com.yunzhupaas.univer.data.resource;
import lombok.Data;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/11/21 上午11:06
*/
@Data
public class UniverConfig {
private String operator;
private UniverValue value;
private String iconType;
private String iconId;
private Integer index;
private String color;
private UniverValue min;
private UniverValue max;
private Boolean isGradient;
private String positiveColor;
private String nativeColor;
}

View File

@@ -0,0 +1,19 @@
package com.yunzhupaas.univer.data.resource;
import lombok.Data;
import java.util.List;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/10/18 下午1:58
*/
@Data
public class UniverCustomFilters {
private List<UniverCustomFilters> customFilters;
private String val;
private String operator;
private Integer and;
}

View File

@@ -0,0 +1,33 @@
package com.yunzhupaas.univer.data.resource;
import lombok.Data;
import java.io.Serializable;
/**
*
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverDrawing implements Serializable {
private String unitId;
private String subUnitId;
private String drawingId;
private Integer drawingType;
private String imageSourceType;
private String source;
// 悬浮图片
private UniverTransform sheetTransform;
// 单元格图片
private UniverTransform docTransform;
private Integer behindDoc;
private Integer layoutType;
private Integer wrapText;
private Integer distB;
private Integer distL;
private Integer distR;
private Integer distT;
}

View File

@@ -0,0 +1,15 @@
package com.yunzhupaas.univer.data.resource;
import lombok.Data;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/10/18 下午1:58
*/
@Data
public class UniverFilters {
private UniverCustomFilters customFilters;
private Long colId;
}

View File

@@ -0,0 +1,17 @@
package com.yunzhupaas.univer.data.resource;
import lombok.Data;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/24 下午1:31
*/
@Data
public class UniverNum {
private String i;
private Integer row;
private Integer col;
private String sheet;
}

View File

@@ -0,0 +1,17 @@
package com.yunzhupaas.univer.data.resource;
import lombok.Data;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/9/10 下午6:12
*/
@Data
public class UniverOffset {
private Integer column;
private Integer columnOffset;
private Integer row;
private Integer rowOffset;
}

View File

@@ -0,0 +1,20 @@
package com.yunzhupaas.univer.data.resource;
import lombok.Data;
import java.io.Serializable;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/22 上午11:41
*/
@Data
public class UniverRef implements Serializable {
private Integer count;
private String i;
private String pattern;
private String type;
}

View File

@@ -0,0 +1,23 @@
package com.yunzhupaas.univer.data.resource;
import com.yunzhupaas.univer.style.UniverStyle;
import lombok.Data;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/22 上午11:33
*/
@Data
public class UniverRule {
private String type;
private String subType;
private String operator;
private UniverStyle style;
private Object value;
private Boolean isShowValue;
private Object config;
private Boolean isPercent;
private Boolean isBottom;
}

View File

@@ -0,0 +1,34 @@
package com.yunzhupaas.univer.data.resource;
import lombok.Data;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/9/10 下午6:09
*/
@Data
public class UniverTransform {
// 悬浮图片
private Boolean flipY;
private Boolean flipX;
private Integer skewX;
private Integer skewY;
private UniverOffset from;
private UniverOffset to;
// 单元格图片
private Integer relativeFrom;
private Integer posOffset;
private UniverTransform size;
private UniverTransform positionH;
private UniverTransform positionV;
// 图片公共
private Integer angle;
private Integer left;
private Integer top;
private Integer width;
private Integer height;
}

View File

@@ -0,0 +1,15 @@
package com.yunzhupaas.univer.data.resource;
import lombok.Data;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/11/21 上午11:09
*/
@Data
public class UniverValue {
private Object value;
private String type;
}

View File

@@ -0,0 +1,30 @@
package com.yunzhupaas.univer.model;
import lombok.Data;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/7/4 下午4:12
*/
@Data
public class UniverPreview {
private String cells;
private String snapshot;
private String queryList;
private String chartData;
private String fullName;
private String versionId;
private Integer allowExport;
private Integer allowPrint;
}

View File

@@ -0,0 +1,37 @@
package com.yunzhupaas.univer.model;
import com.yunzhupaas.univer.resources.UniverResource;
import com.yunzhupaas.univer.sheet.UniverSheet;
import com.yunzhupaas.univer.style.UniverStyle;
import lombok.Data;
import java.io.Serializable;
import java.util.*;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverWorkBook implements Serializable {
private String id;
private Integer rev;
private String name;
/**
* Univer版本
*/
private String appVersion = "0.4.1";
/**
* Univer语言
*/
private String locale = "zhCN";
/**
* 样式列表
*/
private Map<String, UniverStyle> styles = new HashMap<>();
private List<String> sheetOrder = new ArrayList<>();
private Map<String, UniverSheet> sheets = new HashMap<>();
private List<UniverResource> resources = new ArrayList<>();
}

View File

@@ -0,0 +1,24 @@
package com.yunzhupaas.univer.properties;
import lombok.Data;
import java.util.List;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/11/5 下午3:58
*/
@Data
public class UniverBody {
private String dataStream;
private List<UniverBodyConfig> textRuns;
private List<UniverBodyConfig> tables;
private List<UniverBodyConfig> sectionBreaks;
private List<UniverBodyConfig> paragraphs;
private List<UniverBodyConfig> customDecorations;
private List<UniverBodyConfig> customBlocks;
private List<UniverBodyConfig> customRanges;
private UniverBodyConfig settings;
}

View File

@@ -0,0 +1,58 @@
package com.yunzhupaas.univer.properties;
import com.yunzhupaas.univer.style.UniverStyle;
import lombok.Data;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/11/5 下午4:08
*/
@Data
public class UniverBodyConfig {
private Integer startIndex;
private UniverBodyConfig paragraphStyle;
private Integer horizontalAlign;
private Integer rangeType;
private String rangeId;
private String url;
private UniverBodyConfig properties;
private Integer ed;
private String sId;
private String id;
private Integer st;
private UniverStyle ts;
private Integer endIndex;
private String tableId;
private Integer charSpace;
private Integer paddingEnd;
private Integer width;
private String defaultFooterId;
private String defaultHeaderId;
private String evenPageFooterId;
private String evenPageHeaderId;
private String firstPageFooterId;
private String firstPageHeaderId;
private Integer linePitch;
private Integer marginBottom;
private Integer marginFooter;
private Integer marginHeader;
private Integer marginLeft;
private Integer marginRight;
private Integer marginTop;
private Integer pageNumberStart;
private Integer useFirstPageHeaderFooter;
private Integer zoomRatio;
private String blockId;
private Integer blockType;
private Integer type;
private Boolean wholeEntity;
}

View File

@@ -0,0 +1,43 @@
package com.yunzhupaas.univer.properties;
import com.yunzhupaas.univer.style.UniverStyle;
import lombok.Data;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/11/5 下午3:55
*/
@Data
public class UniverDocumentStyle {
private Integer autoHyphenation;
private Integer characterSpacingControl;
private Integer consecutiveHyphenLimit;
private String defaultFooterId;
private String defaultHeaderId;
private Integer defaultTabStop;
private Integer doNotHyphenateCaps;
private Integer documentFlavor;
private Integer evenAndOddHeaders;
private String evenPageFooterId;
private String evenPageHeaderId;
private String firstPageFooterId;
private String firstPageHeaderId;
private Integer hyphenationZone;
private Integer marginBottom;
private Integer marginFooter;
private Integer marginHeader;
private Integer marginLeft;
private Integer marginRight;
private Integer marginTop;
private Integer pageNumberStart;
private Integer pageOrient;
private UniverDocumentStyleConfig pageSize;
private Integer paragraphLineGapDefault;
private UniverDocumentStyleConfig renderConfig;
private Boolean spaceWidthEastAsian;
private UniverStyle textStyle;
private Boolean useFirstPageHeaderFooter;
}

View File

@@ -0,0 +1,21 @@
package com.yunzhupaas.univer.properties;
import lombok.Data;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/11/5 下午3:55
*/
@Data
public class UniverDocumentStyleConfig {
private Integer width;
private Integer height;
private Integer background;
private Integer horizontalAlign;
private Integer verticalAlign;
private Integer centerAngle;
private Integer vertexAngle;
private Integer wrapStrategy;
}

View File

@@ -0,0 +1,33 @@
package com.yunzhupaas.univer.properties;
import com.yunzhupaas.univer.data.resource.UniverDrawing;
import lombok.Data;
import java.util.List;
import java.util.Map;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/11/5 下午5:54
*/
@Data
public class UniverProperties {
private UniverBody body;
private Boolean disabled;
private UniverDocumentStyle documentStyle;
private Map<String, UniverDrawing> drawings;
private List<String> drawingsOrder;
private Map<String, Object> footers;
private List<String> headerFooterDrawingsOrder;
private Map<String, Object> headers;
private String id;
private Map<String, Object> lists;
private String locale;
private Map<String, Object> resources;
private Integer rev;
private UniverBodyConfig settings;
private Map<String, Object> tableSource;
private String title;
}

View File

@@ -0,0 +1,16 @@
package com.yunzhupaas.univer.resources;
import lombok.Data;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverResource {
private String id;
private String name;
private String data;
}

View File

@@ -0,0 +1,67 @@
package com.yunzhupaas.univer.resources;
import com.yunzhupaas.univer.data.resource.*;
import com.yunzhupaas.univer.sheet.UniverSheetRange;
import lombok.Data;
import java.util.List;
import java.util.Map;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/22 下午2:10
*/
@Data
public class UniverResourceData {
// SHEET_DATA_VALIDATION
private String uid;
private String operator;
private String formula1;
private String formula2;
private String error;
private Integer renderMode;
private Boolean allowBlank;
private Integer errorStyle;
private Boolean showErrorMessage;
// SHEET_NUMFMT_PLUGIN
private Map<String, Map<Integer, Map<Integer, UniverNum>>> model;
private List<UniverRef> refModel;
private List<UniverNum> numModel;
// SHEET_CONDITIONAL_FORMATTING_PLUGIN
private String cfId;
private UniverRule rule;
private Boolean stopIfTrue;
// SHEET_CONDITIONAL_FORMATTING_PLUGIN、SHEET_DATA_VALIDATION、SHEET_RANGE_PROTECTION
private List<UniverSheetRange> ranges;
// SHEET_NUMFMT_PLUGIN、SHEET_DATA_VALIDATION
private String type;
// SHEET_DEFINED_NAME_PLUGIN
private String id;
private String name;
private String formulaOrRefString;
private String comment;
private String localSheetId;
// SHEET_RANGE_PROTECTION
private String permissionId;
private String unitType;
private String unitId;
private String subUnitId;
// SHEET_DRAWING_PLUGIN
private List<String> order;
private Map<String, UniverDrawing> data;
// SHEET_FILTER_PLUGIN
private UniverSheetRange ref;
private List<UniverFilters> filterColumns;
private List<Integer> cachedFilteredOut;
}

View File

@@ -0,0 +1,38 @@
package com.yunzhupaas.univer.sheet;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverSheet implements Serializable {
private String id;
private String name;
private String tabColor;
private Integer hidden;
private UniverSheetFreeze freeze;
private Integer rowCount;
private Integer columnCount;
private Integer zoomRatio;
private Integer scrollTop;
private Integer scrollLeft;
private Integer defaultColumnWidth;
private Integer defaultRowHeight;
private List<UniverSheetRange> mergeData;
private Map<Integer, Map<Integer, UniverSheetCellData>> cellData;
private Map<Integer, UniverSheetRowData> rowData;
private Map<Integer, UniverSheetColumnData> columnData;
private UniverSheetRowHeader rowHeader;
private UniverSheetColumnHeader columnHeader;
private Integer showGridlines;
private List<String> selections;
private Integer rightToLeft;
}

View File

@@ -0,0 +1,17 @@
package com.yunzhupaas.univer.sheet;
import lombok.Data;
import java.io.Serializable;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverSheetCell implements Serializable {
private Integer row;
private Integer column;
}

View File

@@ -0,0 +1,45 @@
package com.yunzhupaas.univer.sheet;
import lombok.Data;
import java.io.Serializable;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverSheetCellData implements Serializable {
/**
* The unique key, a random string, is used for the plug-in to associate the
* cell. When the cell information changes,
* the plug-in does not need to change the data, reducing the pressure on the
* back-end interface id?: string.
*/
private Object p;
/**
* style id
* UniverStyle | String
*/
private Object s;
/**
* Origin value
* String | Integer | Boolean
*/
private Object v;
// Usually the type is automatically determined based on the data, or the user
// directly specifies
// 1 string, 2 number, 3 boolean, 4 force string, green icon, set null for cell
// clear all
private Integer t;
/**
* Raw formula string. For example `=SUM(A1:B4)`.
*/
private String f;
}

View File

@@ -0,0 +1,23 @@
package com.yunzhupaas.univer.sheet;
import lombok.Data;
import java.io.Serializable;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverSheetColumnData implements Serializable {
/**
* width
*/
private Integer w;
/**
* hidden
*/
private Integer hd;
}

View File

@@ -0,0 +1,17 @@
package com.yunzhupaas.univer.sheet;
import lombok.Data;
import java.io.Serializable;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverSheetColumnHeader implements Serializable {
private Integer height;
private Integer hidden;
}

View File

@@ -0,0 +1,19 @@
package com.yunzhupaas.univer.sheet;
import lombok.Data;
import java.io.Serializable;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverSheetFreeze implements Serializable {
private Integer xSplit = 0;
private Integer ySplit = 0;
private Integer startRow = -1;
private Integer startColumn = -1;
}

View File

@@ -0,0 +1,47 @@
package com.yunzhupaas.univer.sheet;
import lombok.Data;
import java.io.Serializable;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverSheetRange implements Serializable {
/**
* The start row (inclusive) of the range
* startRow
*/
private Integer startRow;
/**
* The end row (exclusive) of the range
* endRow
*/
private Integer endRow;
/**
* The start column (inclusive) of the range
* startColumn
*/
private Integer startColumn;
/**
* The end column (exclusive) of the range
* endColumn
*/
private Integer endColumn;
private Integer rangeType;
private Integer startAbsoluteRefType;
private Integer endAbsoluteRefType;
private String unitId;
private String sheetId;
}

View File

@@ -0,0 +1,32 @@
package com.yunzhupaas.univer.sheet;
import lombok.Data;
import java.io.Serializable;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverSheetRowData implements Serializable {
/**
* height in pixel
*/
private Integer h;
/**
* is current row self-adaptive to its content, use `ah` to set row height when
* true, else use `h`.
*/
private Integer ia; // pre name `isAutoHeight`
/**
* auto height
*/
private Integer ah;
/**
* hidden
*/
private Integer hd;
}

View File

@@ -0,0 +1,17 @@
package com.yunzhupaas.univer.sheet;
import lombok.Data;
import java.io.Serializable;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverSheetRowHeader implements Serializable {
private Integer width;
private Integer hidden;
}

View File

@@ -0,0 +1,98 @@
package com.yunzhupaas.univer.style;
import lombok.Data;
import java.io.Serializable;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverStyle implements Serializable {
/**
* fontFamily
*/
private String ff;
/**
* fontSize
* <p>
* pt
*/
private Integer fs;
/**
* italic
* 0: false
* 1: true
*/
private Integer it;
/**
* bold
* 0: false
* 1: true
*/
private Integer bl;
/**
* underline
*/
private UniverStyleTextDecoration ul;
/**
* strikethrough
*/
private UniverStyleTextDecoration st;
/**
* overline
*/
private UniverStyleTextDecoration ol;
/**
* background
*/
private UniverStyleColor bg;
/**
* border
*/
private UniverStyleBorder bd;
/**
* foreground
*/
private UniverStyleColor cl;
/**
* (1.正常 2.Subscript 下标 3.Superscript上标 )
*/
private Integer va;
/**
* textRotation
*/
private UniverStyleTextRotation tr;
/**
* textDirection
*/
private Integer td;
/**
* horizontalAlignment
*/
private Integer ht;
/**
* verticalAlignment
*/
private Integer vt;
/**
* wrapStrategy
*/
private Integer tb;
/**
* padding
*/
private UniverStylePadding pd;
/**
* dataFormat
*/
private UniverStylePattern n;
}

View File

@@ -0,0 +1,35 @@
package com.yunzhupaas.univer.style;
import lombok.Data;
import java.io.Serializable;
/**
* Style properties of top, bottom, left and right border
* TLBR = 'tlbr', //START_TOP_LEFT_END_BOTTOM_RIGHT
* TLBC = 'tlbc', // START_TOP_LEFT_END_BOTTOM_CENTER
* TLMR = 'tlmr', // START_TOP_LEFT_END_MIDDLE_RIGHT
* BLTR = 'bltr', // START_BOTTOM_LEFT_END_TOP_RIGHT
* MLTR = 'mltr', // START_MIDDLE_LEFT_END_TOP_RIGHT
* BCTR = 'bctr', // START_BOTTOM_CENTER_END_TOP_RIGHT
*
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverStyleBorder implements Serializable {
private UniverStyleBorderStyle t;
private UniverStyleBorderStyle r;
private UniverStyleBorderStyle b;
private UniverStyleBorderStyle l;
private UniverStyleBorderStyle tl_br;
private UniverStyleBorderStyle tl_bc;
private UniverStyleBorderStyle tl_mr;
private UniverStyleBorderStyle bl_tr;
private UniverStyleBorderStyle ml_tr;
private UniverStyleBorderStyle bc_tr;
}

View File

@@ -0,0 +1,17 @@
package com.yunzhupaas.univer.style;
import lombok.Data;
import java.io.Serializable;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverStyleBorderStyle implements Serializable {
private Integer s;
private UniverStyleColor cl;
}

View File

@@ -0,0 +1,17 @@
package com.yunzhupaas.univer.style;
import lombok.Data;
import java.io.Serializable;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverStyleColor implements Serializable {
private String rgb;
private Object th;
}

View File

@@ -0,0 +1,19 @@
package com.yunzhupaas.univer.style;
import lombok.Data;
import java.io.Serializable;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverStylePadding implements Serializable {
private Integer t;
private Integer r;
private Integer b;
private Integer l;
}

View File

@@ -0,0 +1,14 @@
package com.yunzhupaas.univer.style;
import lombok.Data;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/9/6 上午9:00
*/
@Data
public class UniverStylePattern {
private String pattern;
}

View File

@@ -0,0 +1,24 @@
package com.yunzhupaas.univer.style;
import lombok.Data;
import java.io.Serializable;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverStyleTextDecoration implements Serializable {
// show
private Integer s;
// color is follow the font color. the default value is TRUE, it's also TRUE if
// it is undefined. the cl has no effect when `c` is TRUE.
private Integer c;
// color
private UniverStyleColor cl;
// lineType
private Object t;
}

View File

@@ -0,0 +1,25 @@
package com.yunzhupaas.univer.style;
import lombok.Data;
import java.io.Serializable;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/5/11 下午4:35
*/
@Data
public class UniverStyleTextRotation implements Serializable {
/**
* angle
*/
private int a;
/**
* vertical
* true : 1
* false : 0
*/
private int v;
}

View File

@@ -0,0 +1,15 @@
package com.yunzhupaas.ureport;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Range {
private int start = -1;
private int end;
}

View File

@@ -0,0 +1,15 @@
package com.yunzhupaas.ureport.build;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
import java.util.Map;
@Setter
@Getter
public class BindData {
private Object value;
private List<Map<String, Object>> dataList;
}

View File

@@ -0,0 +1,169 @@
package com.yunzhupaas.ureport.build;
import com.yunzhupaas.ureport.definition.value.SimpleValue;
import com.yunzhupaas.ureport.definition.value.Value;
import com.yunzhupaas.ureport.expression.util.ElCompute;
import com.yunzhupaas.ureport.model.Cell;
import com.yunzhupaas.ureport.model.Column;
import com.yunzhupaas.ureport.model.Report;
import com.yunzhupaas.ureport.model.Row;
import lombok.Getter;
import lombok.Setter;
import java.util.*;
@Getter
@Setter
public class Context {
private Report report;
private Cell rootCell;
private ReportBuilder reportBuilder;
private Map<String, Dataset> datasetMap;
private Map<String, Object> variableMap = new HashMap<>();
private Map<Integer, List<Row>> currentPageRowsMap = new HashMap<>();
private Map<Row, Map<Column, Cell>> blankCellsMap = new HashMap<>();
private Map<String, List<Cell>> unprocessedCellsMap = new HashMap<>();
public Context(ReportBuilder reportBuilder, Report report, Map<String, Dataset> datasetMap) {
this.reportBuilder = reportBuilder;
this.report = report;
report.setContext(this);
this.datasetMap = datasetMap;
Map<String, List<Cell>> cellsMap = report.getCellsMap();
for (String key : cellsMap.keySet()) {
if (key.equals(report.getRootCell().getName())) {
continue;
}
List<Cell> list = new ArrayList<>();
list.addAll(cellsMap.get(key));
unprocessedCellsMap.put(key, list);
}
this.rootCell = new Cell();
this.rootCell.setName("ROOT");
}
public List<Cell> nextUnprocessedCells() {
if (unprocessedCellsMap.size() == 0) {
return null;
}
List<Cell> targetCellsList = null;
String targetCellName = null;
Set<String> keySet = unprocessedCellsMap.keySet();
for (String cellName : keySet) {
List<Cell> cells = unprocessedCellsMap.get(cellName);
Cell cell = cells.get(0);
Value value = cell.getValue();
Cell leftParent = cell.getLeftParentCell();
Cell topParent = cell.getTopParentCell();
if ((leftParent == null || leftParent.isProcessed()) && (topParent == null || topParent.isProcessed())) {
targetCellsList = cells;
targetCellName = cellName;
break;
}
if (value instanceof SimpleValue) {
targetCellsList = cells;
targetCellName = cellName;
break;
}
}
unprocessedCellsMap.remove(targetCellName);
return targetCellsList;
}
public List<BindData> buildCellData(Cell cell) {
return DataCompute.buildCellData(cell, this);
}
public void addReportCell(Cell newCell) {
report.addCell(newCell);
}
public void addCell(Cell newCell) {
addReportCell(newCell);
addUnprocessedCell(newCell);
}
public void addUnprocessedCell(Cell cell) {
String cellName = cell.getName();
List<Cell> cells = null;
if (unprocessedCellsMap.containsKey(cellName)) {
cells = unprocessedCellsMap.get(cellName);
} else {
cells = new ArrayList<>();
unprocessedCellsMap.put(cellName, cells);
}
int lastIdx = report.findSameLeftCell(cells, cell, 0);
if (lastIdx > -1 && lastIdx < cells.size() - 1) {
cells.add(lastIdx + 1, cell);
} else {
cells.add(cell);
}
}
public List<Map<String, Object>> getDatasetData(String name) {
List<Map<String, Object>> list = new ArrayList<>();
if (datasetMap.containsKey(name)) {
list.addAll(datasetMap.get(name).getData());
}
return list;
}
public Row getRow(int rowNumber) {
return report.getRow(rowNumber);
}
public Column getColumn(int columnNumber) {
return report.getColumn(columnNumber);
}
public void addBlankCell(Cell cell) {
cell.setBlankCell(true);
Row row = cell.getRow();
Column column = cell.getColumn();
Map<Column, Cell> cellMap = blankCellsMap.get(row);
if (cellMap == null) {
cellMap = new HashMap<>();
blankCellsMap.put(row, cellMap);
}
cellMap.put(column, cell);
addReportCell(cell);
}
public Cell getBlankCell(Row row, Column column) {
Map<Column, Cell> colCellMap = blankCellsMap.get(row);
if (colCellMap == null) {
return null;
}
Cell targetCell = colCellMap.get(column);
return targetCell;
}
public void removeBlankCell(Cell blankCell) {
Row row = blankCell.getRow();
Column col = blankCell.getColumn();
Map<Column, Cell> colCellMap = blankCellsMap.get(row);
colCellMap.remove(col);
}
public void putVariable(String key, Object value) {
variableMap.put(key, value);
}
public Object evalExpr(String expression) {
return new ElCompute().doCompute(expression);
}
public boolean isCellPocessed(String cellName) {
return !unprocessedCellsMap.containsKey(cellName);
}
public List<Row> getCurrentPageRows(int index) {
return currentPageRowsMap.get(index);
}
public Object getVariable(String key) {
return variableMap.get(key);
}
}

View File

@@ -0,0 +1,32 @@
package com.yunzhupaas.ureport.build;
import com.google.common.collect.ImmutableMap;
import com.yunzhupaas.ureport.compute.DatasetValueCompute;
import com.yunzhupaas.ureport.compute.SimpleValueCompute;
import com.yunzhupaas.ureport.compute.ValueCompute;
import com.yunzhupaas.ureport.definition.value.Value;
import com.yunzhupaas.ureport.definition.value.ValueType;
import com.yunzhupaas.ureport.model.Cell;
import lombok.Data;
import java.util.List;
import java.util.Map;
@Data
public class DataCompute {
@SuppressWarnings("null")
private static Map<String, ValueCompute> valueComputesMap = ImmutableMap.of(
ValueType.simple.name(), new SimpleValueCompute(),
ValueType.dataset.name(), new DatasetValueCompute());
public static List<BindData> buildCellData(Cell cell, Context context) {
Value value = cell.getValue();
ValueCompute valueCompute = valueComputesMap.get(value.getType());
if (valueCompute == null) {
valueCompute = valueComputesMap.get(ValueType.simple.name());
}
List<BindData> list = valueCompute.compute(cell, context);
return list;
}
}

View File

@@ -0,0 +1,14 @@
package com.yunzhupaas.ureport.build;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
import java.util.Map;
@Setter
@Getter
public class Dataset {
private String name;
private List<Map<String, Object>> data;
}

View File

@@ -0,0 +1,32 @@
package com.yunzhupaas.ureport.build;
import com.google.common.collect.ImmutableMap;
import com.yunzhupaas.ureport.build.aggregate.*;
import com.yunzhupaas.ureport.definition.value.AggregateType;
import com.yunzhupaas.ureport.definition.value.DatasetValue;
import com.yunzhupaas.ureport.model.Cell;
import java.util.List;
import java.util.Map;
public class DatasetUtils {
private static Map<AggregateType, Aggregate> aggregates = ImmutableMap.of(
AggregateType.group, new GroupAggregate(),
AggregateType.select, new SelectAggregate(),
AggregateType.avg, new AvgAggregate(),
AggregateType.count, new CountAggregate(),
AggregateType.sum, new SumAggregate(),
AggregateType.min, new MinAggregate(),
AggregateType.max, new MaxAggregate(),
AggregateType.none, new NoneAggregate());
public static List<BindData> computeDatasetExpression(DatasetValue datasetValue, Cell cell, Context context) {
AggregateType type = datasetValue.getAggregate();
Aggregate aggregate = aggregates.get(type);
if (aggregate == null) {
aggregate = aggregates.get(AggregateType.select);
}
return aggregate.aggregate(datasetValue, cell, context);
}
}

View File

@@ -0,0 +1,60 @@
package com.yunzhupaas.ureport.build;
import com.yunzhupaas.ureport.cell.CellBuilder;
import com.yunzhupaas.ureport.cell.down.DownExpandBuilder;
import com.yunzhupaas.ureport.cell.none.NoneExpandBuilder;
import com.yunzhupaas.ureport.cell.right.RightExpandBuilder;
import com.yunzhupaas.ureport.definition.Expand;
import com.yunzhupaas.ureport.definition.ReportDefinition;
import com.yunzhupaas.ureport.model.Cell;
import com.yunzhupaas.ureport.model.Report;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ReportBuilder {
private Map<Expand, CellBuilder> cellBuildersMap = new HashMap<>();
public ReportBuilder() {
cellBuildersMap.put(Expand.Down, new DownExpandBuilder());
cellBuildersMap.put(Expand.None, new NoneExpandBuilder());
cellBuildersMap.put(Expand.Right, new RightExpandBuilder());
}
public Report buildReport(ReportDefinition reportDefinition) {
Report report = reportDefinition.newReport();
Map<String, Dataset> datasetMap = reportDefinition.getDatasetMap();
Context context = new Context(this, report, datasetMap);
List<Cell> cells = new ArrayList<>();
cells.add(report.getRootCell());
do {
buildCell(context, cells);
cells = context.nextUnprocessedCells();
} while (cells != null);
return report;
}
public void buildCell(Context context, List<Cell> cells) {
if (cells == null) {
cells = context.nextUnprocessedCells();
}
if (cells == null) {
return;
}
CellBuilder noneExpandBuilder = new NoneExpandBuilder();
for (Cell cell : cells) {
List<BindData> dataList = context.buildCellData(cell);
cell.setProcessed(true);
int size = dataList.size();
if (size == 1) {
noneExpandBuilder.buildCell(dataList, cell, context);
} else if (size > 1) {
CellBuilder cellBuilder = cellBuildersMap.get(cell.getExpand());
cellBuilder.buildCell(dataList, cell, context);
}
}
}
}

View File

@@ -0,0 +1,18 @@
package com.yunzhupaas.ureport.build.aggregate;
import com.yunzhupaas.ureport.build.BindData;
import com.yunzhupaas.ureport.build.Context;
import com.yunzhupaas.ureport.definition.value.DatasetValue;
import com.yunzhupaas.ureport.model.Cell;
import java.util.*;
/**
* @author
* @since 2016年12月21日
*/
public abstract class Aggregate {
public abstract List<BindData> aggregate(DatasetValue expr, Cell cell, Context context);
}

View File

@@ -0,0 +1,40 @@
package com.yunzhupaas.ureport.build.aggregate;
import com.yunzhupaas.ureport.build.BindData;
import com.yunzhupaas.ureport.build.Context;
import com.yunzhupaas.ureport.definition.value.DatasetValue;
import com.yunzhupaas.ureport.model.Cell;
import com.yunzhupaas.ureport.utils.DataUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author
* @since 1月20日
*/
public class AvgAggregate extends Aggregate {
@Override
public List<BindData> aggregate(DatasetValue expr, Cell cell, Context context) {
List<Map<String, Object>> objList = DataUtils.fetchData(cell, context, expr.getDatasetName());
List<BindData> list = doAggregate(expr, cell, context, objList);
return list;
}
protected List<BindData> doAggregate(DatasetValue expr, Cell cell, Context context,
List<Map<String, Object>> objList) {
List<BigDecimal> bindDataList = DataUtils.dataList(expr, objList);
BigDecimal result = bindDataList.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
if (!objList.isEmpty()) {
result = result.divide(new BigDecimal(objList.size()), RoundingMode.HALF_UP);
}
BindData bindData = new BindData();
bindData.setValue(result.doubleValue());
List<BindData> list = new ArrayList<>();
list.add(bindData);
return list;
}
}

View File

@@ -0,0 +1,29 @@
package com.yunzhupaas.ureport.build.aggregate;
import com.yunzhupaas.ureport.build.BindData;
import com.yunzhupaas.ureport.build.Context;
import com.yunzhupaas.ureport.definition.value.DatasetValue;
import com.yunzhupaas.ureport.model.Cell;
import com.yunzhupaas.ureport.utils.DataUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class CountAggregate extends Aggregate {
@Override
public List<BindData> aggregate(DatasetValue expr, Cell cell, Context context) {
List<Map<String, Object>> objList = DataUtils.fetchData(cell, context, expr.getDatasetName());
List<BindData> list = doAggregate(expr, cell, context, objList);
return list;
}
protected List<BindData> doAggregate(DatasetValue expr, Cell cell, Context context,
List<Map<String, Object>> objList) {
BindData bindData = new BindData();
bindData.setValue(objList.size());
List<BindData> list = new ArrayList<>();
list.add(bindData);
return list;
}
}

View File

@@ -0,0 +1,52 @@
package com.yunzhupaas.ureport.build.aggregate;
import com.yunzhupaas.ureport.build.BindData;
import com.yunzhupaas.ureport.build.Context;
import com.yunzhupaas.ureport.definition.value.DatasetValue;
import com.yunzhupaas.ureport.model.Cell;
import com.yunzhupaas.ureport.utils.DataUtils;
import java.text.Collator;
import java.util.*;
public class GroupAggregate extends Aggregate {
@Override
public List<BindData> aggregate(DatasetValue expr, Cell cell, Context context) {
List<Map<String, Object>> objList = DataUtils.fetchData(cell, context, expr.getDatasetName());
List<BindData> list = doAggregate(expr, cell, context, objList);
return list;
}
protected List<BindData> doAggregate(DatasetValue expr, Cell cell, Context context,
List<Map<String, Object>> objList) {
List<BindData> list = new ArrayList<>();
String property = expr.getProperty();
Map<Object, List<Map<String, Object>>> map = new LinkedHashMap<>();
for (Map<String, Object> obj : objList) {
List<Map<String, Object>> rowList = new ArrayList<>();
Object value = obj.get(property) != null ? obj.get(property) : "";
if (map.containsKey(value)) {
rowList = map.get(value);
}
rowList.add(obj);
map.put(value, rowList);
}
for (Object key : map.keySet()) {
BindData bindData = new BindData();
bindData.setValue(key);
bindData.setDataList(map.get(key));
list.add(bindData);
}
if (list.size() == 0) {
List<Map<String, Object>> rowList = new ArrayList<>();
rowList.add(new HashMap<>());
BindData bindData = new BindData();
bindData.setValue("");
bindData.setDataList(rowList);
list.add(bindData);
}
Collator collator = Collator.getInstance(Locale.CHINA);
list.sort(Comparator.comparing(BindData::getValue, collator));
return list;
}
}

View File

@@ -0,0 +1,37 @@
package com.yunzhupaas.ureport.build.aggregate;
import com.yunzhupaas.ureport.build.BindData;
import com.yunzhupaas.ureport.build.Context;
import com.yunzhupaas.ureport.definition.value.DatasetValue;
import com.yunzhupaas.ureport.model.Cell;
import com.yunzhupaas.ureport.utils.DataUtils;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class MaxAggregate extends Aggregate {
@Override
public List<BindData> aggregate(DatasetValue expr, Cell cell, Context context) {
List<Map<String, Object>> objList = DataUtils.fetchData(cell, context, expr.getDatasetName());
List<BindData> list = doAggregate(expr, cell, context, objList);
return list;
}
protected List<BindData> doAggregate(DatasetValue expr, Cell cell, Context context,
List<Map<String, Object>> objList) {
List<BigDecimal> bindDataList = DataUtils.dataList(expr, objList);
if (bindDataList.isEmpty()) {
bindDataList.add(new BigDecimal(0));
}
BigDecimal result = bindDataList.stream().reduce(bindDataList.get(0), BigDecimal::max);
BindData bindData = new BindData();
bindData.setValue(result.doubleValue());
List<BindData> list = new ArrayList<>();
list.add(bindData);
return list;
}
}

View File

@@ -0,0 +1,37 @@
package com.yunzhupaas.ureport.build.aggregate;
import com.yunzhupaas.ureport.build.BindData;
import com.yunzhupaas.ureport.build.Context;
import com.yunzhupaas.ureport.definition.value.DatasetValue;
import com.yunzhupaas.ureport.model.Cell;
import com.yunzhupaas.ureport.utils.DataUtils;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class MinAggregate extends Aggregate {
@Override
public List<BindData> aggregate(DatasetValue expr, Cell cell, Context context) {
List<Map<String, Object>> objList = DataUtils.fetchData(cell, context, expr.getDatasetName());
List<BindData> list = doAggregate(expr, cell, context, objList);
return list;
}
protected List<BindData> doAggregate(DatasetValue expr, Cell cell, Context context,
List<Map<String, Object>> objList) {
List<BigDecimal> bindDataList = DataUtils.dataList(expr, objList);
if (bindDataList.isEmpty()) {
bindDataList.add(new BigDecimal(0));
}
BigDecimal result = bindDataList.stream().reduce(bindDataList.get(0), BigDecimal::min);
BindData bindData = new BindData();
bindData.setValue(result.doubleValue());
List<BindData> list = new ArrayList<>();
list.add(bindData);
return list;
}
}

View File

@@ -0,0 +1,44 @@
package com.yunzhupaas.ureport.build.aggregate;
import com.yunzhupaas.ureport.build.BindData;
import com.yunzhupaas.ureport.build.Context;
import com.yunzhupaas.ureport.definition.value.DatasetValue;
import com.yunzhupaas.ureport.model.Cell;
import com.yunzhupaas.ureport.utils.DataUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author :云筑产品开发平台组
* @version: V3.1.0
* @copyright 深圳市乐程软件有限公司
* @date 2024/9/13 下午5:17
*/
public class NoneAggregate extends Aggregate {
@Override
public List<BindData> aggregate(DatasetValue expr, Cell cell, Context context) {
List<Map<String, Object>> objList = DataUtils.fetchData(cell, context, expr.getDatasetName());
List<BindData> list = doAggregate(expr, cell, context, objList);
return list;
}
protected List<BindData> doAggregate(DatasetValue expr, Cell cell, Context context,
List<Map<String, Object>> objList) {
List<String> dataList = new ArrayList<>();
String property = expr.getProperty();
for (Map<String, Object> o : objList) {
Object data = o.get(property);
dataList.add(data != null ? data.toString() : "");
}
BindData bindData = new BindData();
bindData.setDataList(objList);
bindData.setValue(String.join(",", dataList));
List<BindData> list = new ArrayList<>();
list.add(bindData);
return list;
}
}

View File

@@ -0,0 +1,41 @@
package com.yunzhupaas.ureport.build.aggregate;
import com.yunzhupaas.ureport.build.BindData;
import com.yunzhupaas.ureport.build.Context;
import com.yunzhupaas.ureport.definition.value.DatasetValue;
import com.yunzhupaas.ureport.model.Cell;
import com.yunzhupaas.ureport.utils.DataUtils;
import java.util.*;
public class SelectAggregate extends Aggregate {
@Override
public List<BindData> aggregate(DatasetValue expr, Cell cell, Context context) {
List<Map<String, Object>> objList = DataUtils.fetchData(cell, context, expr.getDatasetName());
return doAggregate(expr, cell, context, objList);
}
protected List<BindData> doAggregate(DatasetValue expr, Cell cell, Context context,
List<Map<String, Object>> objList) {
List<BindData> list = new ArrayList<>();
String property = expr.getProperty();
for (Map<String, Object> o : objList) {
List<Map<String, Object>> bindList = new ArrayList<>();
bindList.add(o);
Object data = o.get(property);
BindData bindData = new BindData();
bindData.setDataList(bindList);
bindData.setValue(data);
list.add(bindData);
}
if (list.size() == 0) {
List<Map<String, Object>> rowList = new ArrayList<>();
rowList.add(new HashMap<>());
BindData bindData = new BindData();
bindData.setValue("");
bindData.setDataList(rowList);
list.add(bindData);
}
return list;
}
}

View File

@@ -0,0 +1,32 @@
package com.yunzhupaas.ureport.build.aggregate;
import com.yunzhupaas.ureport.build.BindData;
import com.yunzhupaas.ureport.build.Context;
import com.yunzhupaas.ureport.definition.value.DatasetValue;
import com.yunzhupaas.ureport.model.Cell;
import com.yunzhupaas.ureport.utils.DataUtils;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class SumAggregate extends Aggregate {
@Override
public List<BindData> aggregate(DatasetValue expr, Cell cell, Context context) {
List<Map<String, Object>> objList = DataUtils.fetchData(cell, context, expr.getDatasetName());
List<BindData> list = doAggregate(expr, cell, context, objList);
return list;
}
protected List<BindData> doAggregate(DatasetValue expr, Cell cell, Context context,
List<Map<String, Object>> objList) {
List<BigDecimal> bindDataList = DataUtils.dataList(expr, objList);
BigDecimal result = bindDataList.stream().reduce(BigDecimal.YUNZHUPAAS, BigDecimal::add);
BindData bindData = new BindData();
bindData.setValue(result.doubleValue());
List<BindData> list = new ArrayList<>();
list.add(bindData);
return list;
}
}

View File

@@ -0,0 +1,11 @@
package com.yunzhupaas.ureport.cell;
import com.yunzhupaas.ureport.build.BindData;
import com.yunzhupaas.ureport.build.Context;
import com.yunzhupaas.ureport.model.Cell;
import java.util.List;
public interface CellBuilder {
Cell buildCell(List<BindData> dataList, Cell cell, Context context);
}

View File

@@ -0,0 +1,5 @@
package com.yunzhupaas.ureport.cell;
public enum DuplicateType {
Duplicate, IncreaseSpan, Blank, Self;
}

View File

@@ -0,0 +1,80 @@
package com.yunzhupaas.ureport.cell.down;
import com.yunzhupaas.ureport.build.Context;
import com.yunzhupaas.ureport.model.Cell;
import com.yunzhupaas.ureport.model.Row;
import lombok.Getter;
import lombok.Setter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Setter
@Getter
public class CellDownDuplicateUnit {
private Cell mainCell;
private int mainCellRowNumber;
private Context context;
private String groupId;
private DownDuplicate downDuplicate;
private DownDuplocatorWrapper downDuplocatorWrapper;
public CellDownDuplicateUnit(Context context, DownDuplocatorWrapper downDuplocatorWrapper, Cell mainCell,
int mainCellRowNumber, int rowSize) {
this.context = context;
this.downDuplocatorWrapper = downDuplocatorWrapper;
this.mainCell = mainCell;
this.mainCellRowNumber = mainCellRowNumber;
this.downDuplicate = new DownDuplicate(mainCell, rowSize, context);
}
public void duplicate(Cell cell, int index) {
Map<Cell, Cell> newCellMap = new HashMap<>();
newCellMap.put(mainCell, cell);
downDuplicate.setIndex(index);
for (CellDownDuplicator childDuplicator : downDuplocatorWrapper.getMainCellChildren()) {
Cell newCell = childDuplicator.duplicateChildrenCell(downDuplicate, cell, mainCell, false);
newCell.setDataList(cell.getDataList());
newCell.setLeftGroupId(groupId);
newCellMap.put(childDuplicator.getCell(), newCell);
processChildrenCells(newCell, childDuplicator.getCell(), newCellMap, downDuplicate,
childDuplicator.isNonChild());
childDuplicator.setNonChild(false);
}
for (CellDownDuplicator cellDownDuplicator : downDuplocatorWrapper.getCellDuplicators()) {
cellDownDuplicator.duplicate(downDuplicate, cell);
}
Row newRow = downDuplicate.newRow(cell.getRow(), mainCellRowNumber);
cell.setRow(newRow);
newRow.getCells().add(cell);
cell.getColumn().getCells().add(cell);
context.addReportCell(cell);
downDuplicate.reset();
for (Cell newCell : newCellMap.values()) {
Cell originTopCell = newCell.getTopParentCell();
if (originTopCell != null && newCellMap.containsKey(originTopCell)) {
newCell.setTopParentCell(newCellMap.get(originTopCell));
}
}
}
public void complete() {
downDuplicate.complete();
}
private void processChildrenCells(Cell cell, Cell originalCell, Map<Cell, Cell> newCellMap,
DownDuplicate downDuplicate, boolean parentNonChild) {
List<CellDownDuplicator> childCellDownDuplicators = downDuplocatorWrapper.fetchChildrenDuplicator(originalCell);
if (childCellDownDuplicators == null) {
return;
}
for (CellDownDuplicator duplicator : childCellDownDuplicators) {
Cell newCell = duplicator.duplicateChildrenCell(downDuplicate, cell, originalCell, parentNonChild);
newCell.setLeftGroupId(groupId);
newCellMap.put(duplicator.getCell(), newCell);
processChildrenCells(newCell, duplicator.getCell(), newCellMap, downDuplicate, duplicator.isNonChild());
duplicator.setNonChild(false);
}
}
}

View File

@@ -0,0 +1,160 @@
package com.yunzhupaas.ureport.cell.down;
import com.yunzhupaas.enums.UniverDataEnum;
import com.yunzhupaas.univer.sheet.UniverSheetCellData;
import com.yunzhupaas.ureport.build.Context;
import com.yunzhupaas.ureport.cell.DuplicateType;
import com.yunzhupaas.ureport.definition.BlankCellInfo;
import com.yunzhupaas.ureport.definition.value.SimpleValue;
import com.yunzhupaas.ureport.definition.value.Value;
import com.yunzhupaas.ureport.model.Cell;
import com.yunzhupaas.ureport.model.Row;
import com.yunzhupaas.ureport.utils.DataUtils;
import lombok.Getter;
import lombok.Setter;
import java.util.Objects;
@Getter
@Setter
public class CellDownDuplicator {
private Cell cell;
private int cellRowNumber;
private DuplicateType duplicateType;
private BlankCellInfo blankCellInfo;
private boolean nonChild = false;
public CellDownDuplicator(Cell cell, DuplicateType duplicateType, int cellRowNumber) {
this.cell = cell;
this.cellRowNumber = cellRowNumber;
this.duplicateType = duplicateType;
}
public CellDownDuplicator(Cell cell, DuplicateType duplicateType, BlankCellInfo blankCellInfo, int cellRowNumber) {
this.cell = cell;
if (cellRowNumber == 0) {
this.cellRowNumber = cell.getRow().getRowNumber();
} else {
this.cellRowNumber = cellRowNumber;
}
this.duplicateType = duplicateType;
this.blankCellInfo = blankCellInfo;
}
public Cell duplicateChildrenCell(DownDuplicate downDuplicate, Cell leftParent, Cell originalCell,
boolean parentNonChild) {
Cell newCell = cell.newCell();
Row newRow = downDuplicate.newRow(newCell.getRow(), cellRowNumber);
newRow.getCells().add(newCell);
newCell.getColumn().getCells().add(newCell);
newCell.setRow(newRow);
if (newCell.getLeftParentCell() == originalCell) {
newCell.setLeftParentCell(leftParent);
if (parentNonChild) {
nonChild = true;
}
} else {
nonChild = true;
}
Cell leftParentCell = newCell.getLeftParentCell();
if (leftParentCell != null) {
leftParentCell.addRowChild(newCell);
}
Cell topParentCell = newCell.getTopParentCell();
if (topParentCell != null) {
topParentCell.addColumnChild(newCell);
}
Value value = newCell.getValue();
Context context = downDuplicate.getContext();
String leftType = newCell.getLeftType();
String topType = newCell.getTopType();
DataUtils.cellList(newCell, true, true);
if (value instanceof SimpleValue) {
newCell.setData(value.getValue());
newCell.setProcessed(true);
context.addReportCell(newCell);
if (isSimpleValue(value, leftType, topType)) {
newCell.setData("");
// newCell.setCellData(new UniverSheetCellData());
}
} else {
if (nonChild) {
newCell.setValue(new SimpleValue(""));
} else {
context.addCell(newCell);
}
}
return newCell;
}
public Cell duplicate(DownDuplicate downDuplicate, Cell newMainCell) {
switch (duplicateType) {
case Blank:
processBlankCell(downDuplicate, newMainCell);
break;
case Self:
processSelfBlankCell(downDuplicate);
break;
case IncreaseSpan:
processIncreaseSpanCell(downDuplicate);
break;
}
return null;
}
private void processBlankCell(DownDuplicate downDuplicate, Cell newMainCell) {
Context context = downDuplicate.getContext();
Cell newBlankCell = cell.newRowBlankCell(context, blankCellInfo, downDuplicate.getMainCell());
if (blankCellInfo.isParent() && newMainCell.getLeftParentCell() == cell) {
newMainCell.setLeftParentCell(newBlankCell);
}
Row newRow = downDuplicate.newRow(newBlankCell.getRow(), cellRowNumber);
newRow.getCells().add(newBlankCell);
newBlankCell.getColumn().getCells().add(newBlankCell);
newBlankCell.setRow(newRow);
context.addReportCell(newBlankCell);
}
private void processSelfBlankCell(DownDuplicate downDuplicate) {
Cell newBlankCell = cell.newCell();
newBlankCell.setValue(new SimpleValue(""));
Row newRow = downDuplicate.newRow(newBlankCell.getRow(), cellRowNumber);
newRow.getCells().add(newBlankCell);
newBlankCell.getColumn().getCells().add(newBlankCell);
newBlankCell.setRow(newRow);
Cell leftParentCell = newBlankCell.getLeftParentCell();
if (leftParentCell != null) {
leftParentCell.addRowChild(newBlankCell);
}
Cell topParentCell = newBlankCell.getTopParentCell();
if (topParentCell != null) {
topParentCell.addColumnChild(newBlankCell);
}
Context context = downDuplicate.getContext();
context.addBlankCell(newBlankCell);
}
private void processIncreaseSpanCell(DownDuplicate downDuplicate) {
int rowSpan = cell.getRowSpan();
Value value = cell.getValue();
String leftType = cell.getLeftType();
String topType = cell.getTopType();
if (isSimpleValue(value, leftType, topType)) {
return;
}
rowSpan += downDuplicate.getRowSize();
if (rowSpan == 1) {
rowSpan++;
}
cell.setRowSpan(rowSpan);
}
private boolean isSimpleValue(Value value, String leftType, String topType) {
// 判断文本类型是否要合并格子
boolean isSimpleValue = value instanceof SimpleValue;
boolean isLeftNone = Objects.equals(leftType, UniverDataEnum.cellNone.getName());
boolean isTopNone = Objects.equals(topType, UniverDataEnum.cellNone.getName());
return isSimpleValue && isLeftNone && isTopNone;
}
}

View File

@@ -0,0 +1,79 @@
package com.yunzhupaas.ureport.cell.down;
import com.yunzhupaas.ureport.build.BindData;
import com.yunzhupaas.ureport.build.Context;
import com.yunzhupaas.ureport.model.Cell;
import com.yunzhupaas.ureport.model.Column;
import com.yunzhupaas.ureport.model.Row;
import java.util.List;
/**
* @author
* @since 3月2日
*/
public class DownBlankCellApply {
private int rowSize;
private Cell cell;
private Context context;
private DownDuplocatorWrapper downDuplocatorWrapper;
public DownBlankCellApply(int rowSize, Cell cell, Context context, DownDuplocatorWrapper downDuplocatorWrapper) {
this.rowSize = rowSize;
this.cell = cell;
this.context = context;
this.downDuplocatorWrapper = downDuplocatorWrapper;
}
public boolean useBlankCell(int index, BindData bindData) {
if (context.getBlankCellsMap().size() == 0) {
return false;
}
int nextRowNumber = cell.getRow().getRowNumber() + rowSize * (index - 1) + rowSize;
Row nextRow = context.getRow(nextRowNumber);
Cell blankCell = null;
if (nextRow != null) {
blankCell = context.getBlankCell(nextRow, cell.getColumn());
}
if (blankCell == null) {
return false;
}
context.removeBlankCell(blankCell);
blankCell.setValue(cell.getValue());
blankCell.setProcessed(true);
blankCell.setData(bindData.getValue());
blankCell.setBindData(bindData.getDataList());
processChildrenCell(cell, blankCell, index);
return true;
}
private void processChildrenCell(Cell originalCell, Cell leftParentCell, int index) {
List<CellDownDuplicator> children = downDuplocatorWrapper.fetchChildrenDuplicator(originalCell);
if (children == null) {
return;
}
for (CellDownDuplicator child : children) {
Cell childCell = child.getCell();
Cell targetCell = getChildBlankCell(childCell, index);
if (targetCell == null) {
continue;
}
context.removeBlankCell(targetCell);
targetCell.setLeftParentCell(leftParentCell);
targetCell.setValue(childCell.getValue());
if (targetCell.getTopParentCell() == originalCell) {
targetCell.setTopParentCell(leftParentCell);
}
context.addUnprocessedCell(targetCell);
processChildrenCell(childCell, targetCell, index);
}
}
private Cell getChildBlankCell(Cell childCell, int index) {
int nextChildRowNumber = childCell.getRow().getRowNumber() + rowSize * (index - 1) + rowSize;
Row nextChildRow = context.getRow(nextChildRowNumber);
Column col = childCell.getColumn();
Cell targetCell = context.getBlankCell(nextChildRow, col);
return targetCell;
}
}

View File

@@ -0,0 +1,262 @@
package com.yunzhupaas.ureport.cell.down;
import com.yunzhupaas.ureport.Range;
import com.yunzhupaas.ureport.definition.BlankCellInfo;
import com.yunzhupaas.ureport.definition.CellDefinition;
import com.yunzhupaas.ureport.utils.BuildUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class DownCellbuilder {
public void buildParentCell(CellDefinition cell, List<CellDefinition> cells) {
List<Range> rangeList = new ArrayList<>();
Range range = buildChildrenCellRange(cell);
List<CellDefinition> parentCells = new ArrayList<>();
collectParentCells(cell, parentCells);
buildParents(cell, parentCells, range, rangeList);
Range childRange = buildChildrenCells(cell, rangeList);
buildChildrenBlankCells(cell, cells, childRange);
Range rowRange = buildRowRange(rangeList);
buildRowsBlankCells(cell, cells, rowRange);
int start = rowRange.getStart();
int end = rowRange.getEnd();
int rowNumberStart = cell.getRowNumber();
int rowNumberEnd = cell.getRowNumber();
int rowSpan = cell.getRowSpan();
if (rowSpan > 0) {
rowNumberEnd += rowSpan - 1;
}
int rangeStart = 0;
int rangeEnd = 0;
if (start != -1) {
rangeStart = start - rowNumberStart;
}
if (end > rowNumberStart && end > rowNumberEnd) {
rangeEnd = end - rowNumberStart;
} else {
rangeEnd = rowNumberEnd - rowNumberStart;
}
Range duplicateRange = new Range(rangeStart, rangeEnd);
cell.setDuplicateRange(duplicateRange);
}
private void buildRowsBlankCells(CellDefinition cell, List<CellDefinition> cells, Range range) {
Map<String, BlankCellInfo> blankCellNamesMap = cell.getNewBlankCellsMap();
int start = range.getStart();
int end = range.getEnd();
int nextEnd = 0;
for (int i = start; i <= end; i++) {
for (CellDefinition cellDef : cells) {
String name = cellDef.getName();
if (cellPrcessed(cell, name)) {
continue;
}
int rowNumber = cellDef.getRowNumber();
if (rowNumber == i) {
int offset = rowNumber - cell.getRowNumber();
blankCellNamesMap.put(name, new BlankCellInfo(offset, cellDef.getRowSpan(), false));
} else if (rowNumber < i) {
int endRowNumber = BuildUtils.buildRowNumberEnd(cellDef, rowNumber);
if (endRowNumber >= i) {
int offset = rowNumber - cell.getRowNumber();
blankCellNamesMap.put(name, new BlankCellInfo(offset, cellDef.getRowSpan(), false));
}
}
}
}
if (nextEnd > end) {
buildRowsBlankCells(cell, cells, new Range(end, nextEnd));
}
}
private Range buildRowRange(List<Range> rangeList) {
Range rowRange = new Range();
for (Range range : rangeList) {
for (int i = range.getStart(); i <= range.getEnd(); i++) {
if (rowRange.getStart() == -1 || i < rowRange.getStart()) {
rowRange.setStart(i);
}
if (rowRange.getEnd() < i) {
rowRange.setEnd(i);
}
}
}
return rowRange;
}
private Range buildChildrenCells(CellDefinition cell, List<Range> rangeList) {
Range range = new Range();
List<CellDefinition> rowChildrenCells = cell.getRowChildrenCells();
for (CellDefinition childCell : rowChildrenCells) {
cell.getNewCellNames().add(childCell.getName());
int rowNumber = childCell.getRowNumber();
int endRowNumber = BuildUtils.buildRowNumberEnd(childCell, rowNumber);
rangeList.add(new Range(rowNumber, endRowNumber));
if (endRowNumber > range.getEnd()) {
range.setEnd(endRowNumber);
}
if (range.getStart() == -1 || rowNumber < range.getStart()) {
range.setStart(rowNumber);
}
}
return range;
}
private void buildChildrenBlankCells(CellDefinition cell, List<CellDefinition> cells, Range childRange) {
int startRowNumber = cell.getRowNumber();
int endRowNumber = BuildUtils.buildRowNumberEnd(cell, startRowNumber);
int start = childRange.getStart();
int end = childRange.getEnd();
if (start != -1 && start < startRowNumber) {
startRowNumber = start;
}
if (end > endRowNumber) {
endRowNumber = end;
}
Map<String, BlankCellInfo> blankCellNamesMap = cell.getNewBlankCellsMap();
for (int i = startRowNumber; i <= endRowNumber; i++) {
for (CellDefinition c : cells) {
if (c.getRowNumber() != i) {
continue;
}
if (c.equals(cell)) {
continue;
}
String name = c.getName();
boolean contain = cellPrcessed(cell, name);
if (contain) {
continue;
}
int offset = c.getRowNumber() - cell.getRowNumber();
blankCellNamesMap.put(name, new BlankCellInfo(offset, c.getRowSpan(), false));
}
}
}
private boolean cellPrcessed(CellDefinition cell, String name) {
List<String> newCellNames = cell.getNewCellNames();
List<String> increaseCellNames = cell.getIncreaseSpanCellNames();
Map<String, BlankCellInfo> blankCellNamesMap = cell.getNewBlankCellsMap();
boolean contain = cell.getName().equals(name);
if (newCellNames.contains(name)) {
contain = true;
}
if (increaseCellNames.contains(name)) {
contain = true;
}
if (blankCellNamesMap.containsKey(name)) {
contain = true;
}
return contain;
}
private void collectParentCells(CellDefinition cell, List<CellDefinition> parentCells) {
CellDefinition leftParentCell = cell.getLeftParentCell();
if (leftParentCell == null) {
return;
}
parentCells.add(leftParentCell);
collectParentCells(leftParentCell, parentCells);
}
private void buildParents(CellDefinition mainCell, List<CellDefinition> parentCells, Range childRange,
List<Range> rangeList) {
int rowNumberStart = mainCell.getRowNumber();
int rowNumberEnd = BuildUtils.buildRowNumberEnd(mainCell, rowNumberStart);
rangeList.add(new Range(rowNumberStart, rowNumberEnd));
int start = childRange.getStart();
int end = childRange.getEnd();
Map<String, BlankCellInfo> newBlankCellsMap = mainCell.getNewBlankCellsMap();
boolean increase = true;
for (CellDefinition parentCell : parentCells) {
String parentCellName = parentCell.getName();
int parentRowNumberStart = parentCell.getRowNumber();
int parentRowNumberEnd = BuildUtils.buildRowNumberEnd(parentCell, parentRowNumberStart);
int offset = parentRowNumberStart - rowNumberStart;
int parentRowSpan = parentCell.getRowSpan();
boolean isOut = assertOut(parentCell, mainCell, childRange);
if (isOut) {
increase = false;
boolean doBlank = assertDoBlank(parentCell.getLeftParentCell(), parentCell, mainCell, childRange);
if (doBlank) {
newBlankCellsMap.put(parentCellName, new BlankCellInfo(offset, parentRowSpan, true));
rangeList.add(new Range(parentRowNumberStart, parentRowNumberEnd));
}
continue;
}
if ((start != -1 && start < parentRowNumberStart) || end > parentRowNumberEnd) {
newBlankCellsMap.put(parentCellName, new BlankCellInfo(offset, parentRowSpan, true));
rangeList.add(new Range(parentRowNumberStart, parentRowNumberEnd));
increase = false;
continue;
}
if (increase) {
mainCell.getIncreaseSpanCellNames().add(parentCellName);
} else {
newBlankCellsMap.put(parentCellName, new BlankCellInfo(offset, parentRowSpan, true));
rangeList.add(new Range(parentRowNumberStart, parentRowNumberEnd));
}
}
}
private boolean assertDoBlank(CellDefinition nextParentCell, CellDefinition parentCell, CellDefinition mainCell,
Range childRange) {
if (nextParentCell == null) {
return false;
}
boolean isOut = assertOut(nextParentCell, mainCell, childRange);
if (isOut) {
return assertDoBlank(nextParentCell.getLeftParentCell(), parentCell, mainCell, childRange);
}
int start = parentCell.getRowNumber();
int end = BuildUtils.buildRowNumberEnd(parentCell, start);
int nextStart = nextParentCell.getRowNumber();
if (nextStart <= end) {
return true;
}
return assertDoBlank(nextParentCell.getLeftParentCell(), parentCell, mainCell, childRange);
}
private boolean assertOut(CellDefinition parentCell, CellDefinition mainCell, Range childRange) {
int start = parentCell.getRowNumber();
int end = BuildUtils.buildRowNumberEnd(parentCell, start);
int rangeStart = childRange.getStart();
int rangeEnd = childRange.getEnd();
if (rangeStart != -1) {
if ((start >= rangeStart && start <= rangeEnd) || (end >= rangeStart && end <= rangeEnd)) {
return false;
}
}
int rowStart = mainCell.getRowNumber();
int rowEnd = BuildUtils.buildRowNumberEnd(mainCell, rowStart);
if ((start >= rowStart && start <= rowEnd) || (end >= rowStart && end <= rowEnd)
|| (start <= rowStart && end >= rowEnd)) {
return false;
}
return true;
}
private Range buildChildrenCellRange(CellDefinition mainCell) {
Range range = new Range();
List<CellDefinition> childrenCells = mainCell.getRowChildrenCells();
for (CellDefinition childCell : childrenCells) {
int childRowNumberStart = childCell.getRowNumber();
int childRowSpan = childCell.getRowSpan();
childRowSpan = childRowSpan > 0 ? childRowSpan - 1 : childRowSpan;
int childRowNumberEnd = childRowNumberStart + childRowSpan;
if (range.getStart() == -1 || childRowNumberStart < range.getStart()) {
range.setStart(childRowNumberStart);
}
if (childRowNumberEnd > range.getEnd()) {
range.setEnd(childRowNumberEnd);
}
}
return range;
}
}

View File

@@ -0,0 +1,60 @@
package com.yunzhupaas.ureport.cell.down;
import com.yunzhupaas.ureport.build.Context;
import com.yunzhupaas.ureport.model.Cell;
import com.yunzhupaas.ureport.model.Report;
import com.yunzhupaas.ureport.model.Row;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Setter
@Getter
public class DownDuplicate {
private int index;
private Cell mainCell;
private int rowSize;
private Context context;
private int minRowNumber = -1;
private Map<Row, Row> rowMap = new HashMap<>();
private List<Row> newRowList = new ArrayList<>();
public DownDuplicate(Cell mainCell, int rowSize, Context context) {
this.mainCell = mainCell;
this.rowSize = rowSize;
this.context = context;
}
public Row newRow(Row row, int currentRowNumber) {
if (rowMap.containsKey(row)) {
return rowMap.get(row);
} else {
int rowNumber = currentRowNumber;
Row newRow = row.newRow();
rowNumber = rowNumber + rowSize * (index - 1) + rowSize;
if (minRowNumber == -1 || minRowNumber > rowNumber) {
minRowNumber = rowNumber;
}
newRow.setTempRowNumber(rowNumber);
newRowList.add(newRow);
rowMap.put(row, newRow);
return newRow;
}
}
public void complete() {
if (minRowNumber < 1) {
return;
}
Report report = context.getReport();
report.insertRows(minRowNumber, newRowList);
}
public void reset() {
rowMap.clear();
}
}

View File

@@ -0,0 +1,62 @@
package com.yunzhupaas.ureport.cell.down;
import com.yunzhupaas.ureport.cell.DuplicateType;
import com.yunzhupaas.ureport.model.Cell;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Setter
@Getter
public class DownDuplocatorWrapper {
private String mainCellName;
private List<CellDownDuplicator> mainCellChildren = new ArrayList<>();
private List<CellDownDuplicator> cellDuplicators = new ArrayList<>();
private Map<Cell, List<CellDownDuplicator>> createNewDuplicatorsMap = new HashMap<>();
private List<Cell> duplicatorCells = new ArrayList<>();
public DownDuplocatorWrapper(String mainCellName) {
this.mainCellName = mainCellName;
}
public void addCellDownDuplicator(CellDownDuplicator duplicator) {
if (duplicator.getDuplicateType().equals(DuplicateType.Duplicate)) {
addCellDownDuplicatorToMap(duplicator);
} else {
cellDuplicators.add(duplicator);
duplicatorCells.add(duplicator.getCell());
}
}
private void addCellDownDuplicatorToMap(CellDownDuplicator duplicator) {
Cell leftParentCell = duplicator.getCell().getLeftParentCell();
if (leftParentCell.getName().equals(mainCellName)) {
mainCellChildren.add(duplicator);
}
List<CellDownDuplicator> list = null;
if (createNewDuplicatorsMap.containsKey(leftParentCell)) {
list = createNewDuplicatorsMap.get(leftParentCell);
} else {
list = new ArrayList<>();
createNewDuplicatorsMap.put(leftParentCell, list);
}
list.add(duplicator);
}
public boolean contains(Cell cell) {
return duplicatorCells.contains(cell);
}
public List<CellDownDuplicator> getMainCellChildren() {
return mainCellChildren;
}
public List<CellDownDuplicator> fetchChildrenDuplicator(Cell leftParentCell) {
return createNewDuplicatorsMap.get(leftParentCell);
}
}

View File

@@ -0,0 +1,133 @@
package com.yunzhupaas.ureport.cell.down;
import com.yunzhupaas.ureport.Range;
import com.yunzhupaas.ureport.build.BindData;
import com.yunzhupaas.ureport.build.Context;
import com.yunzhupaas.ureport.cell.CellBuilder;
import com.yunzhupaas.ureport.cell.DuplicateType;
import com.yunzhupaas.ureport.definition.BlankCellInfo;
import com.yunzhupaas.ureport.model.Cell;
import com.yunzhupaas.ureport.model.Row;
import com.yunzhupaas.ureport.utils.DataUtils;
import com.yunzhupaas.util.RandomUtil;
import java.util.List;
import java.util.Map;
/**
* @author
* @since 2016年11月1日
*/
public class DownExpandBuilder implements CellBuilder {
@Override
public Cell buildCell(List<BindData> dataList, Cell cell, Context context) {
Range duplicateRange = cell.getDuplicateRange();
int mainCellRowNumber = cell.getRow().getRowNumber();
Range rowRange = buildRowRange(mainCellRowNumber, duplicateRange);
DownDuplocatorWrapper downDuplocatorWrapper = buildCellDownDuplicator(cell, context, rowRange);
int rowSize = rowRange.getEnd() - rowRange.getStart() + 1;
DownBlankCellApply downBlankCellApply = new DownBlankCellApply(rowSize, cell, context, downDuplocatorWrapper);
CellDownDuplicateUnit unit = new CellDownDuplicateUnit(context, downDuplocatorWrapper, cell, mainCellRowNumber,
rowSize);
Cell lastCell = cell;
String groupId = RandomUtil.uuId();
for (int i = 0; i < dataList.size(); i++) {
BindData bindData = dataList.get(i);
if (i == 0) {
cell.setData(bindData.getValue());
cell.setBindData(bindData.getDataList());
cell.setDataList(dataList);
cell.setLeftGroupId(groupId);
DataUtils.cellList(cell, true, true);
continue;
}
boolean useBlankCell = downBlankCellApply.useBlankCell(i, bindData);
if (useBlankCell) {
continue;
}
Cell newCell = cell.newCell();
newCell.setRowNumber(newCell.getRowNumber() + i);
newCell.setData(bindData.getValue());
newCell.setBindData(bindData.getDataList());
newCell.setDataList(dataList);
newCell.setLeftGroupId(groupId);
newCell.setProcessed(true);
Cell leftParentCell = cell.getLeftParentCell();
if (leftParentCell != null) {
leftParentCell.addRowChild(newCell);
}
Cell topParentCell = cell.getTopParentCell();
if (topParentCell != null) {
topParentCell.addColumnChild(newCell);
}
DataUtils.cellList(newCell, true, true);
unit.setGroupId(RandomUtil.uuId());
unit.duplicate(newCell, i);
lastCell = newCell;
}
unit.complete();
return lastCell;
}
private Range buildRowRange(int mainCellRowNumber, Range range) {
int start = mainCellRowNumber + range.getStart();
int end = mainCellRowNumber + range.getEnd();
Range ranges = new Range();
ranges.setStart(start);
ranges.setEnd(end);
return ranges;
}
private DownDuplocatorWrapper buildCellDownDuplicator(Cell cell, Context context, Range range) {
DownDuplocatorWrapper duplicatorWrapper = new DownDuplocatorWrapper(cell.getName());
buildParentCellDuplicators(cell, cell, duplicatorWrapper);
for (int i = range.getStart(); i <= range.getEnd(); i++) {
Row row = context.getRow(i);
List<Cell> rowCells = row.getCells();
for (Cell rowCell : rowCells) {
rowCell.setLeftGroupId(RandomUtil.uuId());
buildDuplicator(duplicatorWrapper, cell, rowCell, i);
}
}
return duplicatorWrapper;
}
private void buildParentCellDuplicators(Cell cell, Cell mainCell, DownDuplocatorWrapper duplicatorWrapper) {
Cell leftParentCell = cell.getLeftParentCell();
if (leftParentCell == null) {
return;
}
buildDuplicator(duplicatorWrapper, mainCell, leftParentCell, 0);
buildParentCellDuplicators(leftParentCell, mainCell, duplicatorWrapper);
}
private void buildDuplicator(DownDuplocatorWrapper duplicatorWrapper, Cell mainCell, Cell currentCell,
int rowNumber) {
if (currentCell == mainCell) {
return;
}
String name = currentCell.getName();
Map<String, BlankCellInfo> newBlankCellNamesMap = mainCell.getNewBlankCellsMap();
List<String> increaseCellNames = mainCell.getIncreaseSpanCellNames();
List<String> newCellNames = mainCell.getNewCellNames();
if (newBlankCellNamesMap.containsKey(name)) {
if (!duplicatorWrapper.contains(currentCell)) {
CellDownDuplicator cellDuplicator = new CellDownDuplicator(currentCell, DuplicateType.Blank,
newBlankCellNamesMap.get(name), rowNumber);
duplicatorWrapper.addCellDownDuplicator(cellDuplicator);
}
} else if (increaseCellNames.contains(name)) {
if (!duplicatorWrapper.contains(currentCell)) {
CellDownDuplicator cellDuplicator = new CellDownDuplicator(currentCell, DuplicateType.IncreaseSpan,
rowNumber);
duplicatorWrapper.addCellDownDuplicator(cellDuplicator);
}
} else if (newCellNames.contains(name)) {
CellDownDuplicator cellDuplicator = new CellDownDuplicator(currentCell, DuplicateType.Duplicate, rowNumber);
duplicatorWrapper.addCellDownDuplicator(cellDuplicator);
} else if (mainCell.getName().equals(name)) {
CellDownDuplicator cellDuplicator = new CellDownDuplicator(currentCell, DuplicateType.Self, rowNumber);
duplicatorWrapper.addCellDownDuplicator(cellDuplicator);
}
}
}

View File

@@ -0,0 +1,35 @@
package com.yunzhupaas.ureport.cell.none;
import com.yunzhupaas.ureport.build.BindData;
import com.yunzhupaas.ureport.build.Context;
import com.yunzhupaas.ureport.cell.CellBuilder;
import com.yunzhupaas.ureport.model.Cell;
import java.util.List;
import java.util.Map;
public class NoneExpandBuilder implements CellBuilder {
@Override
public Cell buildCell(List<BindData> dataList, Cell cell, Context context) {
if (dataList.size() == 1) {
BindData bindData = dataList.get(0);
cell.setData(bindData.getValue());
cell.setBindData(bindData.getDataList());
} else {
Object obj = null;
List<Map<String, Object>> bindData = null;
for (BindData data : dataList) {
if (obj == null) {
obj = data.getValue();
} else {
obj = obj + "," + data.getValue();
}
bindData = data.getDataList();
}
cell.setData(obj);
cell.setBindData(bindData);
}
return cell;
}
}

View File

@@ -0,0 +1,85 @@
package com.yunzhupaas.ureport.cell.right;
import com.yunzhupaas.ureport.build.Context;
import com.yunzhupaas.ureport.model.Cell;
import com.yunzhupaas.ureport.model.Column;
import lombok.Getter;
import lombok.Setter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author
* @since 2016年11月7日
*/
@Setter
@Getter
public class CellRightDuplicateUnit {
private Cell mainCell;
private int mainCellColNumber;
private Context context;
private String groupId;
private RightDuplicate rightDuplicate;
private RightDuplocatorWrapper rightDuplocatorWrapper;
public CellRightDuplicateUnit(Context context, RightDuplocatorWrapper rightDuplocatorWrapper, Cell mainCell,
int mainCellColNumber, int colSize) {
this.context = context;
this.rightDuplocatorWrapper = rightDuplocatorWrapper;
this.mainCell = mainCell;
this.mainCellColNumber = mainCellColNumber;
this.rightDuplicate = new RightDuplicate(mainCell, colSize, context);
}
public void duplicate(Cell cell, int index) {
Map<Cell, Cell> newCellMap = new HashMap<>();
newCellMap.put(mainCell, cell);
rightDuplicate.setIndex(index);
for (CellRightDuplicator childDuplicator : rightDuplocatorWrapper.getMainCellChildren()) {
Cell newCell = childDuplicator.duplicateChildrenCell(rightDuplicate, cell, mainCell, false);
newCell.setDataList(cell.getDataList());
newCell.setTopGroupId(groupId);
newCellMap.put(childDuplicator.getCell(), newCell);
processChildrenCells(newCell, childDuplicator.getCell(), newCellMap, rightDuplicate,
childDuplicator.isNonChild());
childDuplicator.setNonChild(false);
}
for (CellRightDuplicator cellDownDuplicator : rightDuplocatorWrapper.getCellDuplicators()) {
cellDownDuplicator.duplicate(rightDuplicate, cell);
}
Column newCol = rightDuplicate.newColumn(cell.getColumn(), mainCellColNumber);
cell.setColumn(newCol);
newCol.getCells().add(cell);
cell.getRow().getCells().add(cell);
context.addReportCell(cell);
rightDuplicate.reset();
for (Cell newCell : newCellMap.values()) {
Cell originLeftCell = newCell.getLeftParentCell();
if (originLeftCell != null && newCellMap.containsKey(originLeftCell)) {
newCell.setLeftParentCell(newCellMap.get(originLeftCell));
}
}
}
public void complete() {
rightDuplicate.complete();
}
private void processChildrenCells(Cell cell, Cell originalCell, Map<Cell, Cell> newCellMap,
RightDuplicate rightDuplicate, boolean parentNonChild) {
List<CellRightDuplicator> childCellRightDuplicators = rightDuplocatorWrapper
.fetchChildrenDuplicator(originalCell);
if (childCellRightDuplicators == null) {
return;
}
for (CellRightDuplicator duplicator : childCellRightDuplicators) {
Cell newCell = duplicator.duplicateChildrenCell(rightDuplicate, cell, originalCell, parentNonChild);
newCell.setTopGroupId(groupId);
newCellMap.put(duplicator.getCell(), newCell);
processChildrenCells(newCell, duplicator.getCell(), newCellMap, rightDuplicate, duplicator.isNonChild());
duplicator.setNonChild(false);
}
}
}

Some files were not shown because too many files have changed in this diff Show More