初始代码
This commit is contained in:
57
yunzhupaas-datareport-univer-common/pom.xml
Normal file
57
yunzhupaas-datareport-univer-common/pom.xml
Normal 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>
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.yunzhupaas.properties;
|
||||
|
||||
public class ReportProperties {
|
||||
|
||||
public static final String PREFIX = "report";
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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()]));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user