index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/data/FormulaData.java
|
package ai.chat2db.excel.metadata.data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* formula
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class FormulaData {
/**
* formula
*/
private String formulaValue;
@Override
public FormulaData clone() {
FormulaData formulaData = new FormulaData();
formulaData.setFormulaValue(getFormulaValue());
return formulaData;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/data/HyperlinkData.java
|
package ai.chat2db.excel.metadata.data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* hyperlink
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class HyperlinkData extends CoordinateData {
/**
* Depending on the hyperlink type it can be URL, e-mail, path to a file, etc
*/
private String address;
/**
* hyperlink type
*/
private HyperlinkType hyperlinkType;
@Getter
public enum HyperlinkType {
/**
* Not a hyperlink
*/
NONE(org.apache.poi.common.usermodel.HyperlinkType.NONE),
/**
* Link to an existing file or web page
*/
URL(org.apache.poi.common.usermodel.HyperlinkType.URL),
/**
* Link to a place in this document
*/
DOCUMENT(org.apache.poi.common.usermodel.HyperlinkType.DOCUMENT),
/**
* Link to an E-mail address
*/
EMAIL(org.apache.poi.common.usermodel.HyperlinkType.EMAIL),
/**
* Link to a file
*/
FILE(org.apache.poi.common.usermodel.HyperlinkType.FILE);
org.apache.poi.common.usermodel.HyperlinkType value;
HyperlinkType(org.apache.poi.common.usermodel.HyperlinkType value) {
this.value = value;
}
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/data/ImageData.java
|
package ai.chat2db.excel.metadata.data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* image
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class ImageData extends ClientAnchorData {
/**
* image
*/
private byte[] image;
/**
* image type
*/
private ImageType imageType;
@Getter
public enum ImageType {
/**
* Extended windows meta file
*/
PICTURE_TYPE_EMF(2),
/**
* Windows Meta File
*/
PICTURE_TYPE_WMF(3),
/**
* Mac PICT format
*/
PICTURE_TYPE_PICT(4),
/**
* JPEG format
*/
PICTURE_TYPE_JPEG(5),
/**
* PNG format
*/
PICTURE_TYPE_PNG(6),
/**
* Device independent bitmap
*/
PICTURE_TYPE_DIB(7),
;
int value;
ImageType(int value) {
this.value = value;
}
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/data/ReadCellData.java
|
package ai.chat2db.excel.metadata.data;
import java.math.BigDecimal;
import ai.chat2db.excel.enums.CellDataTypeEnum;
import ai.chat2db.excel.constant.EasyExcelConstants;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* read cell data
* <p>
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
public class ReadCellData<T> extends CellData<T> {
/**
* originalNumberValue vs numberValue
* <ol>
* <li>
* NUMBER:
* originalNumberValue: Original data and the accuracy of his is 17, but in fact the excel only 15 precision to
* process the data
* numberValue: After correction of the data and the accuracy of his is 15
* for example, originalNumberValue = `2087.0249999999996` , numberValue = `2087.03`
* </li>
* <li>
* DATE:
* originalNumberValue: Storage is a data type double, accurate to milliseconds
* dateValue: Based on double converted to a date format, he will revised date difference, accurate to seconds
* for example, originalNumberValue = `44729.99998836806` ,time is:`2022-06-17 23:59:58.995`,
* But in excel is displayed:` 2022-06-17 23:59:59`, dateValue = `2022-06-17 23:59:59`
* </li>
* </ol>
* {@link CellDataTypeEnum#NUMBER} {@link CellDataTypeEnum#DATE}
*/
private BigDecimal originalNumberValue;
/**
* data format.
*/
private DataFormatData dataFormatData;
public ReadCellData(CellDataTypeEnum type) {
super();
if (type == null) {
throw new IllegalArgumentException("Type can not be null");
}
setType(type);
}
public ReadCellData(T data) {
super();
setData(data);
}
public ReadCellData(String stringValue) {
this(CellDataTypeEnum.STRING, stringValue);
}
public ReadCellData(CellDataTypeEnum type, String stringValue) {
super();
if (type != CellDataTypeEnum.STRING && type != CellDataTypeEnum.ERROR) {
throw new IllegalArgumentException("Only support CellDataTypeEnum.STRING and CellDataTypeEnum.ERROR");
}
if (stringValue == null) {
throw new IllegalArgumentException("StringValue can not be null");
}
setType(type);
setStringValue(stringValue);
}
public ReadCellData(BigDecimal numberValue) {
super();
if (numberValue == null) {
throw new IllegalArgumentException("DoubleValue can not be null");
}
setType(CellDataTypeEnum.NUMBER);
setNumberValue(numberValue);
}
public ReadCellData(Boolean booleanValue) {
super();
if (booleanValue == null) {
throw new IllegalArgumentException("BooleanValue can not be null");
}
setType(CellDataTypeEnum.BOOLEAN);
setBooleanValue(booleanValue);
}
public static ReadCellData<?> newEmptyInstance() {
return newEmptyInstance(null, null);
}
public static ReadCellData<?> newEmptyInstance(Integer rowIndex, Integer columnIndex) {
ReadCellData<?> cellData = new ReadCellData<>(CellDataTypeEnum.EMPTY);
cellData.setRowIndex(rowIndex);
cellData.setColumnIndex(columnIndex);
return cellData;
}
public static ReadCellData<?> newInstance(Boolean booleanValue) {
return newInstance(booleanValue, null, null);
}
public static ReadCellData<?> newInstance(Boolean booleanValue, Integer rowIndex, Integer columnIndex) {
ReadCellData<?> cellData = new ReadCellData<>(booleanValue);
cellData.setRowIndex(rowIndex);
cellData.setColumnIndex(columnIndex);
return cellData;
}
public static ReadCellData<?> newInstance(String stringValue, Integer rowIndex, Integer columnIndex) {
ReadCellData<?> cellData = new ReadCellData<>(stringValue);
cellData.setRowIndex(rowIndex);
cellData.setColumnIndex(columnIndex);
return cellData;
}
public static ReadCellData<?> newInstance(BigDecimal numberValue, Integer rowIndex, Integer columnIndex) {
ReadCellData<?> cellData = new ReadCellData<>(numberValue);
cellData.setRowIndex(rowIndex);
cellData.setColumnIndex(columnIndex);
return cellData;
}
public static ReadCellData<?> newInstanceOriginal(BigDecimal numberValue, Integer rowIndex, Integer columnIndex) {
ReadCellData<?> cellData = new ReadCellData<>(numberValue);
cellData.setRowIndex(rowIndex);
cellData.setColumnIndex(columnIndex);
cellData.setOriginalNumberValue(numberValue);
cellData.setNumberValue(numberValue.round(EasyExcelConstants.EXCEL_MATH_CONTEXT));
return cellData;
}
@Override
public ReadCellData<Object> clone() {
ReadCellData<Object> readCellData = new ReadCellData<>();
readCellData.setType(getType());
readCellData.setNumberValue(getNumberValue());
readCellData.setOriginalNumberValue(getOriginalNumberValue());
readCellData.setStringValue(getStringValue());
readCellData.setBooleanValue(getBooleanValue());
readCellData.setData(getData());
if (getDataFormatData() != null) {
readCellData.setDataFormatData(getDataFormatData().clone());
}
if (getFormulaData() != null) {
readCellData.setFormulaData(getFormulaData().clone());
}
return readCellData;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/data/RichTextStringData.java
|
package ai.chat2db.excel.metadata.data;
import java.util.List;
import ai.chat2db.excel.util.ListUtils;
import ai.chat2db.excel.write.metadata.style.WriteFont;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* rich text string
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
public class RichTextStringData {
private String textString;
private WriteFont writeFont;
private List<IntervalFont> intervalFontList;
public RichTextStringData(String textString) {
this.textString = textString;
}
@Getter
@Setter
@EqualsAndHashCode
@AllArgsConstructor
public static class IntervalFont {
private Integer startIndex;
private Integer endIndex;
private WriteFont writeFont;
}
/**
* Applies a font to the specified characters of a string.
*
* @param startIndex The start index to apply the font to (inclusive)
* @param endIndex The end index to apply to font to (exclusive)
* @param writeFont The font to use.
*/
public void applyFont(int startIndex, int endIndex, WriteFont writeFont) {
if (intervalFontList == null) {
intervalFontList = ListUtils.newArrayList();
}
intervalFontList.add(new IntervalFont(startIndex, endIndex, writeFont));
}
/**
* Sets the font of the entire string.
*
* @param writeFont The font to use.
*/
public void applyFont(WriteFont writeFont) {
this.writeFont = writeFont;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/data/WriteCellData.java
|
package ai.chat2db.excel.metadata.data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import ai.chat2db.excel.enums.CellDataTypeEnum;
import ai.chat2db.excel.util.ListUtils;
import ai.chat2db.excel.write.metadata.style.WriteCellStyle;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.poi.ss.usermodel.CellStyle;
/**
* write cell data
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
public class WriteCellData<T> extends CellData<T> {
/**
* Support only when writing.{@link CellDataTypeEnum#DATE}
*/
private LocalDateTime dateValue;
/**
* rich text.{@link CellDataTypeEnum#RICH_TEXT_STRING}
*/
private RichTextStringData richTextStringDataValue;
/**
* image
*/
private List<ImageData> imageDataList;
/**
* comment
*/
private CommentData commentData;
/**
* hyper link
*/
private HyperlinkData hyperlinkData;
/**
* style
*/
private WriteCellStyle writeCellStyle;
/**
* If originCellStyle is empty, one will be created.
* If both writeCellStyle and originCellStyle exist, copy from writeCellStyle to originCellStyle.
*/
private CellStyle originCellStyle;
public WriteCellData(String stringValue) {
this(CellDataTypeEnum.STRING, stringValue);
}
public WriteCellData(CellDataTypeEnum type) {
super();
setType(type);
}
public WriteCellData(CellDataTypeEnum type, String stringValue) {
super();
if (type != CellDataTypeEnum.STRING && type != CellDataTypeEnum.ERROR) {
throw new IllegalArgumentException("Only support CellDataTypeEnum.STRING and CellDataTypeEnum.ERROR");
}
if (stringValue == null) {
throw new IllegalArgumentException("StringValue can not be null");
}
setType(type);
setStringValue(stringValue);
}
public WriteCellData(BigDecimal numberValue) {
super();
if (numberValue == null) {
throw new IllegalArgumentException("DoubleValue can not be null");
}
setType(CellDataTypeEnum.NUMBER);
setNumberValue(numberValue);
}
public WriteCellData(Boolean booleanValue) {
super();
if (booleanValue == null) {
throw new IllegalArgumentException("BooleanValue can not be null");
}
setType(CellDataTypeEnum.BOOLEAN);
setBooleanValue(booleanValue);
}
public WriteCellData(Date dateValue) {
super();
if (dateValue == null) {
throw new IllegalArgumentException("DateValue can not be null");
}
setType(CellDataTypeEnum.DATE);
this.dateValue = LocalDateTime.ofInstant(dateValue.toInstant(), ZoneId.systemDefault());
}
public WriteCellData(LocalDateTime dateValue) {
super();
if (dateValue == null) {
throw new IllegalArgumentException("DateValue can not be null");
}
setType(CellDataTypeEnum.DATE);
this.dateValue = dateValue;
}
public WriteCellData(byte[] image) {
super();
if (image == null) {
throw new IllegalArgumentException("Image can not be null");
}
setType(CellDataTypeEnum.EMPTY);
this.imageDataList = ListUtils.newArrayList();
ImageData imageData = new ImageData();
imageData.setImage(image);
imageDataList.add(imageData);
}
/**
* Return a style, if is empty, create a new
*
* @return not null.
*/
public WriteCellStyle getOrCreateStyle() {
if (this.writeCellStyle == null) {
this.writeCellStyle = new WriteCellStyle();
}
return this.writeCellStyle;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/format/DataFormatter.java
|
/*
* ==================================================================== Licensed to the Apache Software Foundation (ASF)
* under one or more contributor license agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the
* License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* 2012 - Alfresco Software, Ltd. Alfresco Software has modified source of this file The details of changes as svn diff
* can be found in svn at location root/projects/3rd-party/src
* ====================================================================
*/
package ai.chat2db.excel.metadata.format;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import ai.chat2db.excel.util.DateUtils;
import org.apache.poi.ss.format.CellFormat;
import org.apache.poi.ss.format.CellFormatResult;
import org.apache.poi.ss.usermodel.ExcelStyleDateFormatter;
import org.apache.poi.ss.usermodel.FractionFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Written with reference to {@link org.apache.poi.ss.usermodel.DataFormatter}.Made some optimizations for date
* conversion.
* <p>
* This is a non-thread-safe class.
*
* @author Jiaju Zhuang
*/
public class DataFormatter {
/**
* For logging any problems we find
*/
private static final Logger LOGGER = LoggerFactory.getLogger(DataFormatter.class);
private static final String defaultFractionWholePartFormat = "#";
private static final String defaultFractionFractionPartFormat = "#/##";
/**
* Pattern to find a number format: "0" or "#"
*/
private static final Pattern numPattern = Pattern.compile("[0#]+");
/**
* Pattern to find days of week as text "ddd...."
*/
private static final Pattern daysAsText = Pattern.compile("([d]{3,})", Pattern.CASE_INSENSITIVE);
/**
* Pattern to find "AM/PM" marker
*/
private static final Pattern amPmPattern =
Pattern.compile("(([AP])[M/P]*)|(([上下])[午/下]*)", Pattern.CASE_INSENSITIVE);
/**
* Pattern to find formats with condition ranges e.g. [>=100]
*/
private static final Pattern rangeConditionalPattern =
Pattern.compile(".*\\[\\s*(>|>=|<|<=|=)\\s*[0-9]*\\.*[0-9].*");
/**
* A regex to find locale patterns like [$$-1009] and [$?-452]. Note that we don't currently process these into
* locales
*/
private static final Pattern localePatternGroup = Pattern.compile("(\\[\\$[^-\\]]*-[0-9A-Z]+])");
/**
* A regex to match the colour formattings rules. Allowed colours are: Black, Blue, Cyan, Green, Magenta, Red,
* White, Yellow, "Color n" (1<=n<=56)
*/
private static final Pattern colorPattern = Pattern.compile(
"(\\[BLACK])|(\\[BLUE])|(\\[CYAN])|(\\[GREEN])|" + "(\\[MAGENTA])|(\\[RED])|(\\[WHITE])|(\\[YELLOW])|"
+ "(\\[COLOR\\s*\\d])|(\\[COLOR\\s*[0-5]\\d])|(\\[DBNum(1|2|3)])|(\\[\\$-\\d{0,3}])",
Pattern.CASE_INSENSITIVE);
/**
* A regex to identify a fraction pattern. This requires that replaceAll("\\?", "#") has already been called
*/
private static final Pattern fractionPattern = Pattern.compile("(?:([#\\d]+)\\s+)?(#+)\\s*/\\s*([#\\d]+)");
/**
* A regex to strip junk out of fraction formats
*/
private static final Pattern fractionStripper = Pattern.compile("(\"[^\"]*\")|([^ ?#\\d/]+)");
/**
* A regex to detect if an alternate grouping character is used in a numeric format
*/
private static final Pattern alternateGrouping = Pattern.compile("([#0]([^.#0])[#0]{3})");
private static final Pattern E_NOTATION_PATTERN = Pattern.compile("E(\\d)");
/**
* Cells formatted with a date or time format and which contain invalid date or time values show 255 pound signs
* ("#").
*/
private static final String invalidDateTimeString;
static {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < 255; i++) {buf.append('#');}
invalidDateTimeString = buf.toString();
}
/**
* The decimal symbols of the locale used for formatting values.
*/
private DecimalFormatSymbols decimalSymbols;
/**
* The date symbols of the locale used for formatting values.
*/
private DateFormatSymbols dateSymbols;
/**
* A default format to use when a number pattern cannot be parsed.
*/
private Format defaultNumFormat;
/**
* A map to cache formats. Map<String,Format> formats
*/
private final Map<String, Format> formats = new HashMap<String, Format>();
/**
* stores the locale valid it the last formatting call
*/
private Locale locale;
/**
* true if date uses 1904 windowing, or false if using 1900 date windowing.
*
* default is false
*
* @return
*/
private Boolean use1904windowing;
/**
* Whether to use scientific Format.
*
* default is false
*/
private Boolean useScientificFormat;
/**
* Creates a formatter using the given locale.
*/
public DataFormatter(Boolean use1904windowing, Locale locale, Boolean useScientificFormat) {
if (use1904windowing == null) {
this.use1904windowing = Boolean.FALSE;
} else {
this.use1904windowing = use1904windowing;
}
if (locale == null) {
this.locale = Locale.getDefault();
} else {
this.locale = locale;
}
if (use1904windowing == null) {
this.useScientificFormat = Boolean.FALSE;
} else {
this.useScientificFormat = useScientificFormat;
}
this.dateSymbols = DateFormatSymbols.getInstance(this.locale);
this.decimalSymbols = DecimalFormatSymbols.getInstance(this.locale);
}
private Format getFormat(Double data, Short dataFormat, String dataFormatString) {
// Might be better to separate out the n p and z formats, falling back to p when n and z are not set.
// That however would require other code to be re factored.
// String[] formatBits = formatStrIn.split(";");
// int i = cellValue > 0.0 ? 0 : cellValue < 0.0 ? 1 : 2;
// String formatStr = (i < formatBits.length) ? formatBits[i] : formatBits[0];
String formatStr = dataFormatString;
// Excel supports 2+ part conditional data formats, eg positive/negative/zero,
// or (>1000),(>0),(0),(negative). As Java doesn't handle these kinds
// of different formats for different ranges, just +ve/-ve, we need to
// handle these ourselves in a special way.
// For now, if we detect 2+ parts, we call out to CellFormat to handle it
// TODO Going forward, we should really merge the logic between the two classes
if (formatStr.contains(";") &&
(formatStr.indexOf(';') != formatStr.lastIndexOf(';')
|| rangeConditionalPattern.matcher(formatStr).matches()
)) {
try {
// Ask CellFormat to get a formatter for it
CellFormat cfmt = CellFormat.getInstance(locale, formatStr);
// CellFormat requires callers to identify date vs not, so do so
Object cellValueO = data;
if (DateUtils.isADateFormat(dataFormat, formatStr) &&
// don't try to handle Date value 0, let a 3 or 4-part format take care of it
data.doubleValue() != 0.0) {
cellValueO = DateUtils.getJavaDate(data, use1904windowing);
}
// Wrap and return (non-cachable - CellFormat does that)
return new CellFormatResultWrapper(cfmt.apply(cellValueO));
} catch (Exception e) {
LOGGER.warn("Formatting failed for format {}, falling back", formatStr, e);
}
}
// See if we already have it cached
Format format = formats.get(formatStr);
if (format != null) {
return format;
}
// Is it one of the special built in types, General or @?
if ("General".equalsIgnoreCase(formatStr) || "@".equals(formatStr)) {
format = getDefaultFormat();
addFormat(formatStr, format);
return format;
}
// Build a formatter, and cache it
format = createFormat(dataFormat, formatStr);
addFormat(formatStr, format);
return format;
}
private Format createFormat(Short dataFormat, String dataFormatString) {
String formatStr = dataFormatString;
Format format = checkSpecialConverter(formatStr);
if (format != null) {
return format;
}
// Remove colour formatting if present
Matcher colourM = colorPattern.matcher(formatStr);
while (colourM.find()) {
String colour = colourM.group();
// Paranoid replacement...
int at = formatStr.indexOf(colour);
if (at == -1) {break;}
String nFormatStr = formatStr.substring(0, at) + formatStr.substring(at + colour.length());
if (nFormatStr.equals(formatStr)) {break;}
// Try again in case there's multiple
formatStr = nFormatStr;
colourM = colorPattern.matcher(formatStr);
}
// Strip off the locale information, we use an instance-wide locale for everything
Matcher m = localePatternGroup.matcher(formatStr);
while (m.find()) {
String match = m.group();
String symbol = match.substring(match.indexOf('$') + 1, match.indexOf('-'));
if (symbol.indexOf('$') > -1) {
symbol = symbol.substring(0, symbol.indexOf('$')) + '\\' + symbol.substring(symbol.indexOf('$'));
}
formatStr = m.replaceAll(symbol);
m = localePatternGroup.matcher(formatStr);
}
// Check for special cases
if (formatStr == null || formatStr.trim().length() == 0) {
return getDefaultFormat();
}
if ("General".equalsIgnoreCase(formatStr) || "@".equals(formatStr)) {
return getDefaultFormat();
}
if (DateUtils.isADateFormat(dataFormat, formatStr)) {
return createDateFormat(formatStr);
}
// Excel supports fractions in format strings, which Java doesn't
if (formatStr.contains("#/") || formatStr.contains("?/")) {
String[] chunks = formatStr.split(";");
for (String chunk1 : chunks) {
String chunk = chunk1.replaceAll("\\?", "#");
Matcher matcher = fractionStripper.matcher(chunk);
chunk = matcher.replaceAll(" ");
chunk = chunk.replaceAll(" +", " ");
Matcher fractionMatcher = fractionPattern.matcher(chunk);
// take the first match
if (fractionMatcher.find()) {
String wholePart = (fractionMatcher.group(1) == null) ? "" : defaultFractionWholePartFormat;
return new FractionFormat(wholePart, fractionMatcher.group(3));
}
}
// Strip custom text in quotes and escaped characters for now as it can cause performance problems in
// fractions.
// String strippedFormatStr = formatStr.replaceAll("\\\\ ", " ").replaceAll("\\\\.",
// "").replaceAll("\"[^\"]*\"", " ").replaceAll("\\?", "#");
return new FractionFormat(defaultFractionWholePartFormat, defaultFractionFractionPartFormat);
}
if (numPattern.matcher(formatStr).find()) {
return createNumberFormat(formatStr);
}
return getDefaultFormat();
}
private Format checkSpecialConverter(String dataFormatString) {
if ("00000\\-0000".equals(dataFormatString) || "00000-0000".equals(dataFormatString)) {
return new ZipPlusFourFormat();
}
if ("[<=9999999]###\\-####;\\(###\\)\\ ###\\-####".equals(dataFormatString)
|| "[<=9999999]###-####;(###) ###-####".equals(dataFormatString)
|| "###\\-####;\\(###\\)\\ ###\\-####".equals(dataFormatString)
|| "###-####;(###) ###-####".equals(dataFormatString)) {
return new PhoneFormat();
}
if ("000\\-00\\-0000".equals(dataFormatString) || "000-00-0000".equals(dataFormatString)) {
return new SSNFormat();
}
return null;
}
private Format createDateFormat(String pFormatStr) {
String formatStr = pFormatStr;
formatStr = formatStr.replaceAll("\\\\-", "-");
formatStr = formatStr.replaceAll("\\\\,", ",");
formatStr = formatStr.replaceAll("\\\\\\.", "."); // . is a special regexp char
formatStr = formatStr.replaceAll("\\\\ ", " ");
formatStr = formatStr.replaceAll("\\\\/", "/"); // weird: m\\/d\\/yyyy
formatStr = formatStr.replaceAll(";@", "");
formatStr = formatStr.replaceAll("\"/\"", "/"); // "/" is escaped for no reason in: mm"/"dd"/"yyyy
formatStr = formatStr.replace("\"\"", "'"); // replace Excel quoting with Java style quoting
formatStr = formatStr.replaceAll("\\\\T", "'T'"); // Quote the T is iso8601 style dates
formatStr = formatStr.replace("\"", "");
boolean hasAmPm = false;
Matcher amPmMatcher = amPmPattern.matcher(formatStr);
while (amPmMatcher.find()) {
formatStr = amPmMatcher.replaceAll("@");
hasAmPm = true;
amPmMatcher = amPmPattern.matcher(formatStr);
}
formatStr = formatStr.replaceAll("@", "a");
Matcher dateMatcher = daysAsText.matcher(formatStr);
if (dateMatcher.find()) {
String match = dateMatcher.group(0).toUpperCase(Locale.ROOT).replaceAll("D", "E");
formatStr = dateMatcher.replaceAll(match);
}
// Convert excel date format to SimpleDateFormat.
// Excel uses lower and upper case 'm' for both minutes and months.
// From Excel help:
/*
The "m" or "mm" code must appear immediately after the "h" or"hh"
code or immediately before the "ss" code; otherwise, Microsoft
Excel displays the month instead of minutes."
*/
StringBuilder sb = new StringBuilder();
char[] chars = formatStr.toCharArray();
boolean mIsMonth = true;
List<Integer> ms = new ArrayList<Integer>();
boolean isElapsed = false;
for (int j = 0; j < chars.length; j++) {
char c = chars[j];
if (c == '\'') {
sb.append(c);
j++;
// skip until the next quote
while (j < chars.length) {
c = chars[j];
sb.append(c);
if (c == '\'') {
break;
}
j++;
}
} else if (c == '[' && !isElapsed) {
isElapsed = true;
mIsMonth = false;
sb.append(c);
} else if (c == ']' && isElapsed) {
isElapsed = false;
sb.append(c);
} else if (isElapsed) {
if (c == 'h' || c == 'H') {
sb.append('H');
} else if (c == 'm' || c == 'M') {
sb.append('m');
} else if (c == 's' || c == 'S') {
sb.append('s');
} else {
sb.append(c);
}
} else if (c == 'h' || c == 'H') {
mIsMonth = false;
if (hasAmPm) {
sb.append('h');
} else {
sb.append('H');
}
} else if (c == 'm' || c == 'M') {
if (mIsMonth) {
sb.append('M');
ms.add(Integer.valueOf(sb.length() - 1));
} else {
sb.append('m');
}
} else if (c == 's' || c == 'S') {
sb.append('s');
// if 'M' precedes 's' it should be minutes ('m')
for (int index : ms) {
if (sb.charAt(index) == 'M') {
sb.replace(index, index + 1, "m");
}
}
mIsMonth = true;
ms.clear();
} else if (Character.isLetter(c)) {
mIsMonth = true;
ms.clear();
if (c == 'y' || c == 'Y') {
sb.append('y');
} else if (c == 'd' || c == 'D') {
sb.append('d');
} else {
sb.append(c);
}
} else {
if (Character.isWhitespace(c)) {
ms.clear();
}
sb.append(c);
}
}
formatStr = sb.toString();
try {
return new ExcelStyleDateFormatter(formatStr, dateSymbols);
} catch (IllegalArgumentException iae) {
LOGGER.debug("Formatting failed for format {}, falling back", formatStr, iae);
// the pattern could not be parsed correctly,
// so fall back to the default number format
return getDefaultFormat();
}
}
private String cleanFormatForNumber(String formatStr) {
StringBuilder sb = new StringBuilder(formatStr);
// If they requested spacers, with "_",
// remove those as we don't do spacing
// If they requested full-column-width
// padding, with "*", remove those too
for (int i = 0; i < sb.length(); i++) {
char c = sb.charAt(i);
if (c == '_' || c == '*') {
if (i > 0 && sb.charAt((i - 1)) == '\\') {
// It's escaped, don't worry
continue;
}
if (i < sb.length() - 1) {
// Remove the character we're supposed
// to match the space of / pad to the
// column width with
sb.deleteCharAt(i + 1);
}
// Remove the _ too
sb.deleteCharAt(i);
i--;
}
}
// Now, handle the other aspects like
// quoting and scientific notation
for (int i = 0; i < sb.length(); i++) {
char c = sb.charAt(i);
// remove quotes and back slashes
if (c == '\\' || c == '"') {
sb.deleteCharAt(i);
i--;
// for scientific/engineering notation
} else if (c == '+' && i > 0 && sb.charAt(i - 1) == 'E') {
sb.deleteCharAt(i);
i--;
}
}
return sb.toString();
}
private static class InternalDecimalFormatWithScale extends Format {
private static final Pattern endsWithCommas = Pattern.compile("(,+)$");
private BigDecimal divider;
private static final BigDecimal ONE_THOUSAND = new BigDecimal(1000);
private final DecimalFormat df;
private static String trimTrailingCommas(String s) {
return s.replaceAll(",+$", "");
}
public InternalDecimalFormatWithScale(String pattern, DecimalFormatSymbols symbols) {
df = new DecimalFormat(trimTrailingCommas(pattern), symbols);
setExcelStyleRoundingMode(df);
Matcher endsWithCommasMatcher = endsWithCommas.matcher(pattern);
if (endsWithCommasMatcher.find()) {
String commas = (endsWithCommasMatcher.group(1));
BigDecimal temp = BigDecimal.ONE;
for (int i = 0; i < commas.length(); ++i) {
temp = temp.multiply(ONE_THOUSAND);
}
divider = temp;
} else {
divider = null;
}
}
private Object scaleInput(Object obj) {
if (divider != null) {
if (obj instanceof BigDecimal) {
obj = ((BigDecimal)obj).divide(divider, RoundingMode.HALF_UP);
} else if (obj instanceof Double) {
obj = (Double)obj / divider.doubleValue();
} else {
throw new UnsupportedOperationException();
}
}
return obj;
}
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
obj = scaleInput(obj);
return df.format(obj, toAppendTo, pos);
}
@Override
public Object parseObject(String source, ParsePosition pos) {
throw new UnsupportedOperationException();
}
}
private Format createNumberFormat(String formatStr) {
String format = cleanFormatForNumber(formatStr);
DecimalFormatSymbols symbols = decimalSymbols;
// Do we need to change the grouping character?
// eg for a format like #'##0 which wants 12'345 not 12,345
Matcher agm = alternateGrouping.matcher(format);
if (agm.find()) {
char grouping = agm.group(2).charAt(0);
// Only replace the grouping character if it is not the default
// grouping character for the US locale (',') in order to enable
// correct grouping for non-US locales.
if (grouping != ',') {
symbols = DecimalFormatSymbols.getInstance(locale);
symbols.setGroupingSeparator(grouping);
String oldPart = agm.group(1);
String newPart = oldPart.replace(grouping, ',');
format = format.replace(oldPart, newPart);
}
}
try {
return new InternalDecimalFormatWithScale(format, symbols);
} catch (IllegalArgumentException iae) {
LOGGER.error("Formatting failed for format {}, falling back", formatStr, iae);
// the pattern could not be parsed correctly,
// so fall back to the default number format
return getDefaultFormat();
}
}
private Format getDefaultFormat() {
// for numeric cells try user supplied default
if (defaultNumFormat != null) {
return defaultNumFormat;
// otherwise use general format
}
defaultNumFormat = new ExcelGeneralNumberFormat(locale, useScientificFormat);
return defaultNumFormat;
}
/**
* Performs Excel-style date formatting, using the supplied Date and format
*/
private String performDateFormatting(Date d, Format dateFormat) {
Format df = dateFormat != null ? dateFormat : getDefaultFormat();
return df.format(d);
}
/**
* Returns the formatted value of an Excel date as a <tt>String</tt> based on the cell's <code>DataFormat</code>.
* i.e. "Thursday, January 02, 2003" , "01/02/2003" , "02-Jan" , etc.
* <p>
* If any conditional format rules apply, the highest priority with a number format is used. If no rules contain a
* number format, or no rules apply, the cell's style format is used. If the style does not have a format, the
* default date format is applied.
*
* @param data to format
* @param dataFormat
* @param dataFormatString
* @return Formatted value
*/
private String getFormattedDateString(Double data, Short dataFormat, String dataFormatString) {
Format dateFormat = getFormat(data, dataFormat, dataFormatString);
if (dateFormat instanceof ExcelStyleDateFormatter) {
// Hint about the raw excel value
((ExcelStyleDateFormatter)dateFormat).setDateToBeFormatted(data);
}
return performDateFormatting(DateUtils.getJavaDate(data, use1904windowing), dateFormat);
}
/**
* Returns the formatted value of an Excel number as a <tt>String</tt> based on the cell's <code>DataFormat</code>.
* Supported formats include currency, percents, decimals, phone number, SSN, etc.: "61.54%", "$100.00", "(800)
* 555-1234".
* <p>
* Format comes from either the highest priority conditional format rule with a specified format, or from the cell
* style.
*
* @param data to format
* @param dataFormat
* @param dataFormatString
* @return a formatted number string
*/
private String getFormattedNumberString(BigDecimal data, Short dataFormat, String dataFormatString) {
Format numberFormat = getFormat(data.doubleValue(), dataFormat, dataFormatString);
return E_NOTATION_PATTERN.matcher(numberFormat.format(data)).replaceFirst("E+$1");
}
/**
* Format data.
*
* @param data
* @param dataFormat
* @param dataFormatString
* @return
*/
public String format(BigDecimal data, Short dataFormat, String dataFormatString) {
if (DateUtils.isADateFormat(dataFormat, dataFormatString)) {
return getFormattedDateString(data.doubleValue(), dataFormat, dataFormatString);
}
return getFormattedNumberString(data, dataFormat, dataFormatString);
}
/**
* <p>
* Sets a default number format to be used when the Excel format cannot be parsed successfully. <b>Note:</b> This is
* a fall back for when an error occurs while parsing an Excel number format pattern. This will not affect cells
* with the <em>General</em> format.
* </p>
* <p>
* The value that will be passed to the Format's format method (specified by <code>java.text.Format#format</code>)
* will be a double value from a numeric cell. Therefore the code in the format method should expect a
* <code>Number</code> value.
* </p>
*
* @param format A Format instance to be used as a default
* @see Format#format
*/
public void setDefaultNumberFormat(Format format) {
for (Map.Entry<String, Format> entry : formats.entrySet()) {
if (entry.getValue() == defaultNumFormat) {
entry.setValue(format);
}
}
defaultNumFormat = format;
}
/**
* Adds a new format to the available formats.
* <p>
* The value that will be passed to the Format's format method (specified by <code>java.text.Format#format</code>)
* will be a double value from a numeric cell. Therefore the code in the format method should expect a
* <code>Number</code> value.
* </p>
*
* @param excelFormatStr The data format string
* @param format A Format instance
*/
public void addFormat(String excelFormatStr, Format format) {
formats.put(excelFormatStr, format);
}
// Some custom formats
/**
* @return a <tt>DecimalFormat</tt> with parseIntegerOnly set <code>true</code>
*/
private static DecimalFormat createIntegerOnlyFormat(String fmt) {
DecimalFormatSymbols dsf = DecimalFormatSymbols.getInstance(Locale.ROOT);
DecimalFormat result = new DecimalFormat(fmt, dsf);
result.setParseIntegerOnly(true);
return result;
}
/**
* Enables excel style rounding mode (round half up) on the Decimal Format given.
*/
public static void setExcelStyleRoundingMode(DecimalFormat format) {
setExcelStyleRoundingMode(format, RoundingMode.HALF_UP);
}
/**
* Enables custom rounding mode on the given Decimal Format.
*
* @param format DecimalFormat
* @param roundingMode RoundingMode
*/
public static void setExcelStyleRoundingMode(DecimalFormat format, RoundingMode roundingMode) {
format.setRoundingMode(roundingMode);
}
/**
* Format class for Excel's SSN format. This class mimics Excel's built-in SSN formatting.
*
* @author James May
*/
@SuppressWarnings("serial")
private static final class SSNFormat extends Format {
private static final DecimalFormat df = createIntegerOnlyFormat("000000000");
private SSNFormat() {
// enforce singleton
}
/**
* Format a number as an SSN
*/
public static String format(Number num) {
String result = df.format(num);
return result.substring(0, 3) + '-' + result.substring(3, 5) + '-' + result.substring(5, 9);
}
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
return toAppendTo.append(format((Number)obj));
}
@Override
public Object parseObject(String source, ParsePosition pos) {
return df.parseObject(source, pos);
}
}
/**
* Format class for Excel Zip + 4 format. This class mimics Excel's built-in formatting for Zip + 4.
*
* @author James May
*/
@SuppressWarnings("serial")
private static final class ZipPlusFourFormat extends Format {
private static final DecimalFormat df = createIntegerOnlyFormat("000000000");
private ZipPlusFourFormat() {
// enforce singleton
}
/**
* Format a number as Zip + 4
*/
public static String format(Number num) {
String result = df.format(num);
return result.substring(0, 5) + '-' + result.substring(5, 9);
}
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
return toAppendTo.append(format((Number)obj));
}
@Override
public Object parseObject(String source, ParsePosition pos) {
return df.parseObject(source, pos);
}
}
/**
* Format class for Excel phone number format. This class mimics Excel's built-in phone number formatting.
*
* @author James May
*/
@SuppressWarnings("serial")
private static final class PhoneFormat extends Format {
private static final DecimalFormat df = createIntegerOnlyFormat("##########");
private PhoneFormat() {
// enforce singleton
}
/**
* Format a number as a phone number
*/
public static String format(Number num) {
String result = df.format(num);
StringBuilder sb = new StringBuilder();
String seg1, seg2, seg3;
int len = result.length();
if (len <= 4) {
return result;
}
seg3 = result.substring(len - 4, len);
seg2 = result.substring(Math.max(0, len - 7), len - 4);
seg1 = result.substring(Math.max(0, len - 10), Math.max(0, len - 7));
if (seg1.trim().length() > 0) {
sb.append('(').append(seg1).append(") ");
}
if (seg2.trim().length() > 0) {
sb.append(seg2).append('-');
}
sb.append(seg3);
return sb.toString();
}
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
return toAppendTo.append(format((Number)obj));
}
@Override
public Object parseObject(String source, ParsePosition pos) {
return df.parseObject(source, pos);
}
}
/**
* Workaround until we merge {@link org.apache.poi.ss.usermodel.DataFormatter} with {@link CellFormat}. Constant,
* non-cachable wrapper around a
* {@link CellFormatResult}
*/
private final class CellFormatResultWrapper extends Format {
private final CellFormatResult result;
private CellFormatResultWrapper(CellFormatResult result) {
this.result = result;
}
@Override
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
return toAppendTo.append(result.text.trim());
}
@Override
public Object parseObject(String source, ParsePosition pos) {
return null; // Not supported
}
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/format/ExcelGeneralNumberFormat.java
|
package ai.chat2db.excel.metadata.format;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.FieldPosition;
import java.text.Format;
import java.text.ParsePosition;
import java.util.Locale;
import org.apache.poi.ss.usermodel.DataFormatter;
/**
* Written with reference to {@link org.apache.poi.ss.usermodel.ExcelGeneralNumberFormat }.
* <p>
* Supported Do not use scientific notation.
*
* @author JiaJu Zhuang
**/
public class ExcelGeneralNumberFormat extends Format {
private static final long serialVersionUID = 1L;
private static final MathContext TO_10_SF = new MathContext(10, RoundingMode.HALF_UP);
private final DecimalFormatSymbols decimalSymbols;
private final DecimalFormat integerFormat;
private final DecimalFormat decimalFormat;
private final DecimalFormat scientificFormat;
public ExcelGeneralNumberFormat(final Locale locale, final boolean useScientificFormat) {
decimalSymbols = DecimalFormatSymbols.getInstance(locale);
// Supported Do not use scientific notation.
if (useScientificFormat) {
scientificFormat = new DecimalFormat("0.#####E0", decimalSymbols);
} else {
scientificFormat = new DecimalFormat("#", decimalSymbols);
}
org.apache.poi.ss.usermodel.DataFormatter.setExcelStyleRoundingMode(scientificFormat);
integerFormat = new DecimalFormat("#", decimalSymbols);
org.apache.poi.ss.usermodel.DataFormatter.setExcelStyleRoundingMode(integerFormat);
decimalFormat = new DecimalFormat("#.##########", decimalSymbols);
DataFormatter.setExcelStyleRoundingMode(decimalFormat);
}
@Override
public StringBuffer format(Object number, StringBuffer toAppendTo, FieldPosition pos) {
final double value;
if (number instanceof Number) {
value = ((Number) number).doubleValue();
if (Double.isInfinite(value) || Double.isNaN(value)) {
return integerFormat.format(number, toAppendTo, pos);
}
} else {
// testBug54786 gets here with a date, so retain previous behaviour
return integerFormat.format(number, toAppendTo, pos);
}
final double abs = Math.abs(value);
if (abs >= 1E11 || (abs <= 1E-10 && abs > 0)) {
return scientificFormat.format(number, toAppendTo, pos);
} else if (Math.floor(value) == value || abs >= 1E10) {
// integer, or integer portion uses all 11 allowed digits
return integerFormat.format(number, toAppendTo, pos);
}
// Non-integers of non-scientific magnitude are formatted as "up to 11
// numeric characters, with the decimal point counting as a numeric
// character". We know there is a decimal point, so limit to 10 digits.
// https://support.microsoft.com/en-us/kb/65903
final double rounded = new BigDecimal(value).round(TO_10_SF).doubleValue();
return decimalFormat.format(rounded, toAppendTo, pos);
}
@Override
public Object parseObject(String source, ParsePosition pos) {
throw new UnsupportedOperationException();
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/property/ColumnWidthProperty.java
|
package ai.chat2db.excel.metadata.property;
import ai.chat2db.excel.annotation.write.style.ColumnWidth;
/**
* Configuration from annotations
*
* @author Jiaju Zhuang
*/
public class ColumnWidthProperty {
private Integer width;
public ColumnWidthProperty(Integer width) {
this.width = width;
}
public static ColumnWidthProperty build(ColumnWidth columnWidth) {
if (columnWidth == null || columnWidth.value() < 0) {
return null;
}
return new ColumnWidthProperty(columnWidth.value());
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/property/DateTimeFormatProperty.java
|
package ai.chat2db.excel.metadata.property;
import ai.chat2db.excel.annotation.format.DateTimeFormat;
import ai.chat2db.excel.util.BooleanUtils;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Configuration from annotations
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class DateTimeFormatProperty {
private String format;
private Boolean use1904windowing;
public DateTimeFormatProperty(String format, Boolean use1904windowing) {
this.format = format;
this.use1904windowing = use1904windowing;
}
public static DateTimeFormatProperty build(DateTimeFormat dateTimeFormat) {
if (dateTimeFormat == null) {
return null;
}
return new DateTimeFormatProperty(dateTimeFormat.value(),
BooleanUtils.isTrue(dateTimeFormat.use1904windowing().getBooleanValue()));
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/property/ExcelContentProperty.java
|
package ai.chat2db.excel.metadata.property;
import java.lang.reflect.Field;
import ai.chat2db.excel.converters.Converter;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author jipengfei
*/
@Getter
@Setter
@EqualsAndHashCode
public class ExcelContentProperty {
public static final ExcelContentProperty EMPTY = new ExcelContentProperty();
/**
* Java field
*/
private Field field;
/**
* Custom defined converters
*/
private Converter<?> converter;
/**
* date time format
*/
private DateTimeFormatProperty dateTimeFormatProperty;
/**
* number format
*/
private NumberFormatProperty numberFormatProperty;
/**
* Content style
*/
private StyleProperty contentStyleProperty;
/**
* Content font
*/
private FontProperty contentFontProperty;
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/property/ExcelHeadProperty.java
|
package ai.chat2db.excel.metadata.property;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import ai.chat2db.excel.enums.HeadKindEnum;
import ai.chat2db.excel.metadata.ConfigurationHolder;
import ai.chat2db.excel.metadata.FieldCache;
import ai.chat2db.excel.metadata.FieldWrapper;
import ai.chat2db.excel.metadata.Head;
import ai.chat2db.excel.util.ClassUtils;
import ai.chat2db.excel.util.StringUtils;
import ai.chat2db.excel.write.metadata.holder.AbstractWriteHolder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Define the header attribute of excel
*
* @author jipengfei
*/
@Getter
@Setter
@EqualsAndHashCode
public class ExcelHeadProperty {
private static final Logger LOGGER = LoggerFactory.getLogger(ExcelHeadProperty.class);
/**
* Custom class
*/
private Class<?> headClazz;
/**
* The types of head
*/
private HeadKindEnum headKind;
/**
* The number of rows in the line with the most rows
*/
private int headRowNumber;
/**
* Configuration header information
*/
private Map<Integer, Head> headMap;
public ExcelHeadProperty(ConfigurationHolder configurationHolder, Class<?> headClazz, List<List<String>> head) {
this.headClazz = headClazz;
headMap = new TreeMap<>();
headKind = HeadKindEnum.NONE;
headRowNumber = 0;
if (head != null && !head.isEmpty()) {
int headIndex = 0;
for (int i = 0; i < head.size(); i++) {
if (configurationHolder instanceof AbstractWriteHolder) {
if (((AbstractWriteHolder)configurationHolder).ignore(null, i)) {
continue;
}
}
headMap.put(headIndex, new Head(headIndex, null, null, head.get(i), Boolean.FALSE, Boolean.TRUE));
headIndex++;
}
headKind = HeadKindEnum.STRING;
}
// convert headClazz to head
initColumnProperties(configurationHolder);
initHeadRowNumber();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("The initialization sheet/table 'ExcelHeadProperty' is complete , head kind is {}", headKind);
}
}
private void initHeadRowNumber() {
headRowNumber = 0;
for (Head head : headMap.values()) {
List<String> list = head.getHeadNameList();
if (list != null && list.size() > headRowNumber) {
headRowNumber = list.size();
}
}
for (Head head : headMap.values()) {
List<String> list = head.getHeadNameList();
if (list != null && !list.isEmpty() && list.size() < headRowNumber) {
int lack = headRowNumber - list.size();
int last = list.size() - 1;
for (int i = 0; i < lack; i++) {
list.add(list.get(last));
}
}
}
}
private void initColumnProperties(ConfigurationHolder configurationHolder) {
if (headClazz == null) {
return;
}
FieldCache fieldCache = ClassUtils.declaredFields(headClazz, configurationHolder);
for (Map.Entry<Integer, FieldWrapper> entry : fieldCache.getSortedFieldMap().entrySet()) {
initOneColumnProperty(entry.getKey(), entry.getValue(),
fieldCache.getIndexFieldMap().containsKey(entry.getKey()));
}
headKind = HeadKindEnum.CLASS;
}
/**
* Initialization column property
*
* @param index
* @param field
* @param forceIndex
* @return Ignore current field
*/
private void initOneColumnProperty(int index, FieldWrapper field, Boolean forceIndex) {
List<String> tmpHeadList = new ArrayList<>();
boolean notForceName = field.getHeads() == null || field.getHeads().length == 0
|| (field.getHeads().length == 1 && StringUtils.isEmpty(field.getHeads()[0]));
if (headMap.containsKey(index)) {
tmpHeadList.addAll(headMap.get(index).getHeadNameList());
} else {
if (notForceName) {
tmpHeadList.add(field.getFieldName());
} else {
Collections.addAll(tmpHeadList, field.getHeads());
}
}
Head head = new Head(index, field.getField(), field.getFieldName(), tmpHeadList, forceIndex, !notForceName);
headMap.put(index, head);
}
public boolean hasHead() {
return headKind != HeadKindEnum.NONE;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/property/FontProperty.java
|
package ai.chat2db.excel.metadata.property;
import ai.chat2db.excel.annotation.write.style.ContentFontStyle;
import ai.chat2db.excel.annotation.write.style.HeadFontStyle;
import ai.chat2db.excel.util.StringUtils;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.common.usermodel.fonts.FontCharset;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
/**
* Configuration from annotations
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class FontProperty {
/**
* The name for the font (i.e. Arial)
*/
private String fontName;
/**
* Height in the familiar unit of measure - points
*/
private Short fontHeightInPoints;
/**
* Whether to use italics or not
*/
private Boolean italic;
/**
* Whether to use a strikeout horizontal line through the text or not
*/
private Boolean strikeout;
/**
* The color for the font
*
* @see Font#COLOR_NORMAL
* @see Font#COLOR_RED
* @see HSSFPalette#getColor(short)
* @see IndexedColors
*/
private Short color;
/**
* Set normal, super or subscript.
*
* @see Font#SS_NONE
* @see Font#SS_SUPER
* @see Font#SS_SUB
*/
private Short typeOffset;
/**
* set type of text underlining to use
*
* @see Font#U_NONE
* @see Font#U_SINGLE
* @see Font#U_DOUBLE
* @see Font#U_SINGLE_ACCOUNTING
* @see Font#U_DOUBLE_ACCOUNTING
*/
private Byte underline;
/**
* Set character-set to use.
*
* @see FontCharset
* @see Font#ANSI_CHARSET
* @see Font#DEFAULT_CHARSET
* @see Font#SYMBOL_CHARSET
*/
private Integer charset;
/**
* Bold
*/
private Boolean bold;
public static FontProperty build(HeadFontStyle headFontStyle) {
if (headFontStyle == null) {
return null;
}
FontProperty styleProperty = new FontProperty();
if (StringUtils.isNotBlank(headFontStyle.fontName())) {
styleProperty.setFontName(headFontStyle.fontName());
}
if (headFontStyle.fontHeightInPoints() >= 0) {
styleProperty.setFontHeightInPoints(headFontStyle.fontHeightInPoints());
}
styleProperty.setItalic(headFontStyle.italic().getBooleanValue());
styleProperty.setStrikeout(headFontStyle.strikeout().getBooleanValue());
if (headFontStyle.color() >= 0) {
styleProperty.setColor(headFontStyle.color());
}
if (headFontStyle.typeOffset() >= 0) {
styleProperty.setTypeOffset(headFontStyle.typeOffset());
}
if (headFontStyle.underline() >= 0) {
styleProperty.setUnderline(headFontStyle.underline());
}
if (headFontStyle.charset() >= 0) {
styleProperty.setCharset(headFontStyle.charset());
}
styleProperty.setBold(headFontStyle.bold().getBooleanValue());
return styleProperty;
}
public static FontProperty build(ContentFontStyle contentFontStyle) {
if (contentFontStyle == null) {
return null;
}
FontProperty styleProperty = new FontProperty();
if (StringUtils.isNotBlank(contentFontStyle.fontName())) {
styleProperty.setFontName(contentFontStyle.fontName());
}
if (contentFontStyle.fontHeightInPoints() >= 0) {
styleProperty.setFontHeightInPoints(contentFontStyle.fontHeightInPoints());
}
styleProperty.setItalic(contentFontStyle.italic().getBooleanValue());
styleProperty.setStrikeout(contentFontStyle.strikeout().getBooleanValue());
if (contentFontStyle.color() >= 0) {
styleProperty.setColor(contentFontStyle.color());
}
if (contentFontStyle.typeOffset() >= 0) {
styleProperty.setTypeOffset(contentFontStyle.typeOffset());
}
if (contentFontStyle.underline() >= 0) {
styleProperty.setUnderline(contentFontStyle.underline());
}
if (contentFontStyle.charset() >= 0) {
styleProperty.setCharset(contentFontStyle.charset());
}
styleProperty.setBold(contentFontStyle.bold().getBooleanValue());
return styleProperty;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/property/LoopMergeProperty.java
|
package ai.chat2db.excel.metadata.property;
import ai.chat2db.excel.annotation.write.style.ContentLoopMerge;
/**
* Configuration from annotations
*
* @author Jiaju Zhuang
*/
public class LoopMergeProperty {
/**
* Each row
*/
private int eachRow;
/**
* Extend column
*/
private int columnExtend;
public LoopMergeProperty(int eachRow, int columnExtend) {
this.eachRow = eachRow;
this.columnExtend = columnExtend;
}
public static LoopMergeProperty build(ContentLoopMerge contentLoopMerge) {
if (contentLoopMerge == null) {
return null;
}
return new LoopMergeProperty(contentLoopMerge.eachRow(), contentLoopMerge.columnExtend());
}
public int getEachRow() {
return eachRow;
}
public void setEachRow(int eachRow) {
this.eachRow = eachRow;
}
public int getColumnExtend() {
return columnExtend;
}
public void setColumnExtend(int columnExtend) {
this.columnExtend = columnExtend;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/property/NumberFormatProperty.java
|
package ai.chat2db.excel.metadata.property;
import java.math.RoundingMode;
import ai.chat2db.excel.annotation.format.NumberFormat;
/**
* Configuration from annotations
*
* @author Jiaju Zhuang
*/
public class NumberFormatProperty {
private String format;
private RoundingMode roundingMode;
public NumberFormatProperty(String format, RoundingMode roundingMode) {
this.format = format;
this.roundingMode = roundingMode;
}
public static NumberFormatProperty build(NumberFormat numberFormat) {
if (numberFormat == null) {
return null;
}
return new NumberFormatProperty(numberFormat.value(), numberFormat.roundingMode());
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public RoundingMode getRoundingMode() {
return roundingMode;
}
public void setRoundingMode(RoundingMode roundingMode) {
this.roundingMode = roundingMode;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/property/OnceAbsoluteMergeProperty.java
|
package ai.chat2db.excel.metadata.property;
import ai.chat2db.excel.annotation.write.style.OnceAbsoluteMerge;
/**
* Configuration from annotations
*
* @author Jiaju Zhuang
*/
public class OnceAbsoluteMergeProperty {
/**
* First row
*/
private int firstRowIndex;
/**
* Last row
*/
private int lastRowIndex;
/**
* First column
*/
private int firstColumnIndex;
/**
* Last row
*/
private int lastColumnIndex;
public OnceAbsoluteMergeProperty(int firstRowIndex, int lastRowIndex, int firstColumnIndex, int lastColumnIndex) {
this.firstRowIndex = firstRowIndex;
this.lastRowIndex = lastRowIndex;
this.firstColumnIndex = firstColumnIndex;
this.lastColumnIndex = lastColumnIndex;
}
public static OnceAbsoluteMergeProperty build(OnceAbsoluteMerge onceAbsoluteMerge) {
if (onceAbsoluteMerge == null) {
return null;
}
return new OnceAbsoluteMergeProperty(onceAbsoluteMerge.firstRowIndex(), onceAbsoluteMerge.lastRowIndex(),
onceAbsoluteMerge.firstColumnIndex(), onceAbsoluteMerge.lastColumnIndex());
}
public int getFirstRowIndex() {
return firstRowIndex;
}
public void setFirstRowIndex(int firstRowIndex) {
this.firstRowIndex = firstRowIndex;
}
public int getLastRowIndex() {
return lastRowIndex;
}
public void setLastRowIndex(int lastRowIndex) {
this.lastRowIndex = lastRowIndex;
}
public int getFirstColumnIndex() {
return firstColumnIndex;
}
public void setFirstColumnIndex(int firstColumnIndex) {
this.firstColumnIndex = firstColumnIndex;
}
public int getLastColumnIndex() {
return lastColumnIndex;
}
public void setLastColumnIndex(int lastColumnIndex) {
this.lastColumnIndex = lastColumnIndex;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/property/RowHeightProperty.java
|
package ai.chat2db.excel.metadata.property;
import ai.chat2db.excel.annotation.write.style.ContentRowHeight;
import ai.chat2db.excel.annotation.write.style.HeadRowHeight;
/**
* Configuration from annotations
*
* @author Jiaju Zhuang
*/
public class RowHeightProperty {
private Short height;
public RowHeightProperty(Short height) {
this.height = height;
}
public static RowHeightProperty build(HeadRowHeight headRowHeight) {
if (headRowHeight == null || headRowHeight.value() < 0) {
return null;
}
return new RowHeightProperty(headRowHeight.value());
}
public static RowHeightProperty build(ContentRowHeight contentRowHeight) {
if (contentRowHeight == null || contentRowHeight.value() < 0) {
return null;
}
return new RowHeightProperty(contentRowHeight.value());
}
public Short getHeight() {
return height;
}
public void setHeight(Short height) {
this.height = height;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/metadata/property/StyleProperty.java
|
package ai.chat2db.excel.metadata.property;
import ai.chat2db.excel.annotation.write.style.ContentStyle;
import ai.chat2db.excel.annotation.write.style.HeadStyle;
import ai.chat2db.excel.metadata.data.DataFormatData;
import ai.chat2db.excel.write.metadata.style.WriteFont;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.BuiltinFormats;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IgnoredErrorType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
/**
* Configuration from annotations
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class StyleProperty {
/**
* Set the data format (must be a valid format). Built in formats are defined at {@link BuiltinFormats}.
*/
private DataFormatData dataFormatData;
/**
* Set the font for this style
*/
private WriteFont writeFont;
/**
* Set the cell's using this style to be hidden
*/
private Boolean hidden;
/**
* Set the cell's using this style to be locked
*/
private Boolean locked;
/**
* Turn on or off "Quote Prefix" or "123 Prefix" for the style, which is used to tell Excel that the thing which
* looks like a number or a formula shouldn't be treated as on. Turning this on is somewhat (but not completely, see
* {@link IgnoredErrorType}) like prefixing the cell value with a ' in Excel
*/
private Boolean quotePrefix;
/**
* Set the type of horizontal alignment for the cell
*/
private HorizontalAlignment horizontalAlignment;
/**
* Set whether the text should be wrapped. Setting this flag to <code>true</code> make all content visible within a
* cell by displaying it on multiple lines
*/
private Boolean wrapped;
/**
* Set the type of vertical alignment for the cell
*/
private VerticalAlignment verticalAlignment;
/**
* Set the degree of rotation for the text in the cell.
*
* Note: HSSF uses values from -90 to 90 degrees, whereas XSSF uses values from 0 to 180 degrees. The
* implementations of this method will map between these two value-ranges accordingly, however the corresponding
* getter is returning values in the range mandated by the current type of Excel file-format that this CellStyle is
* applied to.
*/
private Short rotation;
/**
* Set the number of spaces to indent the text in the cell
*/
private Short indent;
/**
* Set the type of border to use for the left border of the cell
*/
private BorderStyle borderLeft;
/**
* Set the type of border to use for the right border of the cell
*/
private BorderStyle borderRight;
/**
* Set the type of border to use for the top border of the cell
*/
private BorderStyle borderTop;
/**
* Set the type of border to use for the bottom border of the cell
*/
private BorderStyle borderBottom;
/**
* Set the color to use for the left border
*
* @see IndexedColors
*/
private Short leftBorderColor;
/**
* Set the color to use for the right border
*
* @see IndexedColors
*/
private Short rightBorderColor;
/**
* Set the color to use for the top border
*
* @see IndexedColors
*/
private Short topBorderColor;
/**
* Set the color to use for the bottom border
*
* @see IndexedColors
*/
private Short bottomBorderColor;
/**
* Setting to one fills the cell with the foreground color... No idea about other values
*
* @see FillPatternType#SOLID_FOREGROUND
*/
private FillPatternType fillPatternType;
/**
* Set the background fill color.
*
* @see IndexedColors
*/
private Short fillBackgroundColor;
/**
* Set the foreground fill color <i>Note: Ensure Foreground color is set prior to background color.</i>
*
* @see IndexedColors
*/
private Short fillForegroundColor;
/**
* Controls if the Cell should be auto-sized to shrink to fit if the text is too long
*/
private Boolean shrinkToFit;
public static StyleProperty build(HeadStyle headStyle) {
if (headStyle == null) {
return null;
}
StyleProperty styleProperty = new StyleProperty();
if (headStyle.dataFormat() >= 0) {
DataFormatData dataFormatData = new DataFormatData();
dataFormatData.setIndex(headStyle.dataFormat());
styleProperty.setDataFormatData(dataFormatData);
}
styleProperty.setHidden(headStyle.hidden().getBooleanValue());
styleProperty.setLocked(headStyle.locked().getBooleanValue());
styleProperty.setQuotePrefix(headStyle.quotePrefix().getBooleanValue());
styleProperty.setHorizontalAlignment(headStyle.horizontalAlignment().getPoiHorizontalAlignment());
styleProperty.setWrapped(headStyle.wrapped().getBooleanValue());
styleProperty.setVerticalAlignment(headStyle.verticalAlignment().getPoiVerticalAlignmentEnum());
if (headStyle.rotation() >= 0) {
styleProperty.setRotation(headStyle.rotation());
}
if (headStyle.indent() >= 0) {
styleProperty.setIndent(headStyle.indent());
}
styleProperty.setBorderLeft(headStyle.borderLeft().getPoiBorderStyle());
styleProperty.setBorderRight(headStyle.borderRight().getPoiBorderStyle());
styleProperty.setBorderTop(headStyle.borderTop().getPoiBorderStyle());
styleProperty.setBorderBottom(headStyle.borderBottom().getPoiBorderStyle());
if (headStyle.leftBorderColor() >= 0) {
styleProperty.setLeftBorderColor(headStyle.leftBorderColor());
}
if (headStyle.rightBorderColor() >= 0) {
styleProperty.setRightBorderColor(headStyle.rightBorderColor());
}
if (headStyle.topBorderColor() >= 0) {
styleProperty.setTopBorderColor(headStyle.topBorderColor());
}
if (headStyle.bottomBorderColor() >= 0) {
styleProperty.setBottomBorderColor(headStyle.bottomBorderColor());
}
styleProperty.setFillPatternType(headStyle.fillPatternType().getPoiFillPatternType());
if (headStyle.fillBackgroundColor() >= 0) {
styleProperty.setFillBackgroundColor(headStyle.fillBackgroundColor());
}
if (headStyle.fillForegroundColor() >= 0) {
styleProperty.setFillForegroundColor(headStyle.fillForegroundColor());
}
styleProperty.setShrinkToFit(headStyle.shrinkToFit().getBooleanValue());
return styleProperty;
}
public static StyleProperty build(ContentStyle contentStyle) {
if (contentStyle == null) {
return null;
}
StyleProperty styleProperty = new StyleProperty();
if (contentStyle.dataFormat() >= 0) {
DataFormatData dataFormatData = new DataFormatData();
dataFormatData.setIndex(contentStyle.dataFormat());
styleProperty.setDataFormatData(dataFormatData);
}
styleProperty.setHidden(contentStyle.hidden().getBooleanValue());
styleProperty.setLocked(contentStyle.locked().getBooleanValue());
styleProperty.setQuotePrefix(contentStyle.quotePrefix().getBooleanValue());
styleProperty.setHorizontalAlignment(contentStyle.horizontalAlignment().getPoiHorizontalAlignment());
styleProperty.setWrapped(contentStyle.wrapped().getBooleanValue());
styleProperty.setVerticalAlignment(contentStyle.verticalAlignment().getPoiVerticalAlignmentEnum());
if (contentStyle.rotation() >= 0) {
styleProperty.setRotation(contentStyle.rotation());
}
if (contentStyle.indent() >= 0) {
styleProperty.setIndent(contentStyle.indent());
}
styleProperty.setBorderLeft(contentStyle.borderLeft().getPoiBorderStyle());
styleProperty.setBorderRight(contentStyle.borderRight().getPoiBorderStyle());
styleProperty.setBorderTop(contentStyle.borderTop().getPoiBorderStyle());
styleProperty.setBorderBottom(contentStyle.borderBottom().getPoiBorderStyle());
if (contentStyle.leftBorderColor() >= 0) {
styleProperty.setLeftBorderColor(contentStyle.leftBorderColor());
}
if (contentStyle.rightBorderColor() >= 0) {
styleProperty.setRightBorderColor(contentStyle.rightBorderColor());
}
if (contentStyle.topBorderColor() >= 0) {
styleProperty.setTopBorderColor(contentStyle.topBorderColor());
}
if (contentStyle.bottomBorderColor() >= 0) {
styleProperty.setBottomBorderColor(contentStyle.bottomBorderColor());
}
styleProperty.setFillPatternType(contentStyle.fillPatternType().getPoiFillPatternType());
if (contentStyle.fillBackgroundColor() >= 0) {
styleProperty.setFillBackgroundColor(contentStyle.fillBackgroundColor());
}
if (contentStyle.fillForegroundColor() >= 0) {
styleProperty.setFillForegroundColor(contentStyle.fillForegroundColor());
}
styleProperty.setShrinkToFit(contentStyle.shrinkToFit().getBooleanValue());
return styleProperty;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/builder/AbstractExcelReaderParameterBuilder.java
|
package ai.chat2db.excel.read.builder;
import ai.chat2db.excel.read.listener.ReadListener;
import ai.chat2db.excel.read.metadata.ReadBasicParameter;
import ai.chat2db.excel.util.ListUtils;
import ai.chat2db.excel.metadata.AbstractParameterBuilder;
/**
* Build ExcelBuilder
*
* @author Jiaju Zhuang
*/
public abstract class AbstractExcelReaderParameterBuilder<T extends AbstractExcelReaderParameterBuilder,
C extends ReadBasicParameter> extends AbstractParameterBuilder<T, C> {
/**
* Count the number of added heads when read sheet.
*
* <p>
* 0 - This Sheet has no head ,since the first row are the data
* <p>
* 1 - This Sheet has one row head , this is the default
* <p>
* 2 - This Sheet has two row head ,since the third row is the data
*
* @param headRowNumber
* @return
*/
public T headRowNumber(Integer headRowNumber) {
parameter().setHeadRowNumber(headRowNumber);
return self();
}
/**
* Whether to use scientific Format.
*
* default is false
*
* @param useScientificFormat
* @return
*/
public T useScientificFormat(Boolean useScientificFormat) {
parameter().setUseScientificFormat(useScientificFormat);
return self();
}
/**
* Custom type listener run after default
*
* @param readListener
* @return
*/
public T registerReadListener(ReadListener<?> readListener) {
if (parameter().getCustomReadListenerList() == null) {
parameter().setCustomReadListenerList(ListUtils.newArrayList());
}
parameter().getCustomReadListenerList().add(readListener);
return self();
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/builder/ExcelReaderBuilder.java
|
package ai.chat2db.excel.read.builder;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.List;
import javax.xml.parsers.SAXParserFactory;
import ai.chat2db.excel.cache.ReadCache;
import ai.chat2db.excel.cache.selector.ReadCacheSelector;
import ai.chat2db.excel.cache.selector.SimpleReadCacheSelector;
import ai.chat2db.excel.enums.CellExtraTypeEnum;
import ai.chat2db.excel.enums.ReadDefaultReturnEnum;
import ai.chat2db.excel.event.AnalysisEventListener;
import ai.chat2db.excel.event.SyncReadListener;
import ai.chat2db.excel.read.listener.ModelBuildEventListener;
import ai.chat2db.excel.read.metadata.ReadWorkbook;
import ai.chat2db.excel.ExcelReader;
import ai.chat2db.excel.context.AnalysisContext;
import ai.chat2db.excel.support.ExcelTypeEnum;
/**
* Build ExcelWriter
*
* @author Jiaju Zhuang
*/
public class ExcelReaderBuilder extends AbstractExcelReaderParameterBuilder<ExcelReaderBuilder, ReadWorkbook> {
/**
* Workbook
*/
private final ReadWorkbook readWorkbook;
public ExcelReaderBuilder() {
this.readWorkbook = new ReadWorkbook();
}
public ExcelReaderBuilder excelType(ExcelTypeEnum excelType) {
readWorkbook.setExcelType(excelType);
return this;
}
/**
* Read InputStream
* <p>
* If 'inputStream' and 'file' all not empty, file first
*/
public ExcelReaderBuilder file(InputStream inputStream) {
readWorkbook.setInputStream(inputStream);
return this;
}
/**
* Read file
* <p>
* If 'inputStream' and 'file' all not empty, file first
*/
public ExcelReaderBuilder file(File file) {
readWorkbook.setFile(file);
return this;
}
/**
* Read file
* <p>
* If 'inputStream' and 'file' all not empty, file first
*/
public ExcelReaderBuilder file(String pathName) {
return file(new File(pathName));
}
/**
* charset.
* Only work on the CSV file
*/
public ExcelReaderBuilder charset(Charset charset) {
readWorkbook.setCharset(charset);
return this;
}
/**
* Mandatory use 'inputStream' .Default is false.
* <p>
* if false, Will transfer 'inputStream' to temporary files to improve efficiency
*/
public ExcelReaderBuilder mandatoryUseInputStream(Boolean mandatoryUseInputStream) {
readWorkbook.setMandatoryUseInputStream(mandatoryUseInputStream);
return this;
}
/**
* Default true
*
* @param autoCloseStream
* @return
*/
public ExcelReaderBuilder autoCloseStream(Boolean autoCloseStream) {
readWorkbook.setAutoCloseStream(autoCloseStream);
return this;
}
/**
* Ignore empty rows.Default is true.
*
* @param ignoreEmptyRow
* @return
*/
public ExcelReaderBuilder ignoreEmptyRow(Boolean ignoreEmptyRow) {
readWorkbook.setIgnoreEmptyRow(ignoreEmptyRow);
return this;
}
/**
* This object can be read in the Listener {@link AnalysisEventListener#invoke(Object, AnalysisContext)}
* {@link AnalysisContext#getCustom()}
*
* @param customObject
* @return
*/
public ExcelReaderBuilder customObject(Object customObject) {
readWorkbook.setCustomObject(customObject);
return this;
}
/**
* A cache that stores temp data to save memory.
*
* @param readCache
* @return
*/
public ExcelReaderBuilder readCache(ReadCache readCache) {
readWorkbook.setReadCache(readCache);
return this;
}
/**
* Select the cache.Default use {@link SimpleReadCacheSelector}
*
* @param readCacheSelector
* @return
*/
public ExcelReaderBuilder readCacheSelector(ReadCacheSelector readCacheSelector) {
readWorkbook.setReadCacheSelector(readCacheSelector);
return this;
}
/**
* Whether the encryption
*
* @param password
* @return
*/
public ExcelReaderBuilder password(String password) {
readWorkbook.setPassword(password);
return this;
}
/**
* SAXParserFactory used when reading xlsx.
* <p>
* The default will automatically find.
* <p>
* Please pass in the name of a class ,like : "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl"
*
* @param xlsxSAXParserFactoryName
* @return
* @see SAXParserFactory#newInstance()
* @see SAXParserFactory#newInstance(String, ClassLoader)
*/
public ExcelReaderBuilder xlsxSAXParserFactoryName(String xlsxSAXParserFactoryName) {
readWorkbook.setXlsxSAXParserFactoryName(xlsxSAXParserFactoryName);
return this;
}
/**
* Read some extra information, not by default
*
* @param extraType extra information type
* @return
*/
public ExcelReaderBuilder extraRead(CellExtraTypeEnum extraType) {
if (readWorkbook.getExtraReadSet() == null) {
readWorkbook.setExtraReadSet(new HashSet<CellExtraTypeEnum>());
}
readWorkbook.getExtraReadSet().add(extraType);
return this;
}
/**
* Whether to use the default listener, which is used by default.
* <p>
* The {@link ModelBuildEventListener} is loaded by default to convert the object.
*
* @param useDefaultListener
* @return
*/
public ExcelReaderBuilder useDefaultListener(Boolean useDefaultListener) {
readWorkbook.setUseDefaultListener(useDefaultListener);
return this;
}
/**
* Read not to {@code ai.chat2db.excel.metadata.BasicParameter#clazz} value, the default will return type.
* Is only effective when set `useDefaultListener=true` or `useDefaultListener=null`.
*
* @see ReadDefaultReturnEnum
*/
public ExcelReaderBuilder readDefaultReturn(ReadDefaultReturnEnum readDefaultReturn) {
readWorkbook.setReadDefaultReturn(readDefaultReturn);
return this;
}
public ExcelReader build() {
return new ExcelReader(readWorkbook);
}
public void doReadAll() {
try (ExcelReader excelReader = build()) {
excelReader.readAll();
}
}
/**
* Synchronous reads return results
*
* @return
*/
public <T> List<T> doReadAllSync() {
SyncReadListener syncReadListener = new SyncReadListener();
registerReadListener(syncReadListener);
try (ExcelReader excelReader = build()) {
excelReader.readAll();
excelReader.finish();
}
return (List<T>)syncReadListener.getList();
}
public ExcelReaderSheetBuilder sheet() {
return sheet(null, null);
}
public ExcelReaderSheetBuilder sheet(Integer sheetNo) {
return sheet(sheetNo, null);
}
public ExcelReaderSheetBuilder sheet(String sheetName) {
return sheet(null, sheetName);
}
public ExcelReaderSheetBuilder sheet(Integer sheetNo, String sheetName) {
ExcelReaderSheetBuilder excelReaderSheetBuilder = new ExcelReaderSheetBuilder(build());
if (sheetNo != null) {
excelReaderSheetBuilder.sheetNo(sheetNo);
}
if (sheetName != null) {
excelReaderSheetBuilder.sheetName(sheetName);
}
return excelReaderSheetBuilder;
}
@Override
protected ReadWorkbook parameter() {
return readWorkbook;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/builder/ExcelReaderSheetBuilder.java
|
package ai.chat2db.excel.read.builder;
import java.util.List;
import ai.chat2db.excel.event.SyncReadListener;
import ai.chat2db.excel.read.metadata.ReadSheet;
import ai.chat2db.excel.ExcelReader;
import ai.chat2db.excel.exception.ExcelAnalysisException;
import ai.chat2db.excel.exception.ExcelGenerateException;
/**
* Build sheet
*
* @author Jiaju Zhuang
*/
public class ExcelReaderSheetBuilder extends AbstractExcelReaderParameterBuilder<ExcelReaderSheetBuilder, ReadSheet> {
private ExcelReader excelReader;
/**
* Sheet
*/
private final ReadSheet readSheet;
public ExcelReaderSheetBuilder() {
this.readSheet = new ReadSheet();
}
public ExcelReaderSheetBuilder(ExcelReader excelReader) {
this.readSheet = new ReadSheet();
this.excelReader = excelReader;
}
/**
* Starting from 0
*
* @param sheetNo
* @return
*/
public ExcelReaderSheetBuilder sheetNo(Integer sheetNo) {
readSheet.setSheetNo(sheetNo);
return this;
}
/**
* sheet name
*
* @param sheetName
* @return
*/
public ExcelReaderSheetBuilder sheetName(String sheetName) {
readSheet.setSheetName(sheetName);
return this;
}
public ReadSheet build() {
return readSheet;
}
/**
* Sax read
*/
public void doRead() {
if (excelReader == null) {
throw new ExcelGenerateException("Must use 'EasyExcelFactory.read().sheet()' to call this method");
}
excelReader.read(build());
excelReader.finish();
}
/**
* Synchronous reads return results
*
* @return
*/
public <T> List<T> doReadSync() {
if (excelReader == null) {
throw new ExcelAnalysisException("Must use 'EasyExcelFactory.read().sheet()' to call this method");
}
SyncReadListener syncReadListener = new SyncReadListener();
registerReadListener(syncReadListener);
excelReader.read(build());
excelReader.finish();
return (List<T>)syncReadListener.getList();
}
@Override
protected ReadSheet parameter() {
return readSheet;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/listener/IgnoreExceptionReadListener.java
|
package ai.chat2db.excel.read.listener;
import ai.chat2db.excel.context.AnalysisContext;
/**
* Interface to listen for read results
*
* @author Jiaju Zhuang
*/
public interface IgnoreExceptionReadListener<T> extends ReadListener<T> {
/**
* All listeners receive this method when any one Listener does an error report. If an exception is thrown here, the
* entire read will terminate.
*
* @param exception
* @param context
* @throws Exception
*/
@Override
default void onException(Exception exception, AnalysisContext context) throws Exception {}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/listener/ModelBuildEventListener.java
|
package ai.chat2db.excel.read.listener;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Map;
import ai.chat2db.excel.enums.CellDataTypeEnum;
import ai.chat2db.excel.enums.HeadKindEnum;
import ai.chat2db.excel.enums.ReadDefaultReturnEnum;
import ai.chat2db.excel.read.metadata.holder.ReadSheetHolder;
import ai.chat2db.excel.read.metadata.property.ExcelReadHeadProperty;
import ai.chat2db.excel.context.AnalysisContext;
import ai.chat2db.excel.exception.ExcelDataConvertException;
import ai.chat2db.excel.metadata.Head;
import ai.chat2db.excel.metadata.data.DataFormatData;
import ai.chat2db.excel.metadata.data.ReadCellData;
import ai.chat2db.excel.support.cglib.beans.BeanMap;
import ai.chat2db.excel.util.BeanMapUtils;
import ai.chat2db.excel.util.ClassUtils;
import ai.chat2db.excel.util.ConverterUtils;
import ai.chat2db.excel.util.DateUtils;
import ai.chat2db.excel.util.MapUtils;
/**
* Convert to the object the user needs
*
* @author jipengfei
*/
public class ModelBuildEventListener implements IgnoreExceptionReadListener<Map<Integer, ReadCellData<?>>> {
@Override
public void invoke(Map<Integer, ReadCellData<?>> cellDataMap, AnalysisContext context) {
ReadSheetHolder readSheetHolder = context.readSheetHolder();
if (HeadKindEnum.CLASS.equals(readSheetHolder.excelReadHeadProperty().getHeadKind())) {
context.readRowHolder()
.setCurrentRowAnalysisResult(buildUserModel(cellDataMap, readSheetHolder, context));
return;
}
context.readRowHolder().setCurrentRowAnalysisResult(buildNoModel(cellDataMap, readSheetHolder, context));
}
private Object buildNoModel(Map<Integer, ReadCellData<?>> cellDataMap, ReadSheetHolder readSheetHolder,
AnalysisContext context) {
int index = 0;
Map<Integer, Object> map = MapUtils.newLinkedHashMapWithExpectedSize(cellDataMap.size());
for (Map.Entry<Integer, ReadCellData<?>> entry : cellDataMap.entrySet()) {
Integer key = entry.getKey();
ReadCellData<?> cellData = entry.getValue();
while (index < key) {
map.put(index, null);
index++;
}
index++;
ReadDefaultReturnEnum readDefaultReturn = context.readWorkbookHolder().getReadDefaultReturn();
if (readDefaultReturn == ReadDefaultReturnEnum.STRING) {
// string
map.put(key,
(String) ConverterUtils.convertToJavaObject(cellData, null, null, readSheetHolder.converterMap(),
context, context.readRowHolder().getRowIndex(), key));
} else {
// retrun ReadCellData
ReadCellData<?> convertedReadCellData = convertReadCellData(cellData,
context.readWorkbookHolder().getReadDefaultReturn(), readSheetHolder, context, key);
if (readDefaultReturn == ReadDefaultReturnEnum.READ_CELL_DATA) {
map.put(key, convertedReadCellData);
} else {
map.put(key, convertedReadCellData.getData());
}
}
}
// fix https://github.com/CodePhiliaX/easyexcel-plus/issues/2014
int headSize = calculateHeadSize(readSheetHolder);
while (index < headSize) {
map.put(index, null);
index++;
}
return map;
}
private ReadCellData convertReadCellData(ReadCellData<?> cellData, ReadDefaultReturnEnum readDefaultReturn,
ReadSheetHolder readSheetHolder, AnalysisContext context, Integer columnIndex) {
Class<?> classGeneric;
switch (cellData.getType()) {
case STRING:
case DIRECT_STRING:
case ERROR:
case EMPTY:
classGeneric = String.class;
break;
case BOOLEAN:
classGeneric = Boolean.class;
break;
case NUMBER:
DataFormatData dataFormatData = cellData.getDataFormatData();
if (dataFormatData != null && DateUtils.isADateFormat(dataFormatData.getIndex(),
dataFormatData.getFormat())) {
classGeneric = LocalDateTime.class;
} else {
classGeneric = BigDecimal.class;
}
break;
default:
classGeneric = ConverterUtils.defaultClassGeneric;
break;
}
return (ReadCellData)ConverterUtils.convertToJavaObject(cellData, null, ReadCellData.class,
classGeneric, null, readSheetHolder.converterMap(), context, context.readRowHolder().getRowIndex(),
columnIndex);
}
private int calculateHeadSize(ReadSheetHolder readSheetHolder) {
if (readSheetHolder.excelReadHeadProperty().getHeadMap().size() > 0) {
return readSheetHolder.excelReadHeadProperty().getHeadMap().size();
}
if (readSheetHolder.getMaxNotEmptyDataHeadSize() != null) {
return readSheetHolder.getMaxNotEmptyDataHeadSize();
}
return 0;
}
private Object buildUserModel(Map<Integer, ReadCellData<?>> cellDataMap, ReadSheetHolder readSheetHolder,
AnalysisContext context) {
ExcelReadHeadProperty excelReadHeadProperty = readSheetHolder.excelReadHeadProperty();
Object resultModel;
try {
resultModel = excelReadHeadProperty.getHeadClazz().newInstance();
} catch (Exception e) {
throw new ExcelDataConvertException(context.readRowHolder().getRowIndex(), 0,
new ReadCellData<>(CellDataTypeEnum.EMPTY), null,
"Can not instance class: " + excelReadHeadProperty.getHeadClazz().getName(), e);
}
Map<Integer, Head> headMap = excelReadHeadProperty.getHeadMap();
BeanMap dataMap = BeanMapUtils.create(resultModel);
for (Map.Entry<Integer, Head> entry : headMap.entrySet()) {
Integer index = entry.getKey();
Head head = entry.getValue();
String fieldName = head.getFieldName();
if (!cellDataMap.containsKey(index)) {
continue;
}
ReadCellData<?> cellData = cellDataMap.get(index);
Object value = ConverterUtils.convertToJavaObject(cellData, head.getField(),
ClassUtils.declaredExcelContentProperty(dataMap, readSheetHolder.excelReadHeadProperty().getHeadClazz(),
fieldName, readSheetHolder), readSheetHolder.converterMap(), context,
context.readRowHolder().getRowIndex(), index);
if (value != null) {
dataMap.put(fieldName, value);
}
}
return resultModel;
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/listener/PageReadListener.java
|
package ai.chat2db.excel.read.listener;
import java.util.List;
import java.util.function.Consumer;
import ai.chat2db.excel.util.ListUtils;
import ai.chat2db.excel.context.AnalysisContext;
import org.apache.commons.collections4.CollectionUtils;
/**
* page read listener
*
* @author Jiaju Zhuang
*/
public class PageReadListener<T> implements ReadListener<T> {
/**
* Default single handle the amount of data
*/
public static int BATCH_COUNT = 100;
/**
* Temporary storage of data
*/
private List<T> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
/**
* consumer
*/
private final Consumer<List<T>> consumer;
/**
* Single handle the amount of data
*/
private final int batchCount;
public PageReadListener(Consumer<List<T>> consumer) {
this(consumer, BATCH_COUNT);
}
public PageReadListener(Consumer<List<T>> consumer, int batchCount) {
this.consumer = consumer;
this.batchCount = batchCount;
}
@Override
public void invoke(T data, AnalysisContext context) {
cachedDataList.add(data);
if (cachedDataList.size() >= batchCount) {
consumer.accept(cachedDataList);
cachedDataList = ListUtils.newArrayListWithExpectedSize(batchCount);
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
if (CollectionUtils.isNotEmpty(cachedDataList)) {
consumer.accept(cachedDataList);
}
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/listener/ReadListener.java
|
package ai.chat2db.excel.read.listener;
import java.util.Map;
import ai.chat2db.excel.event.Listener;
import ai.chat2db.excel.context.AnalysisContext;
import ai.chat2db.excel.metadata.CellExtra;
import ai.chat2db.excel.metadata.data.ReadCellData;
/**
* Interface to listen for read results
*
* @author Jiaju Zhuang
*/
public interface ReadListener<T> extends Listener {
/**
* All listeners receive this method when any one Listener does an error report. If an exception is thrown here, the
* entire read will terminate.
*
* @param exception
* @param context
* @throws Exception
*/
default void onException(Exception exception, AnalysisContext context) throws Exception {
throw exception;
}
/**
* When analysis one head row trigger invoke function.
*
* @param headMap
* @param context
*/
default void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {}
/**
* When analysis one row trigger invoke function.
*
* @param data one row value. It is same as {@link AnalysisContext#readRowHolder()}
* @param context analysis context
*/
void invoke(T data, AnalysisContext context);
/**
* The current method is called when extra information is returned
*
* @param extra extra information
* @param context analysis context
*/
default void extra(CellExtra extra, AnalysisContext context) {}
/**
* if have something to do after all analysis
*
* @param context
*/
void doAfterAllAnalysed(AnalysisContext context);
/**
* Verify that there is another piece of data.You can stop the read by returning false
*
* @param context
* @return
*/
default boolean hasNext(AnalysisContext context) {
return true;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/ReadBasicParameter.java
|
package ai.chat2db.excel.read.metadata;
import java.util.ArrayList;
import java.util.List;
import ai.chat2db.excel.metadata.BasicParameter;
import ai.chat2db.excel.read.listener.ReadListener;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Read basic parameter
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class ReadBasicParameter extends BasicParameter {
/**
* Count the number of added heads when read sheet.
*
* <p>
* 0 - This Sheet has no head ,since the first row are the data
* <p>
* 1 - This Sheet has one row head , this is the default
* <p>
* 2 - This Sheet has two row head ,since the third row is the data
*/
private Integer headRowNumber;
/**
* Custom type listener run after default
*/
private List<ReadListener<?>> customReadListenerList;
public ReadBasicParameter() {
customReadListenerList = new ArrayList<>();
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/ReadSheet.java
|
package ai.chat2db.excel.read.metadata;
/**
* Read sheet
*
* @author jipengfei
*/
public class ReadSheet extends ReadBasicParameter {
/**
* Starting from 0
*/
private Integer sheetNo;
/**
* sheet name
*/
private String sheetName;
public ReadSheet() {}
public ReadSheet(Integer sheetNo) {
this.sheetNo = sheetNo;
}
public ReadSheet(Integer sheetNo, String sheetName) {
this.sheetNo = sheetNo;
this.sheetName = sheetName;
}
public Integer getSheetNo() {
return sheetNo;
}
public void setSheetNo(Integer sheetNo) {
this.sheetNo = sheetNo;
}
public String getSheetName() {
return sheetName;
}
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
public void copyBasicParameter(ReadSheet other) {
if (other == null) {
return;
}
this.setHeadRowNumber(other.getHeadRowNumber());
this.setCustomReadListenerList(other.getCustomReadListenerList());
this.setHead(other.getHead());
this.setClazz(other.getClazz());
this.setCustomConverterList(other.getCustomConverterList());
this.setAutoTrim(other.getAutoTrim());
this.setUse1904windowing(other.getUse1904windowing());
}
@Override
public String toString() {
return "ReadSheet{" + "sheetNo=" + sheetNo + ", sheetName='" + sheetName + '\'' + "} " + super.toString();
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/ReadWorkbook.java
|
package ai.chat2db.excel.read.metadata;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Set;
import javax.xml.parsers.SAXParserFactory;
import ai.chat2db.excel.cache.ReadCache;
import ai.chat2db.excel.cache.selector.ReadCacheSelector;
import ai.chat2db.excel.cache.selector.SimpleReadCacheSelector;
import ai.chat2db.excel.enums.CellExtraTypeEnum;
import ai.chat2db.excel.enums.ReadDefaultReturnEnum;
import ai.chat2db.excel.event.AnalysisEventListener;
import ai.chat2db.excel.context.AnalysisContext;
import ai.chat2db.excel.read.listener.ModelBuildEventListener;
import ai.chat2db.excel.support.ExcelTypeEnum;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Workbook
*
* @author Jiaju Zhuang
**/
@Getter
@Setter
@EqualsAndHashCode
public class ReadWorkbook extends ReadBasicParameter {
/**
* Excel type
*/
private ExcelTypeEnum excelType;
/**
* Read InputStream
* <p>
* If 'inputStream' and 'file' all not empty, file first
*/
private InputStream inputStream;
/**
* Read file
* <p>
* If 'inputStream' and 'file' all not empty, file first
*/
private File file;
/**
* charset.
* Only work on the CSV file
*/
private Charset charset;
/**
* Mandatory use 'inputStream' .Default is false.
* <p>
* if false, Will transfer 'inputStream' to temporary files to improve efficiency
*/
private Boolean mandatoryUseInputStream;
/**
* Default true
*/
private Boolean autoCloseStream;
/**
* This object can be read in the Listener {@link AnalysisEventListener#invoke(Object, AnalysisContext)}
* {@link AnalysisContext#getCustom()}
*/
private Object customObject;
/**
* A cache that stores temp data to save memory.
*/
private ReadCache readCache;
/**
* Ignore empty rows.Default is true.
*/
private Boolean ignoreEmptyRow;
/**
* Select the cache.Default use {@link SimpleReadCacheSelector}
*/
private ReadCacheSelector readCacheSelector;
/**
* Whether the encryption
*/
private String password;
/**
* SAXParserFactory used when reading xlsx.
* <p>
* The default will automatically find.
* <p>
* Please pass in the name of a class ,like : "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl"
*
* @see SAXParserFactory#newInstance()
* @see SAXParserFactory#newInstance(String, ClassLoader)
*/
private String xlsxSAXParserFactoryName;
/**
* Whether to use the default listener, which is used by default.
* <p>
* The {@link ModelBuildEventListener} is loaded by default to convert the object.
* defualt is true.
*/
private Boolean useDefaultListener;
/**
* Read not to {@code ai.chat2db.excel.metadata.BasicParameter#clazz} value, the default will return type.
* Is only effective when set `useDefaultListener=true` or `useDefaultListener=null`.
*
* @see ReadDefaultReturnEnum
*/
private ReadDefaultReturnEnum readDefaultReturn;
/**
* Read some additional fields. None are read by default.
*
* @see CellExtraTypeEnum
*/
private Set<CellExtraTypeEnum> extraReadSet;
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/holder/AbstractReadHolder.java
|
package ai.chat2db.excel.read.metadata.holder;
import java.util.HashMap;
import java.util.List;
import ai.chat2db.excel.enums.HolderEnum;
import ai.chat2db.excel.read.metadata.property.ExcelReadHeadProperty;
import ai.chat2db.excel.util.ListUtils;
import ai.chat2db.excel.converters.Converter;
import ai.chat2db.excel.converters.ConverterKeyBuild;
import ai.chat2db.excel.converters.DefaultConverterLoader;
import ai.chat2db.excel.metadata.AbstractHolder;
import ai.chat2db.excel.read.listener.ModelBuildEventListener;
import ai.chat2db.excel.read.listener.ReadListener;
import ai.chat2db.excel.read.metadata.ReadBasicParameter;
import ai.chat2db.excel.read.metadata.ReadWorkbook;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* Read Holder
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
public abstract class AbstractReadHolder extends AbstractHolder implements ReadHolder {
/**
* Count the number of added heads when read sheet.
*
* <p>
* 0 - This Sheet has no head ,since the first row are the data
* <p>
* 1 - This Sheet has one row head , this is the default
* <p>
* 2 - This Sheet has two row head ,since the third row is the data
*/
private Integer headRowNumber;
/**
* Excel head property
*/
private ExcelReadHeadProperty excelReadHeadProperty;
/**
* Read listener
*/
private List<ReadListener<?>> readListenerList;
public AbstractReadHolder(ReadBasicParameter readBasicParameter, AbstractReadHolder parentAbstractReadHolder) {
super(readBasicParameter, parentAbstractReadHolder);
if (readBasicParameter.getUseScientificFormat() == null) {
if (parentAbstractReadHolder != null) {
getGlobalConfiguration().setUseScientificFormat(
parentAbstractReadHolder.getGlobalConfiguration().getUseScientificFormat());
}
} else {
getGlobalConfiguration().setUseScientificFormat(readBasicParameter.getUseScientificFormat());
}
// Initialization property
this.excelReadHeadProperty = new ExcelReadHeadProperty(this, getClazz(), getHead());
if (readBasicParameter.getHeadRowNumber() == null) {
if (parentAbstractReadHolder == null) {
if (excelReadHeadProperty.hasHead()) {
this.headRowNumber = excelReadHeadProperty.getHeadRowNumber();
} else {
this.headRowNumber = 1;
}
} else {
this.headRowNumber = parentAbstractReadHolder.getHeadRowNumber();
}
} else {
this.headRowNumber = readBasicParameter.getHeadRowNumber();
}
if (parentAbstractReadHolder == null) {
this.readListenerList = ListUtils.newArrayList();
} else {
this.readListenerList = ListUtils.newArrayList(parentAbstractReadHolder.getReadListenerList());
}
if (HolderEnum.WORKBOOK.equals(holderType())) {
Boolean useDefaultListener = ((ReadWorkbook)readBasicParameter).getUseDefaultListener();
if (useDefaultListener == null || useDefaultListener) {
readListenerList.add(new ModelBuildEventListener());
}
}
if (readBasicParameter.getCustomReadListenerList() != null
&& !readBasicParameter.getCustomReadListenerList().isEmpty()) {
this.readListenerList.addAll(readBasicParameter.getCustomReadListenerList());
}
if (parentAbstractReadHolder == null) {
setConverterMap(DefaultConverterLoader.loadDefaultReadConverter());
} else {
setConverterMap(new HashMap<>(parentAbstractReadHolder.getConverterMap()));
}
if (readBasicParameter.getCustomConverterList() != null
&& !readBasicParameter.getCustomConverterList().isEmpty()) {
for (Converter<?> converter : readBasicParameter.getCustomConverterList()) {
getConverterMap().put(
ConverterKeyBuild.buildKey(converter.supportJavaTypeKey(), converter.supportExcelTypeKey()),
converter);
}
}
}
@Override
public List<ReadListener<?>> readListenerList() {
return getReadListenerList();
}
@Override
public ExcelReadHeadProperty excelReadHeadProperty() {
return getExcelReadHeadProperty();
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/holder/ReadHolder.java
|
package ai.chat2db.excel.read.metadata.holder;
import java.util.List;
import ai.chat2db.excel.read.metadata.property.ExcelReadHeadProperty;
import ai.chat2db.excel.metadata.ConfigurationHolder;
import ai.chat2db.excel.read.listener.ReadListener;
/**
*
* Get the corresponding Holder
*
* @author Jiaju Zhuang
**/
public interface ReadHolder extends ConfigurationHolder {
/**
* What handler does the currently operated cell need to execute
*
* @return Current {@link ReadListener}
*/
List<ReadListener<?>> readListenerList();
/**
* What {@link ExcelReadHeadProperty} does the currently operated cell need to execute
*
* @return Current {@link ExcelReadHeadProperty}
*/
ExcelReadHeadProperty excelReadHeadProperty();
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/holder/ReadRowHolder.java
|
package ai.chat2db.excel.read.metadata.holder;
import java.util.Map;
import ai.chat2db.excel.enums.HolderEnum;
import ai.chat2db.excel.enums.RowTypeEnum;
import ai.chat2db.excel.metadata.Cell;
import ai.chat2db.excel.metadata.GlobalConfiguration;
import ai.chat2db.excel.metadata.Holder;
/**
* sheet holder
*
* @author Jiaju Zhuang
*/
public class ReadRowHolder implements Holder {
/**
* Returns row index of a row in the sheet that contains this cell.Start form 0.
*/
private Integer rowIndex;
/**
* Row type
*/
private RowTypeEnum rowType;
/**
* Cell map
*/
private Map<Integer, Cell> cellMap;
/**
* The result of the previous listener
*/
private Object currentRowAnalysisResult;
/**
* Some global variables
*/
private GlobalConfiguration globalConfiguration;
public ReadRowHolder(Integer rowIndex, RowTypeEnum rowType, GlobalConfiguration globalConfiguration,
Map<Integer, Cell> cellMap) {
this.rowIndex = rowIndex;
this.rowType = rowType;
this.globalConfiguration = globalConfiguration;
this.cellMap = cellMap;
}
public GlobalConfiguration getGlobalConfiguration() {
return globalConfiguration;
}
public void setGlobalConfiguration(GlobalConfiguration globalConfiguration) {
this.globalConfiguration = globalConfiguration;
}
public Object getCurrentRowAnalysisResult() {
return currentRowAnalysisResult;
}
public void setCurrentRowAnalysisResult(Object currentRowAnalysisResult) {
this.currentRowAnalysisResult = currentRowAnalysisResult;
}
public Integer getRowIndex() {
return rowIndex;
}
public void setRowIndex(Integer rowIndex) {
this.rowIndex = rowIndex;
}
public RowTypeEnum getRowType() {
return rowType;
}
public void setRowType(RowTypeEnum rowType) {
this.rowType = rowType;
}
public Map<Integer, Cell> getCellMap() {
return cellMap;
}
public void setCellMap(Map<Integer, Cell> cellMap) {
this.cellMap = cellMap;
}
@Override
public HolderEnum holderType() {
return HolderEnum.ROW;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/holder/ReadSheetHolder.java
|
package ai.chat2db.excel.read.metadata.holder;
import java.util.LinkedHashMap;
import java.util.Map;
import ai.chat2db.excel.enums.HolderEnum;
import ai.chat2db.excel.read.metadata.ReadSheet;
import ai.chat2db.excel.metadata.Cell;
import ai.chat2db.excel.metadata.CellExtra;
import ai.chat2db.excel.metadata.data.ReadCellData;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* sheet holder
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
public class ReadSheetHolder extends AbstractReadHolder {
/**
* current param
*/
private ReadSheet readSheet;
/***
* parent
*/
private ReadWorkbookHolder parentReadWorkbookHolder;
/***
* sheetNo
*/
private Integer sheetNo;
/***
* sheetName
*/
private String sheetName;
/**
* Gets the total number of rows , data may be inaccurate
*/
private Integer approximateTotalRowNumber;
/**
* Data storage of the current row.
*/
private Map<Integer, Cell> cellMap;
/**
* Data storage of the current extra cell.
*/
private CellExtra cellExtra;
/**
* Index of the current row.
*/
private Integer rowIndex;
/**
* Current CellData
*/
private ReadCellData<?> tempCellData;
/**
* Read the size of the largest head in sheet head data.
* see https://github.com/CodePhiliaX/easyexcel-plus/issues/2014
*/
private Integer maxNotEmptyDataHeadSize;
/**
* Reading this sheet has ended.
*/
private Boolean ended;
public ReadSheetHolder(ReadSheet readSheet, ReadWorkbookHolder readWorkbookHolder) {
super(readSheet, readWorkbookHolder);
this.readSheet = readSheet;
this.parentReadWorkbookHolder = readWorkbookHolder;
this.sheetNo = readSheet.getSheetNo();
this.sheetName = readSheet.getSheetName();
this.cellMap = new LinkedHashMap<>();
this.rowIndex = -1;
}
/**
* Approximate total number of rows.
* use: getApproximateTotalRowNumber()
*
* @return
*/
@Deprecated
public Integer getTotal() {
return approximateTotalRowNumber;
}
@Override
public HolderEnum holderType() {
return HolderEnum.SHEET;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/holder/ReadWorkbookHolder.java
|
package ai.chat2db.excel.read.metadata.holder;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import ai.chat2db.excel.cache.ReadCache;
import ai.chat2db.excel.cache.selector.EternalReadCacheSelector;
import ai.chat2db.excel.cache.selector.ReadCacheSelector;
import ai.chat2db.excel.cache.selector.SimpleReadCacheSelector;
import ai.chat2db.excel.enums.CellExtraTypeEnum;
import ai.chat2db.excel.enums.HolderEnum;
import ai.chat2db.excel.enums.ReadDefaultReturnEnum;
import ai.chat2db.excel.event.AnalysisEventListener;
import ai.chat2db.excel.read.metadata.ReadSheet;
import ai.chat2db.excel.context.AnalysisContext;
import ai.chat2db.excel.exception.ExcelAnalysisException;
import ai.chat2db.excel.read.metadata.ReadWorkbook;
import ai.chat2db.excel.support.ExcelTypeEnum;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* Workbook holder
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
public class ReadWorkbookHolder extends AbstractReadHolder {
/**
* current param
*/
private ReadWorkbook readWorkbook;
/**
* Read InputStream
* <p>
* If 'inputStream' and 'file' all not empty, file first
*/
private InputStream inputStream;
/**
* Read file
* <p>
* If 'inputStream' and 'file' all not empty, file first
*/
private File file;
/**
* charset.
* Only work on the CSV file
*/
private Charset charset;
/**
* Mandatory use 'inputStream' .Default is false.
* <p>
* if false, Will transfer 'inputStream' to temporary files to improve efficiency
*/
private Boolean mandatoryUseInputStream;
/**
* Default true
*/
private Boolean autoCloseStream;
/**
* Read not to {@code ai.chat2db.excel.metadata.BasicParameter#clazz} value, the default will return type.
* Is only effective when set `useDefaultListener=true` or `useDefaultListener=null`.
*
* @see ReadDefaultReturnEnum
*/
private ReadDefaultReturnEnum readDefaultReturn;
/**
* Excel type
*/
private ExcelTypeEnum excelType;
/**
* This object can be read in the Listener {@link AnalysisEventListener#invoke(Object, AnalysisContext)}
* {@link AnalysisContext#getCustom()}
*/
private Object customObject;
/**
* Ignore empty rows.Default is true.
*/
private Boolean ignoreEmptyRow;
/**
* A cache that stores temp data to save memory.
*/
private ReadCache readCache;
/**
* Select the cache.Default use {@link SimpleReadCacheSelector}
*/
private ReadCacheSelector readCacheSelector;
/**
* Temporary files when reading excel
*/
private File tempFile;
/**
* Whether the encryption
*/
private String password;
/**
* Read some additional fields. None are read by default.
*
* @see CellExtraTypeEnum
*/
private Set<CellExtraTypeEnum> extraReadSet;
/**
* Actual sheet data
*/
private List<ReadSheet> actualSheetDataList;
/**
* Parameter sheet data
*/
private List<ReadSheet> parameterSheetDataList;
/**
* Read all
*/
private Boolean readAll;
/**
* Prevent repeating sheet
*/
private Set<Integer> hasReadSheet;
public ReadWorkbookHolder(ReadWorkbook readWorkbook) {
super(readWorkbook, null);
this.readWorkbook = readWorkbook;
if (readWorkbook.getInputStream() != null) {
this.inputStream = readWorkbook.getInputStream();
}
this.file = readWorkbook.getFile();
if (readWorkbook.getCharset() == null) {
this.charset = Charset.defaultCharset();
} else {
this.charset = readWorkbook.getCharset();
}
if (readWorkbook.getMandatoryUseInputStream() == null) {
this.mandatoryUseInputStream = Boolean.FALSE;
} else {
this.mandatoryUseInputStream = readWorkbook.getMandatoryUseInputStream();
}
if (readWorkbook.getAutoCloseStream() == null) {
this.autoCloseStream = Boolean.TRUE;
} else {
this.autoCloseStream = readWorkbook.getAutoCloseStream();
}
if (readWorkbook.getReadDefaultReturn() == null) {
this.readDefaultReturn = ReadDefaultReturnEnum.STRING;
} else {
this.readDefaultReturn = readWorkbook.getReadDefaultReturn();
}
this.customObject = readWorkbook.getCustomObject();
if (readWorkbook.getIgnoreEmptyRow() == null) {
this.ignoreEmptyRow = Boolean.TRUE;
} else {
this.ignoreEmptyRow = readWorkbook.getIgnoreEmptyRow();
}
if (readWorkbook.getReadCache() != null) {
if (readWorkbook.getReadCacheSelector() != null) {
throw new ExcelAnalysisException("'readCache' and 'readCacheSelector' only one choice.");
}
this.readCacheSelector = new EternalReadCacheSelector(readWorkbook.getReadCache());
} else {
if (readWorkbook.getReadCacheSelector() == null) {
this.readCacheSelector = new SimpleReadCacheSelector();
} else {
this.readCacheSelector = readWorkbook.getReadCacheSelector();
}
}
if (readWorkbook.getExtraReadSet() == null) {
this.extraReadSet = new HashSet<CellExtraTypeEnum>();
} else {
this.extraReadSet = readWorkbook.getExtraReadSet();
}
this.hasReadSheet = new HashSet<Integer>();
this.password = readWorkbook.getPassword();
}
@Override
public HolderEnum holderType() {
return HolderEnum.WORKBOOK;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/holder
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/holder/csv/CsvReadSheetHolder.java
|
package ai.chat2db.excel.read.metadata.holder.csv;
import ai.chat2db.excel.read.metadata.ReadSheet;
import ai.chat2db.excel.read.metadata.holder.ReadSheetHolder;
import ai.chat2db.excel.read.metadata.holder.ReadWorkbookHolder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* sheet holder
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class CsvReadSheetHolder extends ReadSheetHolder {
public CsvReadSheetHolder(ReadSheet readSheet, ReadWorkbookHolder readWorkbookHolder) {
super(readSheet, readWorkbookHolder);
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/holder
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/holder/csv/CsvReadWorkbookHolder.java
|
package ai.chat2db.excel.read.metadata.holder.csv;
import ai.chat2db.excel.read.metadata.ReadWorkbook;
import ai.chat2db.excel.read.metadata.holder.ReadWorkbookHolder;
import ai.chat2db.excel.support.ExcelTypeEnum;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
/**
* Workbook holder
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class CsvReadWorkbookHolder extends ReadWorkbookHolder {
private CSVFormat csvFormat;
private CSVParser csvParser;
public CsvReadWorkbookHolder(ReadWorkbook readWorkbook) {
super(readWorkbook);
setExcelType(ExcelTypeEnum.CSV);
this.csvFormat = CSVFormat.DEFAULT;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/holder
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/holder/xls/XlsReadSheetHolder.java
|
package ai.chat2db.excel.read.metadata.holder.xls;
import java.util.HashMap;
import java.util.Map;
import ai.chat2db.excel.enums.RowTypeEnum;
import ai.chat2db.excel.read.metadata.ReadSheet;
import ai.chat2db.excel.read.metadata.holder.ReadSheetHolder;
import ai.chat2db.excel.read.metadata.holder.ReadWorkbookHolder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* sheet holder
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
public class XlsReadSheetHolder extends ReadSheetHolder {
/**
* Row type.Temporary storage, last set in <code>ReadRowHolder</code>.
*/
private RowTypeEnum tempRowType;
/**
* Temp object index.
*/
private Integer tempObjectIndex;
/**
* Temp object index.
*/
private Map<Integer, String> objectCacheMap;
public XlsReadSheetHolder(ReadSheet readSheet, ReadWorkbookHolder readWorkbookHolder) {
super(readSheet, readWorkbookHolder);
tempRowType = RowTypeEnum.EMPTY;
objectCacheMap = new HashMap<Integer, String>(16);
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/holder
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/holder/xls/XlsReadWorkbookHolder.java
|
package ai.chat2db.excel.read.metadata.holder.xls;
import java.util.ArrayList;
import java.util.List;
import ai.chat2db.excel.read.metadata.ReadWorkbook;
import ai.chat2db.excel.read.metadata.holder.ReadWorkbookHolder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener;
import org.apache.poi.hssf.record.BoundSheetRecord;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import ai.chat2db.excel.support.ExcelTypeEnum;
/**
* Workbook holder
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
public class XlsReadWorkbookHolder extends ReadWorkbookHolder {
/**
* File System
*/
private POIFSFileSystem poifsFileSystem;
/**
* Format tracking HSSFListener
*/
private FormatTrackingHSSFListener formatTrackingHSSFListener;
/**
* HSSFWorkbook
*/
private HSSFWorkbook hssfWorkbook;
/**
* Bound sheet record list.
*/
private List<BoundSheetRecord> boundSheetRecordList;
/**
* Need read sheet.
*/
private Boolean needReadSheet;
/**
* Sheet Index
*/
private Integer readSheetIndex;
/**
* Ignore record.
*/
private Boolean ignoreRecord;
/**
* Has the current sheet already stopped
*/
private Boolean currentSheetStopped;
public XlsReadWorkbookHolder(ReadWorkbook readWorkbook) {
super(readWorkbook);
this.boundSheetRecordList = new ArrayList<BoundSheetRecord>();
this.needReadSheet = Boolean.TRUE;
setExcelType(ExcelTypeEnum.XLS);
if (getGlobalConfiguration().getUse1904windowing() == null) {
getGlobalConfiguration().setUse1904windowing(Boolean.FALSE);
}
ignoreRecord = Boolean.FALSE;
currentSheetStopped = Boolean.TRUE;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/holder
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/holder/xlsx/XlsxReadSheetHolder.java
|
package ai.chat2db.excel.read.metadata.holder.xlsx;
import java.util.Deque;
import java.util.LinkedList;
import ai.chat2db.excel.read.metadata.ReadSheet;
import ai.chat2db.excel.read.metadata.holder.ReadSheetHolder;
import ai.chat2db.excel.read.metadata.holder.ReadWorkbookHolder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
/**
* sheet holder
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class XlsxReadSheetHolder extends ReadSheetHolder {
/**
* Record the label of the current operation to prevent NPE.
*/
private Deque<String> tagDeque;
/**
* Current Column
*/
private Integer columnIndex;
/**
* Data for current label.
*/
private StringBuilder tempData;
/**
* Formula for current label.
*/
private StringBuilder tempFormula;
/**
* excel Relationship
*/
private PackageRelationshipCollection packageRelationshipCollection;
public XlsxReadSheetHolder(ReadSheet readSheet, ReadWorkbookHolder readWorkbookHolder) {
super(readSheet, readWorkbookHolder);
this.tagDeque = new LinkedList<String>();
packageRelationshipCollection
= ((XlsxReadWorkbookHolder)readWorkbookHolder).getPackageRelationshipCollectionMap().get(
readSheet.getSheetNo());
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/holder
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/holder/xlsx/XlsxReadWorkbookHolder.java
|
package ai.chat2db.excel.read.metadata.holder.xlsx;
import java.util.Map;
import javax.xml.parsers.SAXParserFactory;
import ai.chat2db.excel.read.metadata.ReadWorkbook;
import ai.chat2db.excel.read.metadata.holder.ReadWorkbookHolder;
import ai.chat2db.excel.util.MapUtils;
import ai.chat2db.excel.constant.BuiltinFormats;
import ai.chat2db.excel.metadata.data.DataFormatData;
import ai.chat2db.excel.support.ExcelTypeEnum;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
/**
* Workbook holder
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class XlsxReadWorkbookHolder extends ReadWorkbookHolder {
/**
* Package
*/
private OPCPackage opcPackage;
/**
* SAXParserFactory used when reading xlsx.
* <p>
* The default will automatically find.
* <p>
* Please pass in the name of a class ,like : "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl"
*
* @see SAXParserFactory#newInstance()
* @see SAXParserFactory#newInstance(String, ClassLoader)
*/
private String saxParserFactoryName;
/**
* Current style information
*/
private StylesTable stylesTable;
/**
* cache data format
*/
private Map<Integer, DataFormatData> dataFormatDataCache;
/**
* excel Relationship, key: sheetNo value: PackageRelationshipCollection
*/
private Map<Integer, PackageRelationshipCollection> packageRelationshipCollectionMap;
public XlsxReadWorkbookHolder(ReadWorkbook readWorkbook) {
super(readWorkbook);
this.saxParserFactoryName = readWorkbook.getXlsxSAXParserFactoryName();
setExcelType(ExcelTypeEnum.XLSX);
dataFormatDataCache = MapUtils.newHashMap();
}
public DataFormatData dataFormatData(int dateFormatIndexInteger) {
return dataFormatDataCache.computeIfAbsent(dateFormatIndexInteger, key -> {
DataFormatData dataFormatData = new DataFormatData();
if (stylesTable == null) {
return null;
}
XSSFCellStyle xssfCellStyle = stylesTable.getStyleAt(dateFormatIndexInteger);
if (xssfCellStyle == null) {
return null;
}
dataFormatData.setIndex(xssfCellStyle.getDataFormat());
dataFormatData.setFormat(BuiltinFormats.getBuiltinFormat(dataFormatData.getIndex(),
xssfCellStyle.getDataFormatString(), globalConfiguration().getLocale()));
return dataFormatData;
});
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/metadata/property/ExcelReadHeadProperty.java
|
package ai.chat2db.excel.read.metadata.property;
import java.util.List;
import ai.chat2db.excel.metadata.ConfigurationHolder;
import ai.chat2db.excel.metadata.property.ExcelHeadProperty;
/**
* Define the header attribute of excel
*
* @author jipengfei
*/
public class ExcelReadHeadProperty extends ExcelHeadProperty {
public ExcelReadHeadProperty(ConfigurationHolder configurationHolder, Class headClazz, List<List<String>> head) {
super(configurationHolder, headClazz, head);
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/processor/AnalysisEventProcessor.java
|
package ai.chat2db.excel.read.processor;
import ai.chat2db.excel.context.AnalysisContext;
/**
*
* Event processor
*
* @author jipengfei
*/
public interface AnalysisEventProcessor {
/**
* Read extra information
*
* @param analysisContext
*/
void extra(AnalysisContext analysisContext);
/**
* End row
*
* @param analysisContext
*/
void endRow(AnalysisContext analysisContext);
/**
* Notify after all analysed
*
* @param analysisContext
* Analysis context
*/
void endSheet(AnalysisContext analysisContext);
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/read/processor/DefaultAnalysisEventProcessor.java
|
package ai.chat2db.excel.read.processor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import ai.chat2db.excel.enums.CellDataTypeEnum;
import ai.chat2db.excel.enums.HeadKindEnum;
import ai.chat2db.excel.enums.RowTypeEnum;
import ai.chat2db.excel.read.metadata.holder.ReadRowHolder;
import ai.chat2db.excel.read.metadata.holder.ReadSheetHolder;
import ai.chat2db.excel.read.metadata.property.ExcelReadHeadProperty;
import ai.chat2db.excel.util.BooleanUtils;
import ai.chat2db.excel.util.ConverterUtils;
import ai.chat2db.excel.util.StringUtils;
import ai.chat2db.excel.context.AnalysisContext;
import ai.chat2db.excel.exception.ExcelAnalysisException;
import ai.chat2db.excel.exception.ExcelAnalysisStopException;
import ai.chat2db.excel.metadata.Head;
import ai.chat2db.excel.metadata.data.ReadCellData;
import ai.chat2db.excel.read.listener.ReadListener;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Analysis event
*
* @author jipengfei
*/
public class DefaultAnalysisEventProcessor implements AnalysisEventProcessor {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultAnalysisEventProcessor.class);
@Override
public void extra(AnalysisContext analysisContext) {
dealExtra(analysisContext);
}
@Override
public void endRow(AnalysisContext analysisContext) {
if (RowTypeEnum.EMPTY.equals(analysisContext.readRowHolder().getRowType())) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Empty row!");
}
if (analysisContext.readWorkbookHolder().getIgnoreEmptyRow()) {
return;
}
}
dealData(analysisContext);
}
@Override
public void endSheet(AnalysisContext analysisContext) {
ReadSheetHolder readSheetHolder = analysisContext.readSheetHolder();
if (BooleanUtils.isTrue(readSheetHolder.getEnded())) {
return;
}
readSheetHolder.setEnded(Boolean.TRUE);
for (ReadListener readListener : analysisContext.currentReadHolder().readListenerList()) {
readListener.doAfterAllAnalysed(analysisContext);
}
}
private void dealExtra(AnalysisContext analysisContext) {
for (ReadListener readListener : analysisContext.currentReadHolder().readListenerList()) {
try {
readListener.extra(analysisContext.readSheetHolder().getCellExtra(), analysisContext);
} catch (Exception e) {
onException(analysisContext, e);
break;
}
if (!readListener.hasNext(analysisContext)) {
throw new ExcelAnalysisStopException();
}
}
}
private void onException(AnalysisContext analysisContext, Exception e) {
for (ReadListener readListenerException : analysisContext.currentReadHolder().readListenerList()) {
try {
readListenerException.onException(e, analysisContext);
} catch (RuntimeException re) {
throw re;
} catch (Exception e1) {
throw new ExcelAnalysisException(e1.getMessage(), e1);
}
}
}
private void dealData(AnalysisContext analysisContext) {
ReadRowHolder readRowHolder = analysisContext.readRowHolder();
Map<Integer, ReadCellData<?>> cellDataMap = (Map)readRowHolder.getCellMap();
readRowHolder.setCurrentRowAnalysisResult(cellDataMap);
int rowIndex = readRowHolder.getRowIndex();
int currentHeadRowNumber = analysisContext.readSheetHolder().getHeadRowNumber();
boolean isData = rowIndex >= currentHeadRowNumber;
// Last head column
if (!isData && currentHeadRowNumber == rowIndex + 1) {
buildHead(analysisContext, cellDataMap);
}
// Now is data
for (ReadListener readListener : analysisContext.currentReadHolder().readListenerList()) {
try {
if (isData) {
readListener.invoke(readRowHolder.getCurrentRowAnalysisResult(), analysisContext);
} else {
readListener.invokeHead(cellDataMap, analysisContext);
}
} catch (Exception e) {
onException(analysisContext, e);
break;
}
if (!readListener.hasNext(analysisContext)) {
throw new ExcelAnalysisStopException();
}
}
}
private void buildHead(AnalysisContext analysisContext, Map<Integer, ReadCellData<?>> cellDataMap) {
// Rule out empty head, and then take the largest column
if (MapUtils.isNotEmpty(cellDataMap)) {
cellDataMap.entrySet()
.stream()
.filter(entry -> CellDataTypeEnum.EMPTY != entry.getValue().getType())
.forEach(entry -> analysisContext.readSheetHolder().setMaxNotEmptyDataHeadSize(entry.getKey()));
}
if (!HeadKindEnum.CLASS.equals(analysisContext.currentReadHolder().excelReadHeadProperty().getHeadKind())) {
return;
}
Map<Integer, String> dataMap = ConverterUtils.convertToStringMap(cellDataMap, analysisContext);
ExcelReadHeadProperty excelHeadPropertyData = analysisContext.readSheetHolder().excelReadHeadProperty();
Map<Integer, Head> headMapData = excelHeadPropertyData.getHeadMap();
Map<Integer, Head> tmpHeadMap = new HashMap<Integer, Head>(headMapData.size() * 4 / 3 + 1);
for (Map.Entry<Integer, Head> entry : headMapData.entrySet()) {
Head headData = entry.getValue();
if (headData.getForceIndex() || !headData.getForceName()) {
tmpHeadMap.put(entry.getKey(), headData);
continue;
}
List<String> headNameList = headData.getHeadNameList();
String headName = headNameList.get(headNameList.size() - 1);
for (Map.Entry<Integer, String> stringEntry : dataMap.entrySet()) {
if (stringEntry == null) {
continue;
}
String headString = stringEntry.getValue();
Integer stringKey = stringEntry.getKey();
if (StringUtils.isEmpty(headString)) {
continue;
}
if (analysisContext.currentReadHolder().globalConfiguration().getAutoTrim()) {
headString = headString.trim();
}
if (headName.equals(headString)) {
headData.setColumnIndex(stringKey);
tmpHeadMap.put(stringKey, headData);
break;
}
}
}
excelHeadPropertyData.setHeadMap(tmpHeadMap);
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/support/ExcelTypeEnum.java
|
package ai.chat2db.excel.support;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import ai.chat2db.excel.exception.ExcelAnalysisException;
import ai.chat2db.excel.exception.ExcelCommonException;
import ai.chat2db.excel.read.metadata.ReadWorkbook;
import ai.chat2db.excel.util.StringUtils;
import lombok.Getter;
import org.apache.poi.util.IOUtils;
/**
* @author jipengfei
*/
@Getter
public enum ExcelTypeEnum {
/**
* csv
*/
CSV(".csv", new byte[] {-27, -89, -109, -27}),
/**
* xls
*/
XLS(".xls", new byte[] {-48, -49, 17, -32, -95, -79, 26, -31}),
/**
* xlsx
*/
XLSX(".xlsx", new byte[] {80, 75, 3, 4});
final String value;
final byte[] magic;
ExcelTypeEnum(String value, byte[] magic) {
this.value = value;
this.magic = magic;
}
final static int MAX_PATTERN_LENGTH = 8;
public static ExcelTypeEnum valueOf(ReadWorkbook readWorkbook) {
ExcelTypeEnum excelType = readWorkbook.getExcelType();
if (excelType != null) {
return excelType;
}
File file = readWorkbook.getFile();
InputStream inputStream = readWorkbook.getInputStream();
if (file == null && inputStream == null) {
throw new ExcelAnalysisException("File and inputStream must be a non-null.");
}
try {
if (file != null) {
if (!file.exists()) {
throw new ExcelAnalysisException("File " + file.getAbsolutePath() + " not exists.");
}
// If there is a password, use the FileMagic first
if (!StringUtils.isEmpty(readWorkbook.getPassword())) {
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file))) {
return recognitionExcelType(bufferedInputStream);
}
}
// Use the name to determine the type
String fileName = file.getName();
if (fileName.endsWith(XLSX.getValue())) {
return XLSX;
} else if (fileName.endsWith(XLS.getValue())) {
return XLS;
} else if (fileName.endsWith(CSV.getValue())) {
return CSV;
}
if (StringUtils.isEmpty(readWorkbook.getPassword())) {
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file))) {
return recognitionExcelType(bufferedInputStream);
}
}
}
if (!inputStream.markSupported()) {
inputStream = new BufferedInputStream(inputStream);
readWorkbook.setInputStream(inputStream);
}
return recognitionExcelType(inputStream);
} catch (ExcelCommonException e) {
throw e;
} catch (Exception e) {
throw new ExcelCommonException(
"Convert excel format exception.You can try specifying the 'excelType' yourself", e);
}
}
private static ExcelTypeEnum recognitionExcelType(InputStream inputStream) throws Exception {
// Grab the first bytes of this stream
byte[] data = IOUtils.peekFirstNBytes(inputStream, MAX_PATTERN_LENGTH);
if (findMagic(XLSX.magic, data)) {
return XLSX;
} else if (findMagic(XLS.magic, data)) {
return XLS;
}
// csv has no fixed prefix, if the format is not specified, it defaults to csv
return CSV;
}
private static boolean findMagic(byte[] expected, byte[] actual) {
int i = 0;
for (byte expectedByte : expected) {
if (actual[i++] != expectedByte && expectedByte != '?') {
return false;
}
}
return true;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/BeanMapUtils.java
|
package ai.chat2db.excel.util;
import ai.chat2db.excel.support.cglib.beans.BeanMap;
import ai.chat2db.excel.support.cglib.core.DefaultNamingPolicy;
/**
* bean utils
*
* @author Jiaju Zhuang
*/
public class BeanMapUtils {
/**
* Helper method to create a new <code>BeanMap</code>. For finer
* control over the generated instance, use a new instance of
* <code>BeanMap.Generator</code> instead of this static method.
*
* Custom naming policy to prevent null pointer exceptions.
* see: https://github.com/CodePhiliaX/easyexcel-plus/issues/2064
*
* @param bean the JavaBean underlying the map
* @return a new <code>BeanMap</code> instance
*/
public static BeanMap create(Object bean) {
BeanMap.Generator gen = new BeanMap.Generator();
gen.setBean(bean);
gen.setContextClass(bean.getClass());
gen.setNamingPolicy(EasyExcelNamingPolicy.INSTANCE);
return gen.create();
}
public static class EasyExcelNamingPolicy extends DefaultNamingPolicy {
public static final EasyExcelNamingPolicy INSTANCE = new EasyExcelNamingPolicy();
@Override
protected String getTag() {
return "ByEasyExcelCGLIB";
}
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/BooleanUtils.java
|
package ai.chat2db.excel.util;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Apache Software Foundation (ASF)
*/
public class BooleanUtils {
private static final String TRUE_NUMBER = "1";
private BooleanUtils() {}
/**
* String to boolean
*
* @param str
* @return
*/
public static Boolean valueOf(String str) {
if (TRUE_NUMBER.equals(str)) {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
}
// boolean Boolean methods
//-----------------------------------------------------------------------
/**
* <p>Checks if a {@code Boolean} value is {@code true},
* handling {@code null} by returning {@code false}.</p>
*
* <pre>
* BooleanUtils.isTrue(Boolean.TRUE) = true
* BooleanUtils.isTrue(Boolean.FALSE) = false
* BooleanUtils.isTrue(null) = false
* </pre>
*
* @param bool the boolean to check, null returns {@code false}
* @return {@code true} only if the input is non-null and true
* @since 2.1
*/
public static boolean isTrue(final Boolean bool) {
return Boolean.TRUE.equals(bool);
}
/**
* <p>Checks if a {@code Boolean} value is <i>not</i> {@code true},
* handling {@code null} by returning {@code true}.</p>
*
* <pre>
* BooleanUtils.isNotTrue(Boolean.TRUE) = false
* BooleanUtils.isNotTrue(Boolean.FALSE) = true
* BooleanUtils.isNotTrue(null) = true
* </pre>
*
* @param bool the boolean to check, null returns {@code true}
* @return {@code true} if the input is null or false
* @since 2.3
*/
public static boolean isNotTrue(final Boolean bool) {
return !isTrue(bool);
}
/**
* <p>Checks if a {@code Boolean} value is {@code false},
* handling {@code null} by returning {@code false}.</p>
*
* <pre>
* BooleanUtils.isFalse(Boolean.TRUE) = false
* BooleanUtils.isFalse(Boolean.FALSE) = true
* BooleanUtils.isFalse(null) = false
* </pre>
*
* @param bool the boolean to check, null returns {@code false}
* @return {@code true} only if the input is non-null and false
* @since 2.1
*/
public static boolean isFalse(final Boolean bool) {
return Boolean.FALSE.equals(bool);
}
/**
* <p>Checks if a {@code Boolean} value is <i>not</i> {@code false},
* handling {@code null} by returning {@code true}.</p>
*
* <pre>
* BooleanUtils.isNotFalse(Boolean.TRUE) = true
* BooleanUtils.isNotFalse(Boolean.FALSE) = false
* BooleanUtils.isNotFalse(null) = true
* </pre>
*
* @param bool the boolean to check, null returns {@code true}
* @return {@code true} if the input is null or true
* @since 2.3
*/
public static boolean isNotFalse(final Boolean bool) {
return !isFalse(bool);
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/ClassUtils.java
|
package ai.chat2db.excel.util;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import ai.chat2db.excel.annotation.ExcelIgnore;
import ai.chat2db.excel.annotation.ExcelIgnoreUnannotated;
import ai.chat2db.excel.annotation.ExcelProperty;
import ai.chat2db.excel.annotation.format.DateTimeFormat;
import ai.chat2db.excel.annotation.format.NumberFormat;
import ai.chat2db.excel.annotation.write.style.ContentFontStyle;
import ai.chat2db.excel.annotation.write.style.ContentStyle;
import ai.chat2db.excel.converters.AutoConverter;
import ai.chat2db.excel.converters.Converter;
import ai.chat2db.excel.exception.ExcelCommonException;
import ai.chat2db.excel.metadata.ConfigurationHolder;
import ai.chat2db.excel.metadata.FieldCache;
import ai.chat2db.excel.metadata.FieldWrapper;
import ai.chat2db.excel.metadata.property.DateTimeFormatProperty;
import ai.chat2db.excel.metadata.property.ExcelContentProperty;
import ai.chat2db.excel.metadata.property.FontProperty;
import ai.chat2db.excel.metadata.property.NumberFormatProperty;
import ai.chat2db.excel.metadata.property.StyleProperty;
import ai.chat2db.excel.support.cglib.beans.BeanMap;
import ai.chat2db.excel.write.metadata.holder.WriteHolder;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections4.CollectionUtils;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Apache Software Foundation (ASF)
*/
public class ClassUtils {
/**
* memory cache
*/
public static final Map<FieldCacheKey, FieldCache> FIELD_CACHE = new ConcurrentHashMap<>();
/**
* thread local cache
*/
private static final ThreadLocal<Map<FieldCacheKey, FieldCache>> FIELD_THREAD_LOCAL = new ThreadLocal<>();
/**
* The cache configuration information for each of the class
*/
public static final ConcurrentHashMap<Class<?>, Map<String, ExcelContentProperty>> CLASS_CONTENT_CACHE
= new ConcurrentHashMap<>();
/**
* The cache configuration information for each of the class
*/
private static final ThreadLocal<Map<Class<?>, Map<String, ExcelContentProperty>>> CLASS_CONTENT_THREAD_LOCAL
= new ThreadLocal<>();
/**
* The cache configuration information for each of the class
*/
public static final ConcurrentHashMap<ContentPropertyKey, ExcelContentProperty> CONTENT_CACHE
= new ConcurrentHashMap<>();
/**
* The cache configuration information for each of the class
*/
private static final ThreadLocal<Map<ContentPropertyKey, ExcelContentProperty>> CONTENT_THREAD_LOCAL
= new ThreadLocal<>();
/**
* Calculate the configuration information for the class
*
* @param dataMap
* @param headClazz
* @param fieldName
* @return
*/
public static ExcelContentProperty declaredExcelContentProperty(Map<?, ?> dataMap, Class<?> headClazz,
String fieldName,
ConfigurationHolder configurationHolder) {
Class<?> clazz = null;
if (dataMap instanceof BeanMap) {
Object bean = ((BeanMap)dataMap).getBean();
if (bean != null) {
clazz = bean.getClass();
}
}
return getExcelContentProperty(clazz, headClazz, fieldName, configurationHolder);
}
private static ExcelContentProperty getExcelContentProperty(Class<?> clazz, Class<?> headClass, String fieldName,
ConfigurationHolder configurationHolder) {
switch (configurationHolder.globalConfiguration().getFiledCacheLocation()) {
case THREAD_LOCAL:
Map<ContentPropertyKey, ExcelContentProperty> contentCacheMap = CONTENT_THREAD_LOCAL.get();
if (contentCacheMap == null) {
contentCacheMap = MapUtils.newHashMap();
CONTENT_THREAD_LOCAL.set(contentCacheMap);
}
return contentCacheMap.computeIfAbsent(buildKey(clazz, headClass, fieldName), key -> {
return doGetExcelContentProperty(clazz, headClass, fieldName, configurationHolder);
});
case MEMORY:
return CONTENT_CACHE.computeIfAbsent(buildKey(clazz, headClass, fieldName), key -> {
return doGetExcelContentProperty(clazz, headClass, fieldName, configurationHolder);
});
case NONE:
return doGetExcelContentProperty(clazz, headClass, fieldName, configurationHolder);
default:
throw new UnsupportedOperationException("unsupported enum");
}
}
private static ExcelContentProperty doGetExcelContentProperty(Class<?> clazz, Class<?> headClass,
String fieldName,
ConfigurationHolder configurationHolder) {
ExcelContentProperty excelContentProperty = Optional.ofNullable(
declaredFieldContentMap(clazz, configurationHolder))
.map(map -> map.get(fieldName))
.orElse(null);
ExcelContentProperty headExcelContentProperty = Optional.ofNullable(
declaredFieldContentMap(headClass, configurationHolder))
.map(map -> map.get(fieldName))
.orElse(null);
ExcelContentProperty combineExcelContentProperty = new ExcelContentProperty();
combineExcelContentProperty(combineExcelContentProperty, headExcelContentProperty);
if (clazz != headClass) {
combineExcelContentProperty(combineExcelContentProperty, excelContentProperty);
}
return combineExcelContentProperty;
}
public static void combineExcelContentProperty(ExcelContentProperty combineExcelContentProperty,
ExcelContentProperty excelContentProperty) {
if (excelContentProperty == null) {
return;
}
if (excelContentProperty.getField() != null) {
combineExcelContentProperty.setField(excelContentProperty.getField());
}
if (excelContentProperty.getConverter() != null) {
combineExcelContentProperty.setConverter(excelContentProperty.getConverter());
}
if (excelContentProperty.getDateTimeFormatProperty() != null) {
combineExcelContentProperty.setDateTimeFormatProperty(excelContentProperty.getDateTimeFormatProperty());
}
if (excelContentProperty.getNumberFormatProperty() != null) {
combineExcelContentProperty.setNumberFormatProperty(excelContentProperty.getNumberFormatProperty());
}
if (excelContentProperty.getContentStyleProperty() != null) {
combineExcelContentProperty.setContentStyleProperty(excelContentProperty.getContentStyleProperty());
}
if (excelContentProperty.getContentFontProperty() != null) {
combineExcelContentProperty.setContentFontProperty(excelContentProperty.getContentFontProperty());
}
}
private static ContentPropertyKey buildKey(Class<?> clazz, Class<?> headClass, String fieldName) {
return new ContentPropertyKey(clazz, headClass, fieldName);
}
private static Map<String, ExcelContentProperty> declaredFieldContentMap(Class<?> clazz,
ConfigurationHolder configurationHolder) {
if (clazz == null) {
return null;
}
switch (configurationHolder.globalConfiguration().getFiledCacheLocation()) {
case THREAD_LOCAL:
Map<Class<?>, Map<String, ExcelContentProperty>> classContentCacheMap
= CLASS_CONTENT_THREAD_LOCAL.get();
if (classContentCacheMap == null) {
classContentCacheMap = MapUtils.newHashMap();
CLASS_CONTENT_THREAD_LOCAL.set(classContentCacheMap);
}
return classContentCacheMap.computeIfAbsent(clazz, key -> {
return doDeclaredFieldContentMap(clazz);
});
case MEMORY:
return CLASS_CONTENT_CACHE.computeIfAbsent(clazz, key -> {
return doDeclaredFieldContentMap(clazz);
});
case NONE:
return doDeclaredFieldContentMap(clazz);
default:
throw new UnsupportedOperationException("unsupported enum");
}
}
private static Map<String, ExcelContentProperty> doDeclaredFieldContentMap(Class<?> clazz) {
if (clazz == null) {
return null;
}
List<Field> tempFieldList = new ArrayList<>();
Class<?> tempClass = clazz;
while (tempClass != null) {
Collections.addAll(tempFieldList, tempClass.getDeclaredFields());
// Get the parent class and give it to yourself
tempClass = tempClass.getSuperclass();
}
ContentStyle parentContentStyle = clazz.getAnnotation(ContentStyle.class);
ContentFontStyle parentContentFontStyle = clazz.getAnnotation(ContentFontStyle.class);
Map<String, ExcelContentProperty> fieldContentMap = MapUtils.newHashMapWithExpectedSize(
tempFieldList.size());
for (Field field : tempFieldList) {
ExcelContentProperty excelContentProperty = new ExcelContentProperty();
excelContentProperty.setField(field);
ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
if (excelProperty != null) {
Class<? extends Converter<?>> convertClazz = excelProperty.converter();
if (convertClazz != AutoConverter.class) {
try {
Converter<?> converter = convertClazz.getDeclaredConstructor().newInstance();
excelContentProperty.setConverter(converter);
} catch (Exception e) {
throw new ExcelCommonException(
"Can not instance custom converter:" + convertClazz.getName());
}
}
}
ContentStyle contentStyle = field.getAnnotation(ContentStyle.class);
if (contentStyle == null) {
contentStyle = parentContentStyle;
}
excelContentProperty.setContentStyleProperty(StyleProperty.build(contentStyle));
ContentFontStyle contentFontStyle = field.getAnnotation(ContentFontStyle.class);
if (contentFontStyle == null) {
contentFontStyle = parentContentFontStyle;
}
excelContentProperty.setContentFontProperty(FontProperty.build(contentFontStyle));
excelContentProperty.setDateTimeFormatProperty(
DateTimeFormatProperty.build(field.getAnnotation(DateTimeFormat.class)));
excelContentProperty.setNumberFormatProperty(
NumberFormatProperty.build(field.getAnnotation(NumberFormat.class)));
fieldContentMap.put(field.getName(), excelContentProperty);
}
return fieldContentMap;
}
/**
* Parsing field in the class
*
* @param clazz Need to parse the class
* @param configurationHolder configuration
*/
public static FieldCache declaredFields(Class<?> clazz, ConfigurationHolder configurationHolder) {
switch (configurationHolder.globalConfiguration().getFiledCacheLocation()) {
case THREAD_LOCAL:
Map<FieldCacheKey, FieldCache> fieldCacheMap = FIELD_THREAD_LOCAL.get();
if (fieldCacheMap == null) {
fieldCacheMap = MapUtils.newHashMap();
FIELD_THREAD_LOCAL.set(fieldCacheMap);
}
return fieldCacheMap.computeIfAbsent(new FieldCacheKey(clazz, configurationHolder), key -> {
return doDeclaredFields(clazz, configurationHolder);
});
case MEMORY:
return FIELD_CACHE.computeIfAbsent(new FieldCacheKey(clazz, configurationHolder), key -> {
return doDeclaredFields(clazz, configurationHolder);
});
case NONE:
return doDeclaredFields(clazz, configurationHolder);
default:
throw new UnsupportedOperationException("unsupported enum");
}
}
private static FieldCache doDeclaredFields(Class<?> clazz, ConfigurationHolder configurationHolder) {
List<Field> tempFieldList = new ArrayList<>();
Class<?> tempClass = clazz;
// When the parent class is null, it indicates that the parent class (Object class) has reached the top
// level.
while (tempClass != null) {
Collections.addAll(tempFieldList, tempClass.getDeclaredFields());
// Get the parent class and give it to yourself
tempClass = tempClass.getSuperclass();
}
// Screening of field
Map<Integer, List<FieldWrapper>> orderFieldMap = new TreeMap<>();
Map<Integer, FieldWrapper> indexFieldMap = new TreeMap<>();
Set<String> ignoreSet = new HashSet<>();
ExcelIgnoreUnannotated excelIgnoreUnannotated = clazz.getAnnotation(ExcelIgnoreUnannotated.class);
for (Field field : tempFieldList) {
declaredOneField(field, orderFieldMap, indexFieldMap, ignoreSet, excelIgnoreUnannotated);
}
Map<Integer, FieldWrapper> sortedFieldMap = buildSortedAllFieldMap(orderFieldMap, indexFieldMap);
FieldCache fieldCache = new FieldCache(sortedFieldMap, indexFieldMap);
if (!(configurationHolder instanceof WriteHolder)) {
return fieldCache;
}
WriteHolder writeHolder = (WriteHolder)configurationHolder;
boolean needIgnore = !CollectionUtils.isEmpty(writeHolder.excludeColumnFieldNames())
|| !CollectionUtils.isEmpty(writeHolder.excludeColumnIndexes())
|| !CollectionUtils.isEmpty(writeHolder.includeColumnFieldNames())
|| !CollectionUtils.isEmpty(writeHolder.includeColumnIndexes());
if (!needIgnore) {
return fieldCache;
}
// ignore filed
Map<Integer, FieldWrapper> tempSortedFieldMap = MapUtils.newHashMap();
int index = 0;
for (Map.Entry<Integer, FieldWrapper> entry : sortedFieldMap.entrySet()) {
Integer key = entry.getKey();
FieldWrapper field = entry.getValue();
// The current field needs to be ignored
if (writeHolder.ignore(field.getFieldName(), entry.getKey())) {
ignoreSet.add(field.getFieldName());
indexFieldMap.remove(index);
} else {
// Mandatory sorted fields
if (indexFieldMap.containsKey(key)) {
tempSortedFieldMap.put(key, field);
} else {
// Need to reorder automatically
// Check whether the current key is already in use
while (tempSortedFieldMap.containsKey(index)) {
index++;
}
tempSortedFieldMap.put(index++, field);
}
}
}
fieldCache.setSortedFieldMap(tempSortedFieldMap);
// resort field
resortField(writeHolder, fieldCache);
return fieldCache;
}
/**
* it only works when {@link WriteHolder#includeColumnFieldNames()} or
* {@link WriteHolder#includeColumnIndexes()} has value
* and {@link WriteHolder#orderByIncludeColumn()} is true
**/
private static void resortField(WriteHolder writeHolder, FieldCache fieldCache) {
if (!writeHolder.orderByIncludeColumn()) {
return;
}
Map<Integer, FieldWrapper> indexFieldMap = fieldCache.getIndexFieldMap();
Collection<String> includeColumnFieldNames = writeHolder.includeColumnFieldNames();
if (!CollectionUtils.isEmpty(includeColumnFieldNames)) {
// Field sorted map
Map<String, Integer> filedIndexMap = MapUtils.newHashMap();
int fieldIndex = 0;
for (String includeColumnFieldName : includeColumnFieldNames) {
filedIndexMap.put(includeColumnFieldName, fieldIndex++);
}
// rebuild sortedFieldMap
Map<Integer, FieldWrapper> tempSortedFieldMap = MapUtils.newHashMap();
fieldCache.getSortedFieldMap().forEach((index, field) -> {
Integer tempFieldIndex = filedIndexMap.get(field.getFieldName());
if (tempFieldIndex != null) {
tempSortedFieldMap.put(tempFieldIndex, field);
// The user has redefined the ordering and the ordering of annotations needs to be invalidated
if (!tempFieldIndex.equals(index)) {
indexFieldMap.remove(index);
}
}
});
fieldCache.setSortedFieldMap(tempSortedFieldMap);
return;
}
Collection<Integer> includeColumnIndexes = writeHolder.includeColumnIndexes();
if (!CollectionUtils.isEmpty(includeColumnIndexes)) {
// Index sorted map
Map<Integer, Integer> filedIndexMap = MapUtils.newHashMap();
int fieldIndex = 0;
for (Integer includeColumnIndex : includeColumnIndexes) {
filedIndexMap.put(includeColumnIndex, fieldIndex++);
}
// rebuild sortedFieldMap
Map<Integer, FieldWrapper> tempSortedFieldMap = MapUtils.newHashMap();
fieldCache.getSortedFieldMap().forEach((index, field) -> {
Integer tempFieldIndex = filedIndexMap.get(index);
// The user has redefined the ordering and the ordering of annotations needs to be invalidated
if (tempFieldIndex != null) {
tempSortedFieldMap.put(tempFieldIndex, field);
}
});
fieldCache.setSortedFieldMap(tempSortedFieldMap);
}
}
private static Map<Integer, FieldWrapper> buildSortedAllFieldMap(Map<Integer, List<FieldWrapper>> orderFieldMap,
Map<Integer, FieldWrapper> indexFieldMap) {
Map<Integer, FieldWrapper> sortedAllFieldMap = new HashMap<>(
(orderFieldMap.size() + indexFieldMap.size()) * 4 / 3 + 1);
Map<Integer, FieldWrapper> tempIndexFieldMap = new HashMap<>(indexFieldMap);
int index = 0;
for (List<FieldWrapper> fieldList : orderFieldMap.values()) {
for (FieldWrapper field : fieldList) {
while (tempIndexFieldMap.containsKey(index)) {
sortedAllFieldMap.put(index, tempIndexFieldMap.get(index));
tempIndexFieldMap.remove(index);
index++;
}
sortedAllFieldMap.put(index, field);
index++;
}
}
sortedAllFieldMap.putAll(tempIndexFieldMap);
return sortedAllFieldMap;
}
private static void declaredOneField(Field field, Map<Integer, List<FieldWrapper>> orderFieldMap,
Map<Integer, FieldWrapper> indexFieldMap, Set<String> ignoreSet,
ExcelIgnoreUnannotated excelIgnoreUnannotated) {
String fieldName = FieldUtils.resolveCglibFieldName(field);
FieldWrapper fieldWrapper = new FieldWrapper();
fieldWrapper.setField(field);
fieldWrapper.setFieldName(fieldName);
ExcelIgnore excelIgnore = field.getAnnotation(ExcelIgnore.class);
if (excelIgnore != null) {
ignoreSet.add(fieldName);
return;
}
ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class);
boolean noExcelProperty = excelProperty == null && excelIgnoreUnannotated != null;
if (noExcelProperty) {
ignoreSet.add(fieldName);
return;
}
boolean isStaticFinalOrTransient =
(Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers()))
|| Modifier.isTransient(field.getModifiers());
if (excelProperty == null && isStaticFinalOrTransient) {
ignoreSet.add(fieldName);
return;
}
// set heads
if (excelProperty != null) {
fieldWrapper.setHeads(excelProperty.value());
}
if (excelProperty != null && excelProperty.index() >= 0) {
if (indexFieldMap.containsKey(excelProperty.index())) {
throw new ExcelCommonException(
"The index of '" + indexFieldMap.get(excelProperty.index()).getFieldName()
+ "' and '" + field.getName() + "' must be inconsistent");
}
indexFieldMap.put(excelProperty.index(), fieldWrapper);
return;
}
int order = Integer.MAX_VALUE;
if (excelProperty != null) {
order = excelProperty.order();
}
List<FieldWrapper> orderFieldList = orderFieldMap.computeIfAbsent(order, key -> ListUtils.newArrayList());
orderFieldList.add(fieldWrapper);
}
/**
* <p>Gets a {@code List} of all interfaces implemented by the given
* class and its superclasses.</p>
*
* <p>The order is determined by looking through each interface in turn as
* declared in the source file and following its hierarchy up. Then each
* superclass is considered in the same way. Later duplicates are ignored,
* so the order is maintained.</p>
*
* @param cls the class to look up, may be {@code null}
* @return the {@code List} of interfaces in order,
* {@code null} if null input
*/
public static List<Class<?>> getAllInterfaces(final Class<?> cls) {
if (cls == null) {
return null;
}
final LinkedHashSet<Class<?>> interfacesFound = new LinkedHashSet<>();
getAllInterfaces(cls, interfacesFound);
return new ArrayList<>(interfacesFound);
}
/**
* Gets the interfaces for the specified class.
*
* @param cls the class to look up, may be {@code null}
* @param interfacesFound the {@code Set} of interfaces for the class
*/
private static void getAllInterfaces(Class<?> cls, final HashSet<Class<?>> interfacesFound) {
while (cls != null) {
final Class<?>[] interfaces = cls.getInterfaces();
for (final Class<?> i : interfaces) {
if (interfacesFound.add(i)) {
getAllInterfaces(i, interfacesFound);
}
}
cls = cls.getSuperclass();
}
}
@Getter
@Setter
@EqualsAndHashCode
@AllArgsConstructor
public static class ContentPropertyKey {
private Class<?> clazz;
private Class<?> headClass;
private String fieldName;
}
@Data
public static class FieldCacheKey {
private Class<?> clazz;
private Collection<String> excludeColumnFieldNames;
private Collection<Integer> excludeColumnIndexes;
private Collection<String> includeColumnFieldNames;
private Collection<Integer> includeColumnIndexes;
FieldCacheKey(Class<?> clazz, ConfigurationHolder configurationHolder) {
this.clazz = clazz;
if (configurationHolder instanceof WriteHolder) {
WriteHolder writeHolder = (WriteHolder)configurationHolder;
this.excludeColumnFieldNames = writeHolder.excludeColumnFieldNames();
this.excludeColumnIndexes = writeHolder.excludeColumnIndexes();
this.includeColumnFieldNames = writeHolder.includeColumnFieldNames();
this.includeColumnIndexes = writeHolder.includeColumnIndexes();
}
}
}
public static void removeThreadLocalCache() {
FIELD_THREAD_LOCAL.remove();
CLASS_CONTENT_THREAD_LOCAL.remove();
CONTENT_THREAD_LOCAL.remove();
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/ConverterUtils.java
|
package ai.chat2db.excel.util;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
import ai.chat2db.excel.enums.CellDataTypeEnum;
import ai.chat2db.excel.context.AnalysisContext;
import ai.chat2db.excel.converters.Converter;
import ai.chat2db.excel.converters.ConverterKeyBuild;
import ai.chat2db.excel.converters.ConverterKeyBuild.ConverterKey;
import ai.chat2db.excel.converters.NullableObjectConverter;
import ai.chat2db.excel.converters.ReadConverterContext;
import ai.chat2db.excel.exception.ExcelDataConvertException;
import ai.chat2db.excel.metadata.data.CellData;
import ai.chat2db.excel.metadata.data.ReadCellData;
import ai.chat2db.excel.metadata.property.ExcelContentProperty;
import ai.chat2db.excel.read.metadata.holder.ReadSheetHolder;
/**
* Converting objects
*
* @author Jiaju Zhuang
**/
public class ConverterUtils {
public static Class<?> defaultClassGeneric = String.class;
private ConverterUtils() {}
/**
* Convert it into a String map
*
* @param cellDataMap
* @param context
* @return
*/
public static Map<Integer, String> convertToStringMap(Map<Integer, ReadCellData<?>> cellDataMap,
AnalysisContext context) {
Map<Integer, String> stringMap = MapUtils.newHashMapWithExpectedSize(cellDataMap.size());
ReadSheetHolder readSheetHolder = context.readSheetHolder();
int index = 0;
for (Map.Entry<Integer, ReadCellData<?>> entry : cellDataMap.entrySet()) {
Integer key = entry.getKey();
ReadCellData<?> cellData = entry.getValue();
while (index < key) {
stringMap.put(index, null);
index++;
}
index++;
if (cellData.getType() == CellDataTypeEnum.EMPTY) {
stringMap.put(key, null);
continue;
}
Converter<?> converter =
readSheetHolder.converterMap().get(ConverterKeyBuild.buildKey(String.class, cellData.getType()));
if (converter == null) {
throw new ExcelDataConvertException(context.readRowHolder().getRowIndex(), key, cellData, null,
"Converter not found, convert " + cellData.getType() + " to String");
}
try {
stringMap.put(key,
(String)(converter.convertToJavaData(new ReadConverterContext<>(cellData, null, context))));
} catch (Exception e) {
throw new ExcelDataConvertException(context.readRowHolder().getRowIndex(), key, cellData, null,
"Convert data " + cellData + " to String error ", e);
}
}
return stringMap;
}
/**
* Convert it into a Java object
*
* @param cellData
* @param field
* @param contentProperty
* @param converterMap
* @param context
* @param rowIndex
* @param columnIndex
* @return
*/
public static Object convertToJavaObject(ReadCellData<?> cellData, Field field,
ExcelContentProperty contentProperty, Map<ConverterKey, Converter<?>> converterMap, AnalysisContext context,
Integer rowIndex, Integer columnIndex) {
return convertToJavaObject(cellData, field, null, null, contentProperty, converterMap, context, rowIndex,
columnIndex);
}
/**
* Convert it into a Java object
*
* @param cellData
* @param field
* @param clazz
* @param contentProperty
* @param converterMap
* @param context
* @param rowIndex
* @param columnIndex
* @return
*/
public static Object convertToJavaObject(ReadCellData<?> cellData, Field field, Class<?> clazz,
Class<?> classGeneric, ExcelContentProperty contentProperty, Map<ConverterKey, Converter<?>> converterMap,
AnalysisContext context, Integer rowIndex, Integer columnIndex) {
if (clazz == null) {
if (field == null) {
clazz = String.class;
} else {
clazz = field.getType();
}
}
if (clazz == CellData.class || clazz == ReadCellData.class) {
ReadCellData<Object> cellDataReturn = cellData.clone();
cellDataReturn.setData(
doConvertToJavaObject(cellData, getClassGeneric(field, classGeneric), contentProperty,
converterMap, context, rowIndex, columnIndex));
return cellDataReturn;
}
return doConvertToJavaObject(cellData, clazz, contentProperty, converterMap, context, rowIndex,
columnIndex);
}
private static Class<?> getClassGeneric(Field field, Class<?> classGeneric) {
if (classGeneric != null) {
return classGeneric;
}
if (field == null) {
return defaultClassGeneric;
}
Type type = field.getGenericType();
if (!(type instanceof ParameterizedType)) {
return defaultClassGeneric;
}
ParameterizedType parameterizedType = (ParameterizedType)type;
Type[] types = parameterizedType.getActualTypeArguments();
if (types == null || types.length == 0) {
return defaultClassGeneric;
}
Type actualType = types[0];
if (!(actualType instanceof Class<?>)) {
return defaultClassGeneric;
}
return (Class<?>)actualType;
}
/**
* @param cellData
* @param clazz
* @param contentProperty
* @param converterMap
* @param context
* @param rowIndex
* @param columnIndex
* @return
*/
private static Object doConvertToJavaObject(ReadCellData<?> cellData, Class<?> clazz,
ExcelContentProperty contentProperty, Map<ConverterKey, Converter<?>> converterMap, AnalysisContext context,
Integer rowIndex, Integer columnIndex) {
Converter<?> converter = null;
if (contentProperty != null) {
converter = contentProperty.getConverter();
}
boolean canNotConverterEmpty = cellData.getType() == CellDataTypeEnum.EMPTY
&& !(converter instanceof NullableObjectConverter);
if (canNotConverterEmpty) {
return null;
}
if (converter == null) {
converter = converterMap.get(ConverterKeyBuild.buildKey(clazz, cellData.getType()));
}
if (converter == null) {
throw new ExcelDataConvertException(rowIndex, columnIndex, cellData, contentProperty,
"Converter not found, convert " + cellData.getType() + " to " + clazz.getName());
}
try {
return converter.convertToJavaData(new ReadConverterContext<>(cellData, contentProperty, context));
} catch (Exception e) {
throw new ExcelDataConvertException(rowIndex, columnIndex, cellData, contentProperty,
"Convert data " + cellData + " to " + clazz + " error ", e);
}
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/DateUtils.java
|
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package ai.chat2db.excel.util;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Pattern;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.util.LocaleUtil;
/**
* Date utils
*
* @author Jiaju Zhuang
**/
public class DateUtils {
/**
* Is a cache of dates
*/
private static final ThreadLocal<Map<Short, Boolean>> DATE_THREAD_LOCAL =
new ThreadLocal<>();
/**
* Is a cache of dates
*/
private static final ThreadLocal<Map<String, SimpleDateFormat>> DATE_FORMAT_THREAD_LOCAL =
new ThreadLocal<>();
/**
* The following patterns are used in {@link #isADateFormat(Short, String)}
*/
private static final Pattern date_ptrn1 = Pattern.compile("^\\[\\$\\-.*?\\]");
private static final Pattern date_ptrn2 = Pattern.compile("^\\[[a-zA-Z]+\\]");
private static final Pattern date_ptrn3a = Pattern.compile("[yYmMdDhHsS]");
// add "\u5e74 \u6708 \u65e5" for Chinese/Japanese date format:2017 \u5e74 2 \u6708 7 \u65e5
private static final Pattern date_ptrn3b =
Pattern.compile("^[\\[\\]yYmMdDhHsS\\-T/\u5e74\u6708\u65e5,. :\"\\\\]+0*[ampAMP/]*$");
// elapsed time patterns: [h],[m] and [s]
private static final Pattern date_ptrn4 = Pattern.compile("^\\[([hH]+|[mM]+|[sS]+)\\]");
// for format which start with "[DBNum1]" or "[DBNum2]" or "[DBNum3]" could be a Chinese date
private static final Pattern date_ptrn5 = Pattern.compile("^\\[DBNum(1|2|3)\\]");
// for format which start with "年" or "月" or "日" or "时" or "分" or "秒" could be a Chinese date
private static final Pattern date_ptrn6 = Pattern.compile("(年|月|日|时|分|秒)+");
public static final String DATE_FORMAT_10 = "yyyy-MM-dd";
public static final String DATE_FORMAT_14 = "yyyyMMddHHmmss";
public static final String DATE_FORMAT_16 = "yyyy-MM-dd HH:mm";
public static final String DATE_FORMAT_16_FORWARD_SLASH = "yyyy/MM/dd HH:mm";
public static final String DATE_FORMAT_17 = "yyyyMMdd HH:mm:ss";
public static final String DATE_FORMAT_19 = "yyyy-MM-dd HH:mm:ss";
public static final String DATE_FORMAT_19_FORWARD_SLASH = "yyyy/MM/dd HH:mm:ss";
private static final String MINUS = "-";
public static String defaultDateFormat = DATE_FORMAT_19;
public static String defaultLocalDateFormat = DATE_FORMAT_10;
public static final int SECONDS_PER_MINUTE = 60;
public static final int MINUTES_PER_HOUR = 60;
public static final int HOURS_PER_DAY = 24;
public static final int SECONDS_PER_DAY = (HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE);
// used to specify that date is invalid
private static final int BAD_DATE = -1;
public static final long DAY_MILLISECONDS = SECONDS_PER_DAY * 1000L;
private DateUtils() {}
/**
* convert string to date
*
* @param dateString
* @param dateFormat
* @return
* @throws ParseException
*/
public static Date parseDate(String dateString, String dateFormat) throws ParseException {
if (StringUtils.isEmpty(dateFormat)) {
dateFormat = switchDateFormat(dateString);
}
return getCacheDateFormat(dateFormat).parse(dateString);
}
/**
* convert string to date
*
* @param dateString
* @param dateFormat
* @param local
* @return
*/
public static LocalDateTime parseLocalDateTime(String dateString, String dateFormat, Locale local) {
if (StringUtils.isEmpty(dateFormat)) {
dateFormat = switchDateFormat(dateString);
}
if (local == null) {
return LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern(dateFormat));
} else {
return LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern(dateFormat, local));
}
}
/**
* convert string to date
*
* @param dateString
* @param dateFormat
* @param local
* @return
*/
public static LocalDate parseLocalDate(String dateString, String dateFormat, Locale local) {
if (StringUtils.isEmpty(dateFormat)) {
dateFormat = switchDateFormat(dateString);
}
if (local == null) {
return LocalDate.parse(dateString, DateTimeFormatter.ofPattern(dateFormat));
} else {
return LocalDate.parse(dateString, DateTimeFormatter.ofPattern(dateFormat, local));
}
}
/**
* convert string to date
*
* @param dateString
* @return
* @throws ParseException
*/
public static Date parseDate(String dateString) throws ParseException {
return parseDate(dateString, switchDateFormat(dateString));
}
/**
* switch date format
*
* @param dateString
* @return
*/
public static String switchDateFormat(String dateString) {
int length = dateString.length();
switch (length) {
case 19:
if (dateString.contains(MINUS)) {
return DATE_FORMAT_19;
} else {
return DATE_FORMAT_19_FORWARD_SLASH;
}
case 16:
if (dateString.contains(MINUS)) {
return DATE_FORMAT_16;
} else {
return DATE_FORMAT_16_FORWARD_SLASH;
}
case 17:
return DATE_FORMAT_17;
case 14:
return DATE_FORMAT_14;
case 10:
return DATE_FORMAT_10;
default:
throw new IllegalArgumentException("can not find date format for:" + dateString);
}
}
/**
* Format date
* <p>
* yyyy-MM-dd HH:mm:ss
*
* @param date
* @return
*/
public static String format(Date date) {
return format(date, null);
}
/**
* Format date
*
* @param date
* @param dateFormat
* @return
*/
public static String format(Date date, String dateFormat) {
if (date == null) {
return null;
}
if (StringUtils.isEmpty(dateFormat)) {
dateFormat = defaultDateFormat;
}
return getCacheDateFormat(dateFormat).format(date);
}
/**
* Format date
*
* @param date
* @param dateFormat
* @return
*/
public static String format(LocalDateTime date, String dateFormat, Locale local) {
if (date == null) {
return null;
}
if (StringUtils.isEmpty(dateFormat)) {
dateFormat = defaultDateFormat;
}
if (local == null) {
return date.format(DateTimeFormatter.ofPattern(dateFormat));
} else {
return date.format(DateTimeFormatter.ofPattern(dateFormat, local));
}
}
/**
* Format date
*
* @param date
* @param dateFormat
* @return
*/
public static String format(LocalDate date, String dateFormat) {
return format(date, dateFormat, null);
}
/**
* Format date
*
* @param date
* @param dateFormat
* @return
*/
public static String format(LocalDate date, String dateFormat, Locale local) {
if (date == null) {
return null;
}
if (StringUtils.isEmpty(dateFormat)) {
dateFormat = defaultLocalDateFormat;
}
if (local == null) {
return date.format(DateTimeFormatter.ofPattern(dateFormat));
} else {
return date.format(DateTimeFormatter.ofPattern(dateFormat, local));
}
}
/**
* Format date
*
* @param date
* @param dateFormat
* @return
*/
public static String format(LocalDateTime date, String dateFormat) {
return format(date, dateFormat, null);
}
/**
* Format date
*
* @param date
* @param dateFormat
* @return
*/
public static String format(BigDecimal date, Boolean use1904windowing, String dateFormat) {
if (date == null) {
return null;
}
LocalDateTime localDateTime = DateUtil.getLocalDateTime(date.doubleValue(),
BooleanUtils.isTrue(use1904windowing), true);
return format(localDateTime, dateFormat);
}
private static DateFormat getCacheDateFormat(String dateFormat) {
Map<String, SimpleDateFormat> dateFormatMap = DATE_FORMAT_THREAD_LOCAL.get();
if (dateFormatMap == null) {
dateFormatMap = new HashMap<String, SimpleDateFormat>();
DATE_FORMAT_THREAD_LOCAL.set(dateFormatMap);
} else {
SimpleDateFormat dateFormatCached = dateFormatMap.get(dateFormat);
if (dateFormatCached != null) {
return dateFormatCached;
}
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
dateFormatMap.put(dateFormat, simpleDateFormat);
return simpleDateFormat;
}
/**
* Given an Excel date with either 1900 or 1904 date windowing,
* converts it to a java.util.Date.
*
* Excel Dates and Times are stored without any timezone
* information. If you know (through other means) that your file
* uses a different TimeZone to the system default, you can use
* this version of the getJavaDate() method to handle it.
*
* @param date The Excel date.
* @param use1904windowing true if date uses 1904 windowing,
* or false if using 1900 date windowing.
* @return Java representation of the date, or null if date is not a valid Excel date
*/
public static Date getJavaDate(double date, boolean use1904windowing) {
Calendar calendar = getJavaCalendar(date, use1904windowing, null, true);
return calendar == null ? null : calendar.getTime();
}
/**
* Get EXCEL date as Java Calendar with given time zone.
* @param date The Excel date.
* @param use1904windowing true if date uses 1904 windowing,
* or false if using 1900 date windowing.
* @param timeZone The TimeZone to evaluate the date in
* @param roundSeconds round to closest second
* @return Java representation of the date, or null if date is not a valid Excel date
*/
public static Calendar getJavaCalendar(double date, boolean use1904windowing, TimeZone timeZone, boolean roundSeconds) {
if (!isValidExcelDate(date)) {
return null;
}
int wholeDays = (int)Math.floor(date);
int millisecondsInDay = (int)((date - wholeDays) * DAY_MILLISECONDS + 0.5);
Calendar calendar;
if (timeZone != null) {
calendar = LocaleUtil.getLocaleCalendar(timeZone);
} else {
calendar = LocaleUtil.getLocaleCalendar(); // using default time-zone
}
setCalendar(calendar, wholeDays, millisecondsInDay, use1904windowing, roundSeconds);
return calendar;
}
public static void setCalendar(Calendar calendar, int wholeDays,
int millisecondsInDay, boolean use1904windowing, boolean roundSeconds) {
int startYear = 1900;
int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it isn't
if (use1904windowing) {
startYear = 1904;
dayAdjust = 1; // 1904 date windowing uses 1/2/1904 as the first day
}
else if (wholeDays < 61) {
// Date is prior to 3/1/1900, so adjust because Excel thinks 2/29/1900 exists
// If Excel date == 2/29/1900, will become 3/1/1900 in Java representation
dayAdjust = 0;
}
calendar.set(startYear, Calendar.JANUARY, wholeDays + dayAdjust, 0, 0, 0);
calendar.set(Calendar.MILLISECOND, millisecondsInDay);
if (calendar.get(Calendar.MILLISECOND) == 0) {
calendar.clear(Calendar.MILLISECOND);
}
if (roundSeconds) {
// This is different from poi where you need to change 500 to 499
calendar.add(Calendar.MILLISECOND, 499);
calendar.clear(Calendar.MILLISECOND);
}
}
/**
* Given a double, checks if it is a valid Excel date.
*
* @return true if valid
* @param value the double value
*/
public static boolean isValidExcelDate(double value)
{
return (value > -Double.MIN_VALUE);
}
/**
* Given an Excel date with either 1900 or 1904 date windowing,
* converts it to a java.time.LocalDateTime.
*
* Excel Dates and Times are stored without any timezone
* information. If you know (through other means) that your file
* uses a different TimeZone to the system default, you can use
* this version of the getJavaDate() method to handle it.
*
* @param date The Excel date.
* @param use1904windowing true if date uses 1904 windowing,
* or false if using 1900 date windowing.
* @return Java representation of the date, or null if date is not a valid Excel date
*/
public static LocalDateTime getLocalDateTime(double date, boolean use1904windowing) {
return DateUtil.getLocalDateTime(date, use1904windowing, true);
}
/**
* Given an Excel date with either 1900 or 1904 date windowing,
* converts it to a java.time.LocalDate.
*
* Excel Dates and Times are stored without any timezone
* information. If you know (through other means) that your file
* uses a different TimeZone to the system default, you can use
* this version of the getJavaDate() method to handle it.
*
* @param date The Excel date.
* @param use1904windowing true if date uses 1904 windowing,
* or false if using 1900 date windowing.
* @return Java representation of the date, or null if date is not a valid Excel date
*/
public static LocalDate getLocalDate(double date, boolean use1904windowing) {
LocalDateTime localDateTime = getLocalDateTime(date, use1904windowing);
return localDateTime == null ? null : localDateTime.toLocalDate();
}
/**
* Determine if it is a date format.
*
* @param formatIndex
* @param formatString
* @return
*/
public static boolean isADateFormat(Short formatIndex, String formatString) {
if (formatIndex == null) {
return false;
}
Map<Short, Boolean> isDateCache = DATE_THREAD_LOCAL.get();
if (isDateCache == null) {
isDateCache = MapUtils.newHashMap();
DATE_THREAD_LOCAL.set(isDateCache);
} else {
Boolean isDatecachedDataList = isDateCache.get(formatIndex);
if (isDatecachedDataList != null) {
return isDatecachedDataList;
}
}
boolean isDate = isADateFormatUncached(formatIndex, formatString);
isDateCache.put(formatIndex, isDate);
return isDate;
}
/**
* Determine if it is a date format.
*
* @param formatIndex
* @param formatString
* @return
*/
public static boolean isADateFormatUncached(Short formatIndex, String formatString) {
// First up, is this an internal date format?
if (isInternalDateFormat(formatIndex)) {
return true;
}
if (StringUtils.isEmpty(formatString)) {
return false;
}
String fs = formatString;
final int length = fs.length();
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
char c = fs.charAt(i);
if (i < length - 1) {
char nc = fs.charAt(i + 1);
if (c == '\\') {
switch (nc) {
case '-':
case ',':
case '.':
case ' ':
case '\\':
// skip current '\' and continue to the next char
continue;
}
} else if (c == ';' && nc == '@') {
i++;
// skip ";@" duplets
continue;
}
}
sb.append(c);
}
fs = sb.toString();
// short-circuit if it indicates elapsed time: [h], [m] or [s]
if (date_ptrn4.matcher(fs).matches()) {
return true;
}
// If it starts with [DBNum1] or [DBNum2] or [DBNum3]
// then it could be a Chinese date
fs = date_ptrn5.matcher(fs).replaceAll("");
// If it starts with [$-...], then could be a date, but
// who knows what that starting bit is all about
fs = date_ptrn1.matcher(fs).replaceAll("");
// If it starts with something like [Black] or [Yellow],
// then it could be a date
fs = date_ptrn2.matcher(fs).replaceAll("");
// You're allowed something like dd/mm/yy;[red]dd/mm/yy
// which would place dates before 1900/1904 in red
// For now, only consider the first one
final int separatorIndex = fs.indexOf(';');
if (0 < separatorIndex && separatorIndex < fs.length() - 1) {
fs = fs.substring(0, separatorIndex);
}
// Ensure it has some date letters in it
// (Avoids false positives on the rest of pattern 3)
if (!date_ptrn3a.matcher(fs).find()) {
return false;
}
// If we get here, check it's only made up, in any case, of:
// y m d h s - \ / , . : [ ] T
// optionally followed by AM/PM
boolean result = date_ptrn3b.matcher(fs).matches();
if (result) {
return true;
}
result = date_ptrn6.matcher(fs).find();
return result;
}
/**
* Given a format ID this will check whether the format represents an internal excel date format or not.
*
* @see #isADateFormat(Short, String)
*/
public static boolean isInternalDateFormat(short format) {
switch (format) {
// Internal Date Formats as described on page 427 in
// Microsoft Excel Dev's Kit...
// 14-22
case 0x0e:
case 0x0f:
case 0x10:
case 0x11:
case 0x12:
case 0x13:
case 0x14:
case 0x15:
case 0x16:
// 45-47
case 0x2d:
case 0x2e:
case 0x2f:
return true;
}
return false;
}
public static void removeThreadLocalCache() {
DATE_THREAD_LOCAL.remove();
DATE_FORMAT_THREAD_LOCAL.remove();
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/EasyExcelTempFileCreationStrategy.java
|
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package ai.chat2db.excel.util;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.poi.util.DefaultTempFileCreationStrategy;
import org.apache.poi.util.TempFileCreationStrategy;
import static org.apache.poi.util.TempFile.JAVA_IO_TMPDIR;
/**
* In the scenario where `poifiles` are cleaned up, the {@link DefaultTempFileCreationStrategy} will throw a
* java.nio.file.NoSuchFileException. Therefore, it is necessary to verify the existence of the temporary file every
* time it is created.
*
* @author Jiaju Zhuang
*/
public class EasyExcelTempFileCreationStrategy implements TempFileCreationStrategy {
/**
* Name of POI files directory in temporary directory.
*/
public static final String POIFILES = "poifiles";
/**
* To use files.deleteOnExit after clean JVM exit, set the <code>-Dpoi.delete.tmp.files.on.exit</code> JVM property
*/
public static final String DELETE_FILES_ON_EXIT = "poi.delete.tmp.files.on.exit";
/**
* The directory where the temporary files will be created (<code>null</code> to use the default directory).
*/
private volatile File dir;
/**
* The lock to make dir initialized only once.
*/
private final Lock dirLock = new ReentrantLock();
/**
* Creates the strategy so that it creates the temporary files in the default directory.
*
* @see File#createTempFile(String, String)
*/
public EasyExcelTempFileCreationStrategy() {
this(null);
}
/**
* Creates the strategy allowing to set the
*
* @param dir The directory where the temporary files will be created (<code>null</code> to use the default
* directory).
* @see Files#createTempFile(Path, String, String, FileAttribute[])
*/
public EasyExcelTempFileCreationStrategy(File dir) {
this.dir = dir;
}
private void createPOIFilesDirectory() throws IOException {
// Create our temp dir only once by double-checked locking
// The directory is not deleted, even if it was created by this TempFileCreationStrategy
if (dir == null || !dir.exists()) {
dirLock.lock();
try {
if (dir == null || !dir.exists()) {
String tmpDir = System.getProperty(JAVA_IO_TMPDIR);
if (tmpDir == null) {
throw new IOException("System's temporary directory not defined - set the -D" + JAVA_IO_TMPDIR
+ " jvm property!");
}
Path dirPath = Paths.get(tmpDir, POIFILES);
dir = Files.createDirectories(dirPath).toFile();
}
} finally {
dirLock.unlock();
}
return;
}
}
@Override
public File createTempFile(String prefix, String suffix) throws IOException {
// Identify and create our temp dir, if needed
createPOIFilesDirectory();
// Generate a unique new filename
File newFile = Files.createTempFile(dir.toPath(), prefix, suffix).toFile();
// Set the delete on exit flag, but only when explicitly disabled
if (System.getProperty(DELETE_FILES_ON_EXIT) != null) {
newFile.deleteOnExit();
}
// All done
return newFile;
}
/* (non-JavaDoc) Created directory path is <JAVA_IO_TMPDIR>/poifiles/prefix0123456789 */
@Override
public File createTempDirectory(String prefix) throws IOException {
// Identify and create our temp dir, if needed
createPOIFilesDirectory();
// Generate a unique new filename
File newDirectory = Files.createTempDirectory(dir.toPath(), prefix).toFile();
//this method appears to be only used in tests, so it is probably ok to use deleteOnExit
newDirectory.deleteOnExit();
// All done
return newDirectory;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/FieldUtils.java
|
package ai.chat2db.excel.util;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;
import ai.chat2db.excel.metadata.NullObject;
import ai.chat2db.excel.support.cglib.beans.BeanMap;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Apache Software Foundation (ASF)
*/
public class FieldUtils {
public static Class<?> nullObjectClass = NullObject.class;
private static final int START_RESOLVE_FIELD_LENGTH = 2;
public static Class<?> getFieldClass(Map dataMap, String fieldName, Object value) {
if (dataMap instanceof BeanMap) {
Class<?> fieldClass = ((BeanMap)dataMap).getPropertyType(fieldName);
if (fieldClass != null) {
return fieldClass;
}
}
return getFieldClass(value);
}
public static Class<?> getFieldClass(Object value) {
if (value != null) {
return value.getClass();
}
return nullObjectClass;
}
/**
* Parsing the name matching cglib。
* <pre>
* null -> null
* string1 -> string1
* String2 -> string2
* sTring3 -> STring3
* STring4 -> STring4
* STRING5 -> STRING5
* STRing6 -> STRing6
* </pre>
*
* @param field field
* @return field name.
*/
public static String resolveCglibFieldName(Field field) {
if (field == null) {
return null;
}
String fieldName = field.getName();
if (StringUtils.isBlank(fieldName) || fieldName.length() < START_RESOLVE_FIELD_LENGTH) {
return fieldName;
}
char firstChar = fieldName.charAt(0);
char secondChar = fieldName.charAt(1);
if (Character.isUpperCase(firstChar) == Character.isUpperCase(secondChar)) {
return fieldName;
}
if (Character.isUpperCase(firstChar)) {
return buildFieldName(Character.toLowerCase(firstChar), fieldName);
}
return buildFieldName(Character.toUpperCase(firstChar), fieldName);
}
private static String buildFieldName(char firstChar, String fieldName) {
return firstChar + fieldName.substring(1);
}
/**
* Gets an accessible {@link Field} by name respecting scope. Superclasses/interfaces will be considered.
*
* @param cls the {@link Class} to reflect, must not be {@code null}
* @param fieldName the field name to obtain
* @return the Field object
* @throws IllegalArgumentException if the class is {@code null}, or the field name is blank or empty
*/
public static Field getField(final Class<?> cls, final String fieldName) {
final Field field = getField(cls, fieldName, false);
MemberUtils.setAccessibleWorkaround(field);
return field;
}
/**
* Gets an accessible {@link Field} by name, breaking scope if requested. Superclasses/interfaces will be
* considered.
*
* @param cls the {@link Class} to reflect, must not be {@code null}
* @param fieldName the field name to obtain
* @param forceAccess whether to break scope restrictions using the
* {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will
* only
* match {@code public} fields.
* @return the Field object
* @throws NullPointerException if the class is {@code null}
* @throws IllegalArgumentException if the field name is blank or empty or is matched at multiple places
* in the inheritance hierarchy
*/
public static Field getField(final Class<?> cls, final String fieldName, final boolean forceAccess) {
Validate.isTrue(cls != null, "The class must not be null");
Validate.isTrue(StringUtils.isNotBlank(fieldName), "The field name must not be blank/empty");
// FIXME is this workaround still needed? lang requires Java 6
// Sun Java 1.3 has a bugged implementation of getField hence we write the
// code ourselves
// getField() will return the Field object with the declaring class
// set correctly to the class that declares the field. Thus requesting the
// field on a subclass will return the field from the superclass.
//
// priority order for lookup:
// searchclass private/protected/package/public
// superclass protected/package/public
// private/different package blocks access to further superclasses
// implementedinterface public
// check up the superclass hierarchy
for (Class<?> acls = cls; acls != null; acls = acls.getSuperclass()) {
try {
final Field field = acls.getDeclaredField(fieldName);
// getDeclaredField checks for non-public scopes as well
// and it returns accurate results
if (!Modifier.isPublic(field.getModifiers())) {
if (forceAccess) {
field.setAccessible(true);
} else {
continue;
}
}
return field;
} catch (final NoSuchFieldException ex) { // NOPMD
// ignore
}
}
// check the public interface case. This must be manually searched for
// incase there is a public supersuperclass field hidden by a private/package
// superclass field.
Field match = null;
for (final Class<?> class1 : ClassUtils.getAllInterfaces(cls)) {
try {
final Field test = class1.getField(fieldName);
Validate.isTrue(match == null, "Reference to field %s is ambiguous relative to %s"
+ "; a matching field exists on two or more implemented interfaces.", fieldName, cls);
match = test;
} catch (final NoSuchFieldException ex) { // NOPMD
// ignore
}
}
return match;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/FileTypeUtils.java
|
package ai.chat2db.excel.util;
import java.util.HashMap;
import java.util.Map;
import ai.chat2db.excel.metadata.data.ImageData.ImageType;
/**
* file type utils
*
* @author Jiaju Zhuang
*/
public class FileTypeUtils {
private static final char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e',
'f'};
private static final int IMAGE_TYPE_MARK_LENGTH = 28;
private static final Map<String, ImageType> FILE_TYPE_MAP;
/**
* Default image type
*/
public static ImageType defaultImageType = ImageType.PICTURE_TYPE_PNG;
static {
FILE_TYPE_MAP = new HashMap<>();
FILE_TYPE_MAP.put("ffd8ff", ImageType.PICTURE_TYPE_JPEG);
FILE_TYPE_MAP.put("89504e47", ImageType.PICTURE_TYPE_PNG);
}
public static int getImageTypeFormat(byte[] image) {
ImageType imageType = getImageType(image);
if (imageType != null) {
return imageType.getValue();
}
return defaultImageType.getValue();
}
public static ImageType getImageType(byte[] image) {
if (image == null || image.length <= IMAGE_TYPE_MARK_LENGTH) {
return null;
}
byte[] typeMarkByte = new byte[IMAGE_TYPE_MARK_LENGTH];
System.arraycopy(image, 0, typeMarkByte, 0, IMAGE_TYPE_MARK_LENGTH);
return FILE_TYPE_MAP.get(encodeHexStr(typeMarkByte));
}
private static String encodeHexStr(byte[] data) {
final int len = data.length;
final char[] out = new char[len << 1];
// two characters from the hex value.
for (int i = 0, j = 0; i < len; i++) {
out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
out[j++] = DIGITS[0x0F & data[i]];
}
return new String(out);
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/FileUtils.java
|
package ai.chat2db.excel.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import ai.chat2db.excel.exception.ExcelAnalysisException;
import ai.chat2db.excel.exception.ExcelCommonException;
import org.apache.poi.util.TempFile;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Apache Software Foundation (ASF)
*/
public class FileUtils {
public static final String POI_FILES = "poifiles";
public static final String EX_CACHE = "excache";
/**
* If a server has multiple projects in use at the same time, a directory with the same name will be created under
* the temporary directory, but each project is run by a different user, so there is a permission problem, so each
* project creates a unique UUID as a separate Temporary Files.
*/
private static String tempFilePrefix =
System.getProperty(TempFile.JAVA_IO_TMPDIR) + File.separator + UUID.randomUUID().toString() + File.separator;
/**
* Used to store poi temporary files.
*/
private static String poiFilesPath = tempFilePrefix + POI_FILES + File.separator;
/**
* Used to store easy excel temporary files.
*/
private static String cachePath = tempFilePrefix + EX_CACHE + File.separator;
private static final int WRITE_BUFF_SIZE = 8192;
private FileUtils() {}
static {
// Create a temporary directory in advance
File tempFile = new File(tempFilePrefix);
createDirectory(tempFile);
tempFile.deleteOnExit();
// Initialize the cache directory
File cacheFile = new File(cachePath);
createDirectory(cacheFile);
}
/**
* Reads the contents of a file into a byte array. * The file is always closed.
*
* @param file
* @return
* @throws IOException
*/
public static byte[] readFileToByteArray(final File file) throws IOException {
InputStream in = openInputStream(file);
try {
final long fileLength = file.length();
return fileLength > 0 ? IoUtils.toByteArray(in, (int)fileLength) : IoUtils.toByteArray(in);
} finally {
in.close();
}
}
/**
* Opens a {@link FileInputStream} for the specified file, providing better error messages than simply calling
* <code>new FileInputStream(file)</code>.
* <p>
* At the end of the method either the stream will be successfully opened, or an exception will have been thrown.
* <p>
* An exception is thrown if the file does not exist. An exception is thrown if the file object exists but is a
* directory. An exception is thrown if the file exists but cannot be read.
*
* @param file
* @return
* @throws IOException
*/
public static FileInputStream openInputStream(final File file) throws IOException {
if (file.exists()) {
if (file.isDirectory()) {
throw new IOException("File '" + file + "' exists but is a directory");
}
if (file.canRead() == false) {
throw new IOException("File '" + file + "' cannot be read");
}
} else {
throw new FileNotFoundException("File '" + file + "' does not exist");
}
return new FileInputStream(file);
}
/**
* Write inputStream to file
*
* @param file file
* @param inputStream inputStream
*/
public static void writeToFile(File file, InputStream inputStream) {
writeToFile(file, inputStream, true);
}
/**
* Write inputStream to file
*
* @param file file
* @param inputStream inputStream
* @param closeInputStream closeInputStream
*/
public static void writeToFile(File file, InputStream inputStream, boolean closeInputStream) {
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
int bytesRead;
byte[] buffer = new byte[WRITE_BUFF_SIZE];
while ((bytesRead = inputStream.read(buffer, 0, WRITE_BUFF_SIZE)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
throw new ExcelAnalysisException("Can not create temporary file!", e);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
throw new ExcelAnalysisException("Can not close 'outputStream'!", e);
}
}
if (inputStream != null && closeInputStream) {
try {
inputStream.close();
} catch (IOException e) {
throw new ExcelAnalysisException("Can not close 'inputStream'", e);
}
}
}
}
public static void createPoiFilesDirectory() {
TempFile.setTempFileCreationStrategy(new EasyExcelTempFileCreationStrategy());
}
public static File createCacheTmpFile() {
return createDirectory(new File(cachePath + UUID.randomUUID().toString()));
}
public static File createTmpFile(String fileName) {
File directory = createDirectory(new File(tempFilePrefix));
return new File(directory, fileName);
}
/**
* @param directory
*/
public static File createDirectory(File directory) {
if (!directory.exists() && !directory.mkdirs()) {
throw new ExcelCommonException("Cannot create directory:" + directory.getAbsolutePath());
}
return directory;
}
/**
* delete file
*
* @param file
*/
public static void delete(File file) {
if (file.isFile()) {
file.delete();
return;
}
if (file.isDirectory()) {
File[] childFiles = file.listFiles();
if (childFiles == null || childFiles.length == 0) {
file.delete();
return;
}
for (int i = 0; i < childFiles.length; i++) {
delete(childFiles[i]);
}
file.delete();
}
}
public static String getTempFilePrefix() {
return tempFilePrefix;
}
public static void setTempFilePrefix(String tempFilePrefix) {
FileUtils.tempFilePrefix = tempFilePrefix;
}
public static String getPoiFilesPath() {
return poiFilesPath;
}
public static void setPoiFilesPath(String poiFilesPath) {
FileUtils.poiFilesPath = poiFilesPath;
}
public static String getCachePath() {
return cachePath;
}
public static void setCachePath(String cachePath) {
FileUtils.cachePath = cachePath;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/IntUtils.java
|
package ai.chat2db.excel.util;
/**
* Int utils
*
* @author Jiaju Zhuang
**/
public class IntUtils {
private IntUtils() {}
/**
* The largest power of two that can be represented as an {@code int}.
*
* @since 10.0
*/
public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2);
/**
* Returns the {@code int} nearest in value to {@code value}.
*
* @param value any {@code long} value
* @return the same value cast to {@code int} if it is in the range of the {@code int} type,
* {@link Integer#MAX_VALUE} if it is too large, or {@link Integer#MIN_VALUE} if it is too
* small
*/
public static int saturatedCast(long value) {
if (value > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if (value < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int) value;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/IoUtils.java
|
package ai.chat2db.excel.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* IO Utils
*
* @author Jiaju Zhuang
*/
public class IoUtils {
public static final int EOF = -1;
/**
* The default buffer size ({@value}) to use for
*/
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private IoUtils() {}
/**
* Gets the contents of an InputStream as a byte[].
*
* @param input
* @return
* @throws IOException
*/
public static byte[] toByteArray(final InputStream input) throws IOException {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
copy(input, output);
return output.toByteArray();
} finally {
output.toByteArray();
}
}
/**
* Gets the contents of an InputStream as a byte[].
*
* @param input
* @param size
* @return
* @throws IOException
*/
public static byte[] toByteArray(final InputStream input, final int size) throws IOException {
if (size < 0) {
throw new IllegalArgumentException("Size must be equal or greater than zero: " + size);
}
if (size == 0) {
return new byte[0];
}
final byte[] data = new byte[size];
int offset = 0;
int read;
while (offset < size && (read = input.read(data, offset, size - offset)) != EOF) {
offset += read;
}
if (offset != size) {
throw new IOException("Unexpected read size. current: " + offset + ", expected: " + size);
}
return data;
}
/**
* Copies bytes
*
* @param input
* @param output
* @return
* @throws IOException
*/
public static int copy(final InputStream input, final OutputStream output) throws IOException {
long count = 0;
int n;
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
while (EOF != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
if (count > Integer.MAX_VALUE) {
return -1;
}
return (int)count;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/ListUtils.java
|
package ai.chat2db.excel.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import lombok.NonNull;
import org.apache.commons.compress.utils.Iterators;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Apache Software Foundation (ASF)
*/
public class ListUtils {
private ListUtils() {}
/**
* Creates a <i>mutable</i>, empty {@code ArrayList} instance (for Java 6 and earlier).
*
* <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
* deprecated. Instead, use the {@code ArrayList} {@linkplain ArrayList#ArrayList() constructor}
* directly, taking advantage of the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*/
public static <E> ArrayList<E> newArrayList() {
return new ArrayList<>();
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements.
*
*/
public static <E> ArrayList<E> newArrayList(E... elements) {
checkNotNull(elements);
// Avoid integer overflow when a large array is passed in
int capacity = computeArrayListCapacity(elements.length);
ArrayList<E> list = new ArrayList<>(capacity);
Collections.addAll(list, elements);
return list;
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements; a very thin
* shortcut for creating an empty list and then calling {@link Iterators#addAll}.
*
*/
public static <E> ArrayList<E> newArrayList(Iterator<? extends E> elements) {
ArrayList<E> list = newArrayList();
Iterators.addAll(list, elements);
return list;
}
/**
* Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements;
*
*
* <p><b>Note for Java 7 and later:</b> if {@code elements} is a {@link Collection}, you don't
* need this method. Use the {@code ArrayList} {@linkplain ArrayList#ArrayList(Collection)
* constructor} directly, taking advantage of the new <a href="http://goo.gl/iz2Wi">"diamond"
* syntax</a>.
*/
public static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) {
checkNotNull(elements); // for GWT
// Let ArrayList's sizing logic work, if possible
return (elements instanceof Collection)
? new ArrayList<>((Collection<? extends E>)elements)
: newArrayList(elements.iterator());
}
/**
* Creates an {@code ArrayList} instance backed by an array with the specified initial size;
* simply delegates to {@link ArrayList#ArrayList(int)}.
*
* <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
* deprecated. Instead, use {@code new }{@link ArrayList#ArrayList(int) ArrayList}{@code <>(int)}
* directly, taking advantage of the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
* (Unlike here, there is no risk of overload ambiguity, since the {@code ArrayList} constructors
* very wisely did not accept varargs.)
*
* @param initialArraySize the exact size of the initial backing array for the returned array list
* ({@code ArrayList} documentation calls this value the "capacity")
* @return a new, empty {@code ArrayList} which is guaranteed not to resize itself unless its size
* reaches {@code initialArraySize + 1}
* @throws IllegalArgumentException if {@code initialArraySize} is negative
*/
public static <E> ArrayList<E> newArrayListWithCapacity(int initialArraySize) {
checkNonnegative(initialArraySize, "initialArraySize");
return new ArrayList<>(initialArraySize);
}
/**
* Creates an {@code ArrayList} instance to hold {@code estimatedSize} elements, <i>plus</i> an
* unspecified amount of padding; you almost certainly mean to call {@link
* #newArrayListWithCapacity} (see that method for further advice on usage).
*
* <p><b>Note:</b> This method will soon be deprecated. Even in the rare case that you do want
* some amount of padding, it's best if you choose your desired amount explicitly.
*
* @param estimatedSize an estimate of the eventual {@link List#size()} of the new list
* @return a new, empty {@code ArrayList}, sized appropriately to hold the estimated number of
* elements
* @throws IllegalArgumentException if {@code estimatedSize} is negative
*/
public static <E> ArrayList<E> newArrayListWithExpectedSize(int estimatedSize) {
return new ArrayList<>(computeArrayListCapacity(estimatedSize));
}
static int computeArrayListCapacity(int arraySize) {
checkNonnegative(arraySize, "arraySize");
return IntUtils.saturatedCast(5L + arraySize + (arraySize / 10));
}
static int checkNonnegative(int value, String name) {
if (value < 0) {
throw new IllegalArgumentException(name + " cannot be negative but was: " + value);
}
return value;
}
/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T extends @NonNull Object> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/MapUtils.java
|
package ai.chat2db.excel.util;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.TreeMap;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Apache Software Foundation (ASF)
*/
public class MapUtils {
private MapUtils() {}
/**
* Creates a <i>mutable</i>, empty {@code HashMap} instance.
*
* <p><b>Note:</b> if mutability is not required, use ImmutableMap.of() instead.
*
* <p><b>Note:</b> if {@code K} is an {@code enum} type, use newEnumMap instead.
*
* <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
* deprecated. Instead, use the {@code HashMap} constructor directly, taking advantage of the new
* <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @return a new, empty {@code HashMap}
*/
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<>(16);
}
/**
* Creates a <i>mutable</i>, empty {@code TreeMap} instance using the natural ordering of its
* elements.
*
* <p><b>Note:</b> if mutability is not required, use ImmutableSortedMap.of() instead.
*
* <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
* deprecated. Instead, use the {@code TreeMap} constructor directly, taking advantage of the new
* <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @return a new, empty {@code TreeMap}
*/
public static <K extends Comparable, V> TreeMap<K, V> newTreeMap() {
return new TreeMap<>();
}
/**
* Creates a {@code HashMap} instance, with a high enough "initial capacity" that it <i>should</i>
* hold {@code expectedSize} elements without growth. This behavior cannot be broadly guaranteed,
* but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed that the method
* isn't inadvertently <i>oversizing</i> the returned map.
*
* @param expectedSize the number of entries you expect to add to the returned map
* @return a new, empty {@code HashMap} with enough capacity to hold {@code expectedSize} entries
* without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
*/
public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(int expectedSize) {
return new HashMap<>(capacity(expectedSize));
}
/**
* Creates a <i>mutable</i>, empty, insertion-ordered {@code LinkedHashMap} instance.
*
* <p><b>Note:</b> if mutability is not required, use ImmutableMap.of() instead.
*
* <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
* deprecated. Instead, use the {@code LinkedHashMap} constructor directly, taking advantage of
* the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
*
* @return a new, empty {@code LinkedHashMap}
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() {
return new LinkedHashMap<>();
}
/**
* Creates a {@code LinkedHashMap} instance, with a high enough "initial capacity" that it
* <i>should</i> hold {@code expectedSize} elements without growth. This behavior cannot be
* broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed
* that the method isn't inadvertently <i>oversizing</i> the returned map.
*
* @param expectedSize the number of entries you expect to add to the returned map
* @return a new, empty {@code LinkedHashMap} with enough capacity to hold {@code expectedSize}
* entries without resizing
* @throws IllegalArgumentException if {@code expectedSize} is negative
* @since 19.0
*/
public static <K, V> LinkedHashMap<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) {
return new LinkedHashMap<>(capacity(expectedSize));
}
/**
* Returns a capacity that is sufficient to keep the map from being resized as long as it grows no
* larger than expectedSize and the load factor is ≥ its default (0.75).
*/
static int capacity(int expectedSize) {
if (expectedSize < 3) {
return expectedSize + 1;
}
if (expectedSize < IntUtils.MAX_POWER_OF_TWO) {
// This is the calculation used in JDK8 to resize when a putAll
// happens; it seems to be the most conservative calculation we
// can make. 0.75 is the default load factor.
return (int)((float)expectedSize / 0.75F + 1.0F);
}
return Integer.MAX_VALUE;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/MemberUtils.java
|
package ai.chat2db.excel.util;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Apache Software Foundation (ASF)
*/
public class MemberUtils {
private static final int ACCESS_TEST = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE;
/**
* XXX Default access superclass workaround.
*
* When a {@code public} class has a default access superclass with {@code public} members,
* these members are accessible. Calling them from compiled code works fine.
* Unfortunately, on some JVMs, using reflection to invoke these members
* seems to (wrongly) prevent access even when the modifier is {@code public}.
* Calling {@code setAccessible(true)} solves the problem but will only work from
* sufficiently privileged code. Better workarounds would be gratefully
* accepted.
* @param o the AccessibleObject to set as accessible
* @return a boolean indicating whether the accessibility of the object was set to true.
*/
static boolean setAccessibleWorkaround(final AccessibleObject o) {
if (o == null || o.isAccessible()) {
return false;
}
final Member m = (Member) o;
if (!o.isAccessible() && Modifier.isPublic(m.getModifiers()) && isPackageAccess(m.getDeclaringClass().getModifiers())) {
try {
o.setAccessible(true);
return true;
} catch (final SecurityException e) { // NOPMD
// ignore in favor of subsequent IllegalAccessException
}
}
return false;
}
/**
* Returns whether a given set of modifiers implies package access.
* @param modifiers to test
* @return {@code true} unless {@code package}/{@code protected}/{@code private} modifier detected
*/
static boolean isPackageAccess(final int modifiers) {
return (modifiers & ACCESS_TEST) == 0;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/NumberDataFormatterUtils.java
|
package ai.chat2db.excel.util;
import java.math.BigDecimal;
import java.util.Locale;
import ai.chat2db.excel.metadata.GlobalConfiguration;
import ai.chat2db.excel.metadata.format.DataFormatter;
/**
* Convert number data, including date.
*
* @author Jiaju Zhuang
**/
public class NumberDataFormatterUtils {
/**
* Cache DataFormatter.
*/
private static final ThreadLocal<DataFormatter> DATA_FORMATTER_THREAD_LOCAL = new ThreadLocal<DataFormatter>();
/**
* Format number data.
*
* @param data
* @param dataFormat Not null.
* @param dataFormatString
* @param globalConfiguration
* @return
*/
public static String format(BigDecimal data, Short dataFormat, String dataFormatString,
GlobalConfiguration globalConfiguration) {
if (globalConfiguration == null) {
return format(data, dataFormat, dataFormatString, null, null, null);
}
return format(data, dataFormat, dataFormatString, globalConfiguration.getUse1904windowing(),
globalConfiguration.getLocale(), globalConfiguration.getUseScientificFormat());
}
/**
* Format number data.
*
* @param data
* @param dataFormat Not null.
* @param dataFormatString
* @param use1904windowing
* @param locale
* @param useScientificFormat
* @return
*/
public static String format(BigDecimal data, Short dataFormat, String dataFormatString, Boolean use1904windowing,
Locale locale, Boolean useScientificFormat) {
DataFormatter dataFormatter = DATA_FORMATTER_THREAD_LOCAL.get();
if (dataFormatter == null) {
dataFormatter = new DataFormatter(use1904windowing, locale, useScientificFormat);
DATA_FORMATTER_THREAD_LOCAL.set(dataFormatter);
}
return dataFormatter.format(data, dataFormat, dataFormatString);
}
public static void removeThreadLocalCache() {
DATA_FORMATTER_THREAD_LOCAL.remove();
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/NumberUtils.java
|
package ai.chat2db.excel.util;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import ai.chat2db.excel.metadata.data.WriteCellData;
import ai.chat2db.excel.metadata.property.ExcelContentProperty;
/**
* Number utils
*
* @author Jiaju Zhuang
*/
public class NumberUtils {
private NumberUtils() {}
/**
* format
*
* @param num
* @param contentProperty
* @return
*/
public static String format(Number num, ExcelContentProperty contentProperty) {
if (contentProperty == null || contentProperty.getNumberFormatProperty() == null
|| StringUtils.isEmpty(contentProperty.getNumberFormatProperty().getFormat())) {
if (num instanceof BigDecimal) {
return ((BigDecimal)num).toPlainString();
} else {
return num.toString();
}
}
String format = contentProperty.getNumberFormatProperty().getFormat();
RoundingMode roundingMode = contentProperty.getNumberFormatProperty().getRoundingMode();
DecimalFormat decimalFormat = new DecimalFormat(format);
decimalFormat.setRoundingMode(roundingMode);
return decimalFormat.format(num);
}
/**
* format
*
* @param num
* @param contentProperty
* @return
*/
public static WriteCellData<?> formatToCellDataString(Number num, ExcelContentProperty contentProperty) {
return new WriteCellData<>(format(num, contentProperty));
}
/**
* format
*
* @param num
* @param contentProperty
* @return
*/
public static WriteCellData<?> formatToCellData(Number num, ExcelContentProperty contentProperty) {
WriteCellData<?> cellData = new WriteCellData<>(new BigDecimal(num.toString()));
if (contentProperty != null && contentProperty.getNumberFormatProperty() != null
&& StringUtils.isNotBlank(contentProperty.getNumberFormatProperty().getFormat())) {
WorkBookUtil.fillDataFormat(cellData, contentProperty.getNumberFormatProperty().getFormat(), null);
}
return cellData;
}
/**
* parse
*
* @param string
* @param contentProperty
* @return
*/
public static Short parseShort(String string, ExcelContentProperty contentProperty) throws ParseException {
if (!hasFormat(contentProperty)) {
return new BigDecimal(string).shortValue();
}
return parse(string, contentProperty).shortValue();
}
/**
* parse
*
* @param string
* @param contentProperty
* @return
*/
public static Long parseLong(String string, ExcelContentProperty contentProperty) throws ParseException {
if (!hasFormat(contentProperty)) {
return new BigDecimal(string).longValue();
}
return parse(string, contentProperty).longValue();
}
/**
* parse Integer from string
*
* @param string An integer read in string format
* @param contentProperty Properties of the content read in
* @return An integer converted from a string
*/
public static Integer parseInteger(String string, ExcelContentProperty contentProperty) throws ParseException {
if (!hasFormat(contentProperty)) {
return new BigDecimal(string).intValue();
}
return parse(string, contentProperty).intValue();
}
/**
* parse
*
* @param string
* @param contentProperty
* @return
*/
public static Float parseFloat(String string, ExcelContentProperty contentProperty) throws ParseException {
if (!hasFormat(contentProperty)) {
return new BigDecimal(string).floatValue();
}
return parse(string, contentProperty).floatValue();
}
/**
* parse
*
* @param string
* @param contentProperty
* @return
*/
public static BigDecimal parseBigDecimal(String string, ExcelContentProperty contentProperty)
throws ParseException {
if (!hasFormat(contentProperty)) {
return new BigDecimal(string);
}
return new BigDecimal(parse(string, contentProperty).toString());
}
/**
* parse
*
* @param string
* @param contentProperty
* @return
*/
public static Byte parseByte(String string, ExcelContentProperty contentProperty) throws ParseException {
if (!hasFormat(contentProperty)) {
return new BigDecimal(string).byteValue();
}
return parse(string, contentProperty).byteValue();
}
/**
* parse
*
* @param string
* @param contentProperty
* @return
*/
public static Double parseDouble(String string, ExcelContentProperty contentProperty) throws ParseException {
if (!hasFormat(contentProperty)) {
return new BigDecimal(string).doubleValue();
}
return parse(string, contentProperty).doubleValue();
}
private static boolean hasFormat(ExcelContentProperty contentProperty) {
return contentProperty != null && contentProperty.getNumberFormatProperty() != null
&& !StringUtils.isEmpty(contentProperty.getNumberFormatProperty().getFormat());
}
/**
* parse
*
* @param string
* @param contentProperty
* @return
* @throws ParseException
*/
private static Number parse(String string, ExcelContentProperty contentProperty) throws ParseException {
String format = contentProperty.getNumberFormatProperty().getFormat();
RoundingMode roundingMode = contentProperty.getNumberFormatProperty().getRoundingMode();
DecimalFormat decimalFormat = new DecimalFormat(format);
decimalFormat.setRoundingMode(roundingMode);
decimalFormat.setParseBigDecimal(true);
return decimalFormat.parse(string);
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/PoiUtils.java
|
package ai.chat2db.excel.util;
import org.apache.poi.hssf.record.RowRecord;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.util.BitField;
import org.apache.poi.util.BitFieldFactory;
import org.apache.poi.xssf.usermodel.XSSFRow;
import java.lang.reflect.Field;
/**
* utils
*
* @author Jiaju Zhuang
*/
public class PoiUtils {
/**
* Whether to customize the height
*/
public static final BitField CUSTOM_HEIGHT = BitFieldFactory.getInstance(0x640);
private static final Field ROW_RECORD_FIELD = FieldUtils.getField(HSSFRow.class, "row", true);
/**
* Whether to customize the height
*
* @param row row
* @return
*/
public static boolean customHeight(Row row) {
if (row instanceof XSSFRow) {
XSSFRow xssfRow = (XSSFRow)row;
return xssfRow.getCTRow().getCustomHeight();
}
if (row instanceof HSSFRow) {
HSSFRow hssfRow = (HSSFRow)row;
try {
RowRecord record = (RowRecord)ROW_RECORD_FIELD.get(hssfRow);
return CUSTOM_HEIGHT.getValue(record.getOptionFlags()) == 1;
} catch (IllegalAccessException ignore) {
}
}
return false;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/PositionUtils.java
|
package ai.chat2db.excel.util;
import java.util.regex.Pattern;
/**
* @author jipengfei
*/
public class PositionUtils {
private static final Pattern CELL_REF_PATTERN = Pattern.compile("(\\$?[A-Z]+)?" + "(\\$?[0-9]+)?",
Pattern.CASE_INSENSITIVE);
private static final char SHEET_NAME_DELIMITER = '!';
private static final char REDUNDANT_CHARACTERS = '$';
private PositionUtils() {}
public static int getRowByRowTagt(String rowTagt, Integer before) {
int row;
if (rowTagt != null) {
row = Integer.parseInt(rowTagt) - 1;
return row;
} else {
if (before == null) {
before = -1;
}
return before + 1;
}
}
public static int getRow(String currentCellIndex) {
if (currentCellIndex == null) {
return -1;
}
int firstNumber = currentCellIndex.length() - 1;
for (; firstNumber >= 0; firstNumber--) {
char c = currentCellIndex.charAt(firstNumber);
if (c < '0' || c > '9') {
break;
}
}
return Integer.parseUnsignedInt(currentCellIndex.substring(firstNumber + 1)) - 1;
}
public static int getCol(String currentCellIndex, Integer before) {
if (currentCellIndex == null) {
if (before == null) {
before = -1;
}
return before + 1;
}
int firstNumber = currentCellIndex.charAt(0) == REDUNDANT_CHARACTERS ? 1 : 0;
int col = 0;
for (; firstNumber < currentCellIndex.length(); firstNumber++) {
char c = currentCellIndex.charAt(firstNumber);
boolean isNotLetter = c == REDUNDANT_CHARACTERS || (c >= '0' && c <= '9');
if (isNotLetter) {
break;
}
col = col * 26 + Character.toUpperCase(c) - 'A' + 1;
}
return col - 1;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/SheetUtils.java
|
package ai.chat2db.excel.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.chat2db.excel.context.AnalysisContext;
import ai.chat2db.excel.read.metadata.ReadSheet;
import ai.chat2db.excel.read.metadata.holder.ReadWorkbookHolder;
/**
* Sheet utils
*
* @author Jiaju Zhuang
*/
public class SheetUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(SheetUtils.class);
private SheetUtils() {}
/**
* Match the parameters to the actual sheet
*
* @param readSheet actual sheet
* @param analysisContext
* @return
*/
public static ReadSheet match(ReadSheet readSheet, AnalysisContext analysisContext) {
ReadWorkbookHolder readWorkbookHolder = analysisContext.readWorkbookHolder();
if (readWorkbookHolder.getReadAll()) {
return readSheet;
}
for (ReadSheet parameterReadSheet : readWorkbookHolder.getParameterSheetDataList()) {
if (parameterReadSheet == null) {
continue;
}
if (parameterReadSheet.getSheetNo() == null && parameterReadSheet.getSheetName() == null) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("The first is read by default.");
}
parameterReadSheet.setSheetNo(0);
}
boolean match = (parameterReadSheet.getSheetNo() != null
&& parameterReadSheet.getSheetNo().equals(readSheet.getSheetNo()));
if (!match) {
String parameterSheetName = parameterReadSheet.getSheetName();
if (!StringUtils.isEmpty(parameterSheetName)) {
boolean autoTrim = (parameterReadSheet.getAutoTrim() != null && parameterReadSheet.getAutoTrim())
|| (parameterReadSheet.getAutoTrim() == null
&& analysisContext.readWorkbookHolder().getGlobalConfiguration().getAutoTrim());
String sheetName = readSheet.getSheetName();
if (autoTrim) {
parameterSheetName = parameterSheetName.trim();
sheetName = sheetName.trim();
}
match = parameterSheetName.equals(sheetName);
}
}
if (match) {
readSheet.copyBasicParameter(parameterReadSheet);
return readSheet;
}
}
return null;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/StringUtils.java
|
package ai.chat2db.excel.util;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Apache Software Foundation (ASF)
*/
public class StringUtils {
private StringUtils() {}
/**
* A String for a space character.
*/
public static final String SPACE = " ";
/**
* The empty String {@code ""}.
*/
public static final String EMPTY = "";
/**
* <p>Checks if a CharSequence is empty ("") or null.</p>
*
* <pre>
* StringUtils.isEmpty(null) = true
* StringUtils.isEmpty("") = true
* StringUtils.isEmpty(" ") = false
* StringUtils.isEmpty("bob") = false
* StringUtils.isEmpty(" bob ") = false
* </pre>
*
* <p>NOTE: This method changed in Lang version 2.0.
* It no longer trims the CharSequence.
* That functionality is available in isBlank().</p>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is empty or null
*/
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
/**
* <p>Checks if a CharSequence is empty (""), null or whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is null, empty or whitespace only
*/
public static boolean isBlank(final CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
/**
* <p>Checks if a CharSequence is not empty (""), not null and not whitespace only.</p>
*
* <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p>
*
* <pre>
* StringUtils.isNotBlank(null) = false
* StringUtils.isNotBlank("") = false
* StringUtils.isNotBlank(" ") = false
* StringUtils.isNotBlank("bob") = true
* StringUtils.isNotBlank(" bob ") = true
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is
* not empty and not null and not whitespace only
* @since 2.0
* @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence)
*/
public static boolean isNotBlank(final CharSequence cs) {
return !isBlank(cs);
}
/**
* <p>Compares two CharSequences, returning {@code true} if they represent
* equal sequences of characters.</p>
*
* <p>{@code null}s are handled without exceptions. Two {@code null}
* references are considered to be equal. The comparison is case sensitive.</p>
*
* <pre>
* StringUtils.equals(null, null) = true
* StringUtils.equals(null, "abc") = false
* StringUtils.equals("abc", null) = false
* StringUtils.equals("abc", "abc") = true
* StringUtils.equals("abc", "ABC") = false
* </pre>
*
* @param cs1 the first CharSequence, may be {@code null}
* @param cs2 the second CharSequence, may be {@code null}
* @return {@code true} if the CharSequences are equal (case-sensitive), or both {@code null}
* @see Object#equals(Object)
* @since 3.0 Changed signature from equals(String, String) to equals(CharSequence, CharSequence)
*/
public static boolean equals(final CharSequence cs1, final CharSequence cs2) {
if (cs1 == cs2) {
return true;
}
if (cs1 == null || cs2 == null) {
return false;
}
if (cs1.length() != cs2.length()) {
return false;
}
if (cs1 instanceof String && cs2 instanceof String) {
return cs1.equals(cs2);
}
return regionMatches(cs1, false, 0, cs2, 0, cs1.length());
}
/**
* Green implementation of regionMatches.
*
* @param cs the {@code CharSequence} to be processed
* @param ignoreCase whether or not to be case insensitive
* @param thisStart the index to start on the {@code cs} CharSequence
* @param substring the {@code CharSequence} to be looked for
* @param start the index to start on the {@code substring} CharSequence
* @param length character length of the region
* @return whether the region matched
*/
public static boolean regionMatches(final CharSequence cs, final boolean ignoreCase, final int thisStart,
final CharSequence substring, final int start, final int length) {
if (cs instanceof String && substring instanceof String) {
return ((String)cs).regionMatches(ignoreCase, thisStart, (String)substring, start, length);
}
int index1 = thisStart;
int index2 = start;
int tmpLen = length;
// Extract these first so we detect NPEs the same as the java.lang.String version
final int srcLen = cs.length() - thisStart;
final int otherLen = substring.length() - start;
// Check for invalid parameters
if (thisStart < 0 || start < 0 || length < 0) {
return false;
}
// Check that the regions are long enough
if (srcLen < length || otherLen < length) {
return false;
}
while (tmpLen-- > 0) {
final char c1 = cs.charAt(index1++);
final char c2 = substring.charAt(index2++);
if (c1 == c2) {
continue;
}
if (!ignoreCase) {
return false;
}
// The same check as in String.regionMatches():
if (Character.toUpperCase(c1) != Character.toUpperCase(c2)
&& Character.toLowerCase(c1) != Character.toLowerCase(c2)) {
return false;
}
}
return true;
}
/**
* <p>Checks if the CharSequence contains only Unicode digits.
* A decimal point is not a Unicode digit and returns false.</p>
*
* <p>{@code null} will return {@code false}.
* An empty CharSequence (length()=0) will return {@code false}.</p>
*
* <p>Note that the method does not allow for a leading sign, either positive or negative.
* Also, if a String passes the numeric test, it may still generate a NumberFormatException
* when parsed by Integer.parseInt or Long.parseLong, e.g. if the value is outside the range
* for int or long respectively.</p>
*
* <pre>
* StringUtils.isNumeric(null) = false
* StringUtils.isNumeric("") = false
* StringUtils.isNumeric(" ") = false
* StringUtils.isNumeric("123") = true
* StringUtils.isNumeric("\u0967\u0968\u0969") = true
* StringUtils.isNumeric("12 3") = false
* StringUtils.isNumeric("ab2c") = false
* StringUtils.isNumeric("12-3") = false
* StringUtils.isNumeric("12.3") = false
* StringUtils.isNumeric("-123") = false
* StringUtils.isNumeric("+123") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if only contains digits, and is non-null
* @since 3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence)
* @since 3.0 Changed "" to return false and not true
*/
public static boolean isNumeric(final CharSequence cs) {
if (isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isDigit(cs.charAt(i))) {
return false;
}
}
return true;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/StyleUtil.java
|
package ai.chat2db.excel.util;
import java.util.Optional;
import ai.chat2db.excel.constant.BuiltinFormats;
import ai.chat2db.excel.metadata.data.DataFormatData;
import ai.chat2db.excel.metadata.data.HyperlinkData;
import ai.chat2db.excel.metadata.data.RichTextStringData;
import ai.chat2db.excel.metadata.data.RichTextStringData.IntervalFont;
import ai.chat2db.excel.support.ExcelTypeEnum;
import ai.chat2db.excel.write.metadata.holder.WriteWorkbookHolder;
import ai.chat2db.excel.write.metadata.style.WriteCellStyle;
import ai.chat2db.excel.write.metadata.style.WriteFont;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.Units;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
/**
* @author jipengfei
*/
@Slf4j
public class StyleUtil {
private StyleUtil() {}
/**
* Build cell style
*
* @param workbook
* @param originCellStyle
* @param writeCellStyle
* @return
*/
public static CellStyle buildCellStyle(Workbook workbook, CellStyle originCellStyle,
WriteCellStyle writeCellStyle) {
CellStyle cellStyle = workbook.createCellStyle();
if (originCellStyle != null) {
cellStyle.cloneStyleFrom(originCellStyle);
}
if (writeCellStyle == null) {
return cellStyle;
}
buildCellStyle(cellStyle, writeCellStyle);
return cellStyle;
}
private static void buildCellStyle(CellStyle cellStyle, WriteCellStyle writeCellStyle) {
if (writeCellStyle.getHidden() != null) {
cellStyle.setHidden(writeCellStyle.getHidden());
}
if (writeCellStyle.getLocked() != null) {
cellStyle.setLocked(writeCellStyle.getLocked());
}
if (writeCellStyle.getQuotePrefix() != null) {
cellStyle.setQuotePrefixed(writeCellStyle.getQuotePrefix());
}
if (writeCellStyle.getHorizontalAlignment() != null) {
cellStyle.setAlignment(writeCellStyle.getHorizontalAlignment());
}
if (writeCellStyle.getWrapped() != null) {
cellStyle.setWrapText(writeCellStyle.getWrapped());
}
if (writeCellStyle.getVerticalAlignment() != null) {
cellStyle.setVerticalAlignment(writeCellStyle.getVerticalAlignment());
}
if (writeCellStyle.getRotation() != null) {
cellStyle.setRotation(writeCellStyle.getRotation());
}
if (writeCellStyle.getIndent() != null) {
cellStyle.setIndention(writeCellStyle.getIndent());
}
if (writeCellStyle.getBorderLeft() != null) {
cellStyle.setBorderLeft(writeCellStyle.getBorderLeft());
}
if (writeCellStyle.getBorderRight() != null) {
cellStyle.setBorderRight(writeCellStyle.getBorderRight());
}
if (writeCellStyle.getBorderTop() != null) {
cellStyle.setBorderTop(writeCellStyle.getBorderTop());
}
if (writeCellStyle.getBorderBottom() != null) {
cellStyle.setBorderBottom(writeCellStyle.getBorderBottom());
}
if (writeCellStyle.getLeftBorderColor() != null) {
cellStyle.setLeftBorderColor(writeCellStyle.getLeftBorderColor());
}
if (writeCellStyle.getRightBorderColor() != null) {
cellStyle.setRightBorderColor(writeCellStyle.getRightBorderColor());
}
if (writeCellStyle.getTopBorderColor() != null) {
cellStyle.setTopBorderColor(writeCellStyle.getTopBorderColor());
}
if (writeCellStyle.getBottomBorderColor() != null) {
cellStyle.setBottomBorderColor(writeCellStyle.getBottomBorderColor());
}
if (writeCellStyle.getFillPatternType() != null) {
cellStyle.setFillPattern(writeCellStyle.getFillPatternType());
}
if (writeCellStyle.getFillBackgroundColor() != null) {
cellStyle.setFillBackgroundColor(writeCellStyle.getFillBackgroundColor());
}
if (writeCellStyle.getFillForegroundColor() != null) {
cellStyle.setFillForegroundColor(writeCellStyle.getFillForegroundColor());
}
if (writeCellStyle.getShrinkToFit() != null) {
cellStyle.setShrinkToFit(writeCellStyle.getShrinkToFit());
}
}
public static short buildDataFormat(Workbook workbook, DataFormatData dataFormatData) {
if (dataFormatData == null) {
return BuiltinFormats.GENERAL;
}
if (dataFormatData.getIndex() != null && dataFormatData.getIndex() >= 0) {
return dataFormatData.getIndex();
}
if (StringUtils.isNotBlank(dataFormatData.getFormat())) {
if (log.isDebugEnabled()) {
log.info("create new data fromat:{}", dataFormatData);
}
DataFormat dataFormatCreate = workbook.createDataFormat();
return dataFormatCreate.getFormat(dataFormatData.getFormat());
}
return BuiltinFormats.GENERAL;
}
public static Font buildFont(Workbook workbook, Font originFont, WriteFont writeFont) {
if (log.isDebugEnabled()) {
log.info("create new font:{},{}", writeFont, originFont);
}
if (writeFont == null && originFont == null) {
return null;
}
Font font = createFont(workbook, originFont, writeFont);
if (writeFont == null || font == null) {
return font;
}
if (writeFont.getFontName() != null) {
font.setFontName(writeFont.getFontName());
}
if (writeFont.getFontHeightInPoints() != null) {
font.setFontHeightInPoints(writeFont.getFontHeightInPoints());
}
if (writeFont.getItalic() != null) {
font.setItalic(writeFont.getItalic());
}
if (writeFont.getStrikeout() != null) {
font.setStrikeout(writeFont.getStrikeout());
}
if (writeFont.getColor() != null) {
font.setColor(writeFont.getColor());
}
if (writeFont.getTypeOffset() != null) {
font.setTypeOffset(writeFont.getTypeOffset());
}
if (writeFont.getUnderline() != null) {
font.setUnderline(writeFont.getUnderline());
}
if (writeFont.getCharset() != null) {
font.setCharSet(writeFont.getCharset());
}
if (writeFont.getBold() != null) {
font.setBold(writeFont.getBold());
}
return font;
}
private static Font createFont(Workbook workbook, Font originFont, WriteFont writeFont) {
Font font = workbook.createFont();
if (originFont == null) {
return font;
}
if (originFont instanceof XSSFFont) {
XSSFFont xssfFont = (XSSFFont)font;
XSSFFont xssfOriginFont = ((XSSFFont)originFont);
xssfFont.setFontName(xssfOriginFont.getFontName());
xssfFont.setFontHeightInPoints(xssfOriginFont.getFontHeightInPoints());
xssfFont.setItalic(xssfOriginFont.getItalic());
xssfFont.setStrikeout(xssfOriginFont.getStrikeout());
// Colors cannot be overwritten
if (writeFont == null || writeFont.getColor() == null) {
xssfFont.setColor(Optional.of(xssfOriginFont)
.map(XSSFFont::getXSSFColor)
.map(XSSFColor::getRGB)
.map(rgb -> new XSSFColor(rgb, null))
.orElse(null));
}
xssfFont.setTypeOffset(xssfOriginFont.getTypeOffset());
xssfFont.setUnderline(xssfOriginFont.getUnderline());
xssfFont.setCharSet(xssfOriginFont.getCharSet());
xssfFont.setBold(xssfOriginFont.getBold());
return xssfFont;
} else if (originFont instanceof HSSFFont) {
HSSFFont hssfFont = (HSSFFont)font;
HSSFFont hssfOriginFont = (HSSFFont)originFont;
hssfFont.setFontName(hssfOriginFont.getFontName());
hssfFont.setFontHeightInPoints(hssfOriginFont.getFontHeightInPoints());
hssfFont.setItalic(hssfOriginFont.getItalic());
hssfFont.setStrikeout(hssfOriginFont.getStrikeout());
hssfFont.setColor(hssfOriginFont.getColor());
hssfFont.setTypeOffset(hssfOriginFont.getTypeOffset());
hssfFont.setUnderline(hssfOriginFont.getUnderline());
hssfFont.setCharSet(hssfOriginFont.getCharSet());
hssfFont.setBold(hssfOriginFont.getBold());
return hssfFont;
}
return font;
}
public static RichTextString buildRichTextString(WriteWorkbookHolder writeWorkbookHolder,
RichTextStringData richTextStringData) {
if (richTextStringData == null) {
return null;
}
RichTextString richTextString;
if (writeWorkbookHolder.getExcelType() == ExcelTypeEnum.XLSX) {
richTextString = new XSSFRichTextString(richTextStringData.getTextString());
} else {
richTextString = new HSSFRichTextString(richTextStringData.getTextString());
}
if (richTextStringData.getWriteFont() != null) {
richTextString.applyFont(writeWorkbookHolder.createFont(richTextStringData.getWriteFont(), null, true));
}
if (CollectionUtils.isNotEmpty(richTextStringData.getIntervalFontList())) {
for (IntervalFont intervalFont : richTextStringData.getIntervalFontList()) {
richTextString.applyFont(intervalFont.getStartIndex(), intervalFont.getEndIndex(),
writeWorkbookHolder.createFont(intervalFont.getWriteFont(), null, true));
}
}
return richTextString;
}
public static HyperlinkType getHyperlinkType(HyperlinkData.HyperlinkType hyperlinkType) {
if (hyperlinkType == null) {
return HyperlinkType.NONE;
}
return hyperlinkType.getValue();
}
public static int getCoordinate(Integer coordinate) {
if (coordinate == null) {
return 0;
}
return Units.toEMU(coordinate);
}
public static int getCellCoordinate(Integer currentCoordinate, Integer absoluteCoordinate,
Integer relativeCoordinate) {
if (absoluteCoordinate != null && absoluteCoordinate > 0) {
return absoluteCoordinate;
}
if (relativeCoordinate != null) {
return currentCoordinate + relativeCoordinate;
}
return currentCoordinate;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/Validate.java
|
package ai.chat2db.excel.util;
import java.util.Objects;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Apache Software Foundation (ASF)
*/
public class Validate {
private static final String DEFAULT_IS_TRUE_EX_MESSAGE = "The validated expression is false";
private static final String DEFAULT_IS_NULL_EX_MESSAGE = "The validated object is null";
/**
* <p>Validate that the argument condition is {@code true}; otherwise
* throwing an exception with the specified message. This method is useful when
* validating according to an arbitrary boolean expression, such as validating a
* primitive number or using your own custom validation expression.</p>
*
* <pre>Validate.isTrue(i > 0.0, "The value must be greater than zero: %d", i);</pre>
*
* <p>For performance reasons, the long value is passed as a separate parameter and
* appended to the exception message only in the case of an error.</p>
*
* @param expression the boolean expression to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param value the value to append to the message when invalid
* @throws IllegalArgumentException if expression is {@code false}
* @see #isTrue(boolean)
* @see #isTrue(boolean, String, double)
* @see #isTrue(boolean, String, Object...)
*/
public static void isTrue(final boolean expression, final String message, final long value) {
if (!expression) {
throw new IllegalArgumentException(String.format(message, Long.valueOf(value)));
}
}
/**
* <p>Validate that the argument condition is {@code true}; otherwise
* throwing an exception with the specified message. This method is useful when
* validating according to an arbitrary boolean expression, such as validating a
* primitive number or using your own custom validation expression.</p>
*
* <pre>Validate.isTrue(d > 0.0, "The value must be greater than zero: %s", d);</pre>
*
* <p>For performance reasons, the double value is passed as a separate parameter and
* appended to the exception message only in the case of an error.</p>
*
* @param expression the boolean expression to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param value the value to append to the message when invalid
* @throws IllegalArgumentException if expression is {@code false}
* @see #isTrue(boolean)
* @see #isTrue(boolean, String, long)
* @see #isTrue(boolean, String, Object...)
*/
public static void isTrue(final boolean expression, final String message, final double value) {
if (!expression) {
throw new IllegalArgumentException(String.format(message, Double.valueOf(value)));
}
}
/**
* <p>Validate that the argument condition is {@code true}; otherwise
* throwing an exception with the specified message. This method is useful when
* validating according to an arbitrary boolean expression, such as validating a
* primitive number or using your own custom validation expression.</p>
*
* <pre>
* Validate.isTrue(i >= min && i <= max, "The value must be between %d and %d", min, max);
* Validate.isTrue(myObject.isOk(), "The object is not okay");</pre>
*
* @param expression the boolean expression to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message, null array not recommended
* @throws IllegalArgumentException if expression is {@code false}
* @see #isTrue(boolean)
* @see #isTrue(boolean, String, long)
* @see #isTrue(boolean, String, double)
*/
public static void isTrue(final boolean expression, final String message, final Object... values) {
if (!expression) {
throw new IllegalArgumentException(String.format(message, values));
}
}
/**
* <p>Validate that the argument condition is {@code true}; otherwise
* throwing an exception. This method is useful when validating according
* to an arbitrary boolean expression, such as validating a
* primitive number or using your own custom validation expression.</p>
*
* <pre>
* Validate.isTrue(i > 0);
* Validate.isTrue(myObject.isOk());</pre>
*
* <p>The message of the exception is "The validated expression is
* false".</p>
*
* @param expression the boolean expression to check
* @throws IllegalArgumentException if expression is {@code false}
* @see #isTrue(boolean, String, long)
* @see #isTrue(boolean, String, double)
* @see #isTrue(boolean, String, Object...)
*/
public static void isTrue(final boolean expression) {
if (!expression) {
throw new IllegalArgumentException(DEFAULT_IS_TRUE_EX_MESSAGE);
}
}
/**
* <p>Validate that the specified argument is not {@code null};
* otherwise throwing an exception.
*
* <pre>Validate.notNull(myObject, "The object must not be null");</pre>
*
* <p>The message of the exception is "The validated object is
* null".</p>
*
* @param <T> the object type
* @param object the object to check
* @return the validated object (never {@code null} for method chaining)
* @throws NullPointerException if the object is {@code null}
* @see #notNull(Object, String, Object...)
*/
public static <T> T notNull(final T object) {
return notNull(object, DEFAULT_IS_NULL_EX_MESSAGE);
}
/**
* <p>Validate that the specified argument is not {@code null};
* otherwise throwing an exception with the specified message.
*
* <pre>Validate.notNull(myObject, "The object must not be null");</pre>
*
* @param <T> the object type
* @param object the object to check
* @param message the {@link String#format(String, Object...)} exception message if invalid, not null
* @param values the optional values for the formatted exception message
* @return the validated object (never {@code null} for method chaining)
* @throws NullPointerException if the object is {@code null}
* @see #notNull(Object)
*/
public static <T> T notNull(final T object, final String message, final Object... values) {
return Objects.requireNonNull(object, () -> String.format(message, values));
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/WorkBookUtil.java
|
package ai.chat2db.excel.util;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import ai.chat2db.excel.metadata.csv.CsvWorkbook;
import ai.chat2db.excel.metadata.data.DataFormatData;
import ai.chat2db.excel.metadata.data.WriteCellData;
import ai.chat2db.excel.write.metadata.holder.WriteWorkbookHolder;
import ai.chat2db.excel.write.metadata.style.WriteCellStyle;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* @author jipengfei
*/
public class WorkBookUtil {
private WorkBookUtil() {}
public static void createWorkBook(WriteWorkbookHolder writeWorkbookHolder) throws IOException {
switch (writeWorkbookHolder.getExcelType()) {
case XLSX:
if (writeWorkbookHolder.getTempTemplateInputStream() != null) {
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(writeWorkbookHolder.getTempTemplateInputStream());
writeWorkbookHolder.setCachedWorkbook(xssfWorkbook);
if (writeWorkbookHolder.getInMemory()) {
writeWorkbookHolder.setWorkbook(xssfWorkbook);
} else {
writeWorkbookHolder.setWorkbook(new SXSSFWorkbook(xssfWorkbook));
}
return;
}
Workbook workbook;
if (writeWorkbookHolder.getInMemory()) {
workbook = new XSSFWorkbook();
} else {
workbook = new SXSSFWorkbook();
}
writeWorkbookHolder.setCachedWorkbook(workbook);
writeWorkbookHolder.setWorkbook(workbook);
return;
case XLS:
HSSFWorkbook hssfWorkbook;
if (writeWorkbookHolder.getTempTemplateInputStream() != null) {
hssfWorkbook = new HSSFWorkbook(
new POIFSFileSystem(writeWorkbookHolder.getTempTemplateInputStream()));
} else {
hssfWorkbook = new HSSFWorkbook();
}
writeWorkbookHolder.setCachedWorkbook(hssfWorkbook);
writeWorkbookHolder.setWorkbook(hssfWorkbook);
if (writeWorkbookHolder.getPassword() != null) {
Biff8EncryptionKey.setCurrentUserPassword(writeWorkbookHolder.getPassword());
hssfWorkbook.writeProtectWorkbook(writeWorkbookHolder.getPassword(), StringUtils.EMPTY);
}
return;
case CSV:
CsvWorkbook csvWorkbook = new CsvWorkbook(new PrintWriter(
new OutputStreamWriter(writeWorkbookHolder.getOutputStream(), writeWorkbookHolder.getCharset())),
writeWorkbookHolder.getGlobalConfiguration().getLocale(),
writeWorkbookHolder.getGlobalConfiguration().getUse1904windowing(),
writeWorkbookHolder.getGlobalConfiguration().getUseScientificFormat(),
writeWorkbookHolder.getCharset(),
writeWorkbookHolder.getWithBom());
writeWorkbookHolder.setCachedWorkbook(csvWorkbook);
writeWorkbookHolder.setWorkbook(csvWorkbook);
return;
default:
throw new UnsupportedOperationException("Wrong excel type.");
}
}
public static Sheet createSheet(Workbook workbook, String sheetName) {
return workbook.createSheet(sheetName);
}
public static Row createRow(Sheet sheet, int rowNum) {
return sheet.createRow(rowNum);
}
public static Cell createCell(Row row, int colNum) {
return row.createCell(colNum);
}
public static Cell createCell(Row row, int colNum, CellStyle cellStyle) {
Cell cell = row.createCell(colNum);
cell.setCellStyle(cellStyle);
return cell;
}
public static Cell createCell(Row row, int colNum, CellStyle cellStyle, String cellValue) {
Cell cell = createCell(row, colNum, cellStyle);
cell.setCellValue(cellValue);
return cell;
}
public static Cell createCell(Row row, int colNum, String cellValue) {
Cell cell = row.createCell(colNum);
cell.setCellValue(cellValue);
return cell;
}
public static void fillDataFormat(WriteCellData<?> cellData, String format, String defaultFormat) {
if (cellData.getWriteCellStyle() == null) {
cellData.setWriteCellStyle(new WriteCellStyle());
}
if (cellData.getWriteCellStyle().getDataFormatData() == null) {
cellData.getWriteCellStyle().setDataFormatData(new DataFormatData());
}
if (cellData.getWriteCellStyle().getDataFormatData().getFormat() == null) {
if (format == null) {
cellData.getWriteCellStyle().getDataFormatData().setFormat(defaultFormat);
} else {
cellData.getWriteCellStyle().getDataFormatData().setFormat(format);
}
}
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/util/WriteHandlerUtils.java
|
package ai.chat2db.excel.util;
import ai.chat2db.excel.write.handler.chain.CellHandlerExecutionChain;
import ai.chat2db.excel.write.handler.chain.RowHandlerExecutionChain;
import ai.chat2db.excel.write.handler.chain.SheetHandlerExecutionChain;
import ai.chat2db.excel.write.handler.chain.WorkbookHandlerExecutionChain;
import ai.chat2db.excel.write.handler.context.CellWriteHandlerContext;
import ai.chat2db.excel.write.handler.context.RowWriteHandlerContext;
import ai.chat2db.excel.write.handler.context.SheetWriteHandlerContext;
import ai.chat2db.excel.write.handler.context.WorkbookWriteHandlerContext;
import ai.chat2db.excel.context.WriteContext;
import ai.chat2db.excel.metadata.Head;
import ai.chat2db.excel.metadata.property.ExcelContentProperty;
import ai.chat2db.excel.write.metadata.holder.AbstractWriteHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
/**
* Write handler utils
*
* @author Jiaju Zhuang
*/
@Slf4j
public class WriteHandlerUtils {
private WriteHandlerUtils() {}
public static WorkbookWriteHandlerContext createWorkbookWriteHandlerContext(WriteContext writeContext) {
WorkbookWriteHandlerContext context = new WorkbookWriteHandlerContext(writeContext,
writeContext.writeWorkbookHolder());
writeContext.writeWorkbookHolder().setWorkbookWriteHandlerContext(context);
return context;
}
public static void beforeWorkbookCreate(WorkbookWriteHandlerContext context) {
beforeWorkbookCreate(context, false);
}
public static void beforeWorkbookCreate(WorkbookWriteHandlerContext context, boolean runOwn) {
WorkbookHandlerExecutionChain workbookHandlerExecutionChain = getWorkbookHandlerExecutionChain(context, runOwn);
if (workbookHandlerExecutionChain != null) {
workbookHandlerExecutionChain.beforeWorkbookCreate(context);
}
}
public static void afterWorkbookCreate(WorkbookWriteHandlerContext context) {
afterWorkbookCreate(context, false);
}
public static void afterWorkbookCreate(WorkbookWriteHandlerContext context, boolean runOwn) {
WorkbookHandlerExecutionChain workbookHandlerExecutionChain = getWorkbookHandlerExecutionChain(context, runOwn);
if (workbookHandlerExecutionChain != null) {
workbookHandlerExecutionChain.afterWorkbookCreate(context);
}
}
private static WorkbookHandlerExecutionChain getWorkbookHandlerExecutionChain(WorkbookWriteHandlerContext context,
boolean runOwn) {
AbstractWriteHolder abstractWriteHolder = (AbstractWriteHolder)context.getWriteContext().currentWriteHolder();
if (runOwn) {
return abstractWriteHolder.getOwnWorkbookHandlerExecutionChain();
} else {
return abstractWriteHolder.getWorkbookHandlerExecutionChain();
}
}
public static void afterWorkbookDispose(WorkbookWriteHandlerContext context) {
WorkbookHandlerExecutionChain workbookHandlerExecutionChain = getWorkbookHandlerExecutionChain(context, false);
if (workbookHandlerExecutionChain != null) {
workbookHandlerExecutionChain.afterWorkbookDispose(context);
}
}
public static SheetWriteHandlerContext createSheetWriteHandlerContext(WriteContext writeContext) {
return new SheetWriteHandlerContext(writeContext, writeContext.writeWorkbookHolder(),
writeContext.writeSheetHolder());
}
public static void beforeSheetCreate(SheetWriteHandlerContext context) {
beforeSheetCreate(context, false);
}
public static void beforeSheetCreate(SheetWriteHandlerContext context, boolean runOwn) {
SheetHandlerExecutionChain sheetHandlerExecutionChain = getSheetHandlerExecutionChain(context, runOwn);
if (sheetHandlerExecutionChain != null) {
sheetHandlerExecutionChain.beforeSheetCreate(context);
}
}
public static void afterSheetCreate(SheetWriteHandlerContext context) {
afterSheetCreate(context, false);
}
public static void afterSheetCreate(SheetWriteHandlerContext context, boolean runOwn) {
SheetHandlerExecutionChain sheetHandlerExecutionChain = getSheetHandlerExecutionChain(context, runOwn);
if (sheetHandlerExecutionChain != null) {
sheetHandlerExecutionChain.afterSheetCreate(context);
}
}
private static SheetHandlerExecutionChain getSheetHandlerExecutionChain(SheetWriteHandlerContext context,
boolean runOwn) {
AbstractWriteHolder abstractWriteHolder = (AbstractWriteHolder)context.getWriteContext().currentWriteHolder();
if (runOwn) {
return abstractWriteHolder.getOwnSheetHandlerExecutionChain();
} else {
return abstractWriteHolder.getSheetHandlerExecutionChain();
}
}
public static CellWriteHandlerContext createCellWriteHandlerContext(WriteContext writeContext, Row row,
Integer rowIndex, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead,
ExcelContentProperty excelContentProperty) {
return new CellWriteHandlerContext(writeContext, writeContext.writeWorkbookHolder(),
writeContext.writeSheetHolder(), writeContext.writeTableHolder(), row, rowIndex, null, columnIndex,
relativeRowIndex, head, null, null, isHead, excelContentProperty);
}
public static void beforeCellCreate(CellWriteHandlerContext context) {
CellHandlerExecutionChain cellHandlerExecutionChain = ((AbstractWriteHolder)context.getWriteContext()
.currentWriteHolder()).getCellHandlerExecutionChain();
if (cellHandlerExecutionChain != null) {
cellHandlerExecutionChain.beforeCellCreate(context);
}
}
public static void afterCellCreate(CellWriteHandlerContext context) {
CellHandlerExecutionChain cellHandlerExecutionChain = ((AbstractWriteHolder)context.getWriteContext()
.currentWriteHolder()).getCellHandlerExecutionChain();
if (cellHandlerExecutionChain != null) {
cellHandlerExecutionChain.afterCellCreate(context);
}
}
public static void afterCellDataConverted(CellWriteHandlerContext context) {
CellHandlerExecutionChain cellHandlerExecutionChain = ((AbstractWriteHolder)context.getWriteContext()
.currentWriteHolder()).getCellHandlerExecutionChain();
if (cellHandlerExecutionChain != null) {
cellHandlerExecutionChain.afterCellDataConverted(context);
}
}
public static void afterCellDispose(CellWriteHandlerContext context) {
CellHandlerExecutionChain cellHandlerExecutionChain = ((AbstractWriteHolder)context.getWriteContext()
.currentWriteHolder()).getCellHandlerExecutionChain();
if (cellHandlerExecutionChain != null) {
cellHandlerExecutionChain.afterCellDispose(context);
}
}
public static RowWriteHandlerContext createRowWriteHandlerContext(WriteContext writeContext, Integer rowIndex,
Integer relativeRowIndex, Boolean isHead) {
return new RowWriteHandlerContext(writeContext, writeContext.writeWorkbookHolder(),
writeContext.writeSheetHolder(), writeContext.writeTableHolder(), rowIndex, null, relativeRowIndex, isHead);
}
public static void beforeRowCreate(RowWriteHandlerContext context) {
RowHandlerExecutionChain rowHandlerExecutionChain = ((AbstractWriteHolder)context.getWriteContext()
.currentWriteHolder()).getRowHandlerExecutionChain();
if (rowHandlerExecutionChain != null) {
rowHandlerExecutionChain.beforeRowCreate(context);
}
}
public static void afterRowCreate(RowWriteHandlerContext context) {
RowHandlerExecutionChain rowHandlerExecutionChain = ((AbstractWriteHolder)context.getWriteContext()
.currentWriteHolder()).getRowHandlerExecutionChain();
if (rowHandlerExecutionChain != null) {
rowHandlerExecutionChain.afterRowCreate(context);
}
}
public static void afterRowDispose(RowWriteHandlerContext context) {
RowHandlerExecutionChain rowHandlerExecutionChain = ((AbstractWriteHolder)context.getWriteContext()
.currentWriteHolder()).getRowHandlerExecutionChain();
if (rowHandlerExecutionChain != null) {
rowHandlerExecutionChain.afterRowDispose(context);
}
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/ExcelBuilder.java
|
package ai.chat2db.excel.write;
import java.util.Collection;
import ai.chat2db.excel.context.WriteContext;
import ai.chat2db.excel.write.merge.OnceAbsoluteMergeStrategy;
import ai.chat2db.excel.write.metadata.WriteSheet;
import ai.chat2db.excel.write.metadata.WriteTable;
import ai.chat2db.excel.write.metadata.fill.FillConfig;
/**
* @author jipengfei
*/
public interface ExcelBuilder {
/**
* WorkBook increase value
*
* @param data
* java basic type or java model extend BaseModel
* @param writeSheet
* Write the sheet
* @deprecated please use{@link ExcelBuilder#addContent(Collection, WriteSheet, WriteTable)}
*/
@Deprecated
void addContent(Collection<?> data, WriteSheet writeSheet);
/**
* WorkBook increase value
*
* @param data
* java basic type or java model extend BaseModel
* @param writeSheet
* Write the sheet
* @param writeTable
* Write the table
*/
void addContent(Collection<?> data, WriteSheet writeSheet, WriteTable writeTable);
/**
* WorkBook fill value
*
* @param data
* @param fillConfig
* @param writeSheet
*/
void fill(Object data, FillConfig fillConfig, WriteSheet writeSheet);
/**
* Creates new cell range. Indexes are zero-based.
*
* @param firstRow
* Index of first row
* @param lastRow
* Index of last row (inclusive), must be equal to or larger than {@code firstRow}
* @param firstCol
* Index of first column
* @param lastCol
* Index of last column (inclusive), must be equal to or larger than {@code firstCol}
* @deprecated please use{@link OnceAbsoluteMergeStrategy}
*/
@Deprecated
void merge(int firstRow, int lastRow, int firstCol, int lastCol);
/**
* Gets the written data
*
* @return
*/
WriteContext writeContext();
/**
* Close io
*
* @param onException
*/
void finish(boolean onException);
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/ExcelBuilderImpl.java
|
package ai.chat2db.excel.write;
import java.util.Collection;
import ai.chat2db.excel.context.WriteContext;
import ai.chat2db.excel.context.WriteContextImpl;
import ai.chat2db.excel.enums.WriteTypeEnum;
import ai.chat2db.excel.exception.ExcelGenerateException;
import ai.chat2db.excel.support.ExcelTypeEnum;
import ai.chat2db.excel.util.FileUtils;
import ai.chat2db.excel.write.executor.ExcelWriteAddExecutor;
import ai.chat2db.excel.write.executor.ExcelWriteFillExecutor;
import ai.chat2db.excel.write.metadata.WriteSheet;
import ai.chat2db.excel.write.metadata.WriteTable;
import ai.chat2db.excel.write.metadata.WriteWorkbook;
import ai.chat2db.excel.write.metadata.fill.FillConfig;
import org.apache.poi.ss.util.CellRangeAddress;
/**
* @author jipengfei
*/
public class ExcelBuilderImpl implements ExcelBuilder {
private final WriteContext context;
private ExcelWriteFillExecutor excelWriteFillExecutor;
private ExcelWriteAddExecutor excelWriteAddExecutor;
static {
// Create temporary cache directory at initialization time to avoid POI concurrent write bugs
FileUtils.createPoiFilesDirectory();
}
public ExcelBuilderImpl(WriteWorkbook writeWorkbook) {
try {
context = new WriteContextImpl(writeWorkbook);
} catch (RuntimeException e) {
finishOnException();
throw e;
} catch (Throwable e) {
finishOnException();
throw new ExcelGenerateException(e);
}
}
@Override
public void addContent(Collection<?> data, WriteSheet writeSheet) {
addContent(data, writeSheet, null);
}
@Override
public void addContent(Collection<?> data, WriteSheet writeSheet, WriteTable writeTable) {
try {
context.currentSheet(writeSheet, WriteTypeEnum.ADD);
context.currentTable(writeTable);
if (excelWriteAddExecutor == null) {
excelWriteAddExecutor = new ExcelWriteAddExecutor(context);
}
excelWriteAddExecutor.add(data);
} catch (RuntimeException e) {
finishOnException();
throw e;
} catch (Throwable e) {
finishOnException();
throw new ExcelGenerateException(e);
}
}
@Override
public void fill(Object data, FillConfig fillConfig, WriteSheet writeSheet) {
try {
if (context.writeWorkbookHolder().getTempTemplateInputStream() == null) {
throw new ExcelGenerateException("Calling the 'fill' method must use a template.");
}
if (context.writeWorkbookHolder().getExcelType() == ExcelTypeEnum.CSV) {
throw new ExcelGenerateException("csv does not support filling data.");
}
context.currentSheet(writeSheet, WriteTypeEnum.FILL);
if (excelWriteFillExecutor == null) {
excelWriteFillExecutor = new ExcelWriteFillExecutor(context);
}
excelWriteFillExecutor.fill(data, fillConfig);
} catch (RuntimeException e) {
finishOnException();
throw e;
} catch (Throwable e) {
finishOnException();
throw new ExcelGenerateException(e);
}
}
private void finishOnException() {
finish(true);
}
@Override
public void finish(boolean onException) {
if (context != null) {
context.finish(onException);
}
}
@Override
public void merge(int firstRow, int lastRow, int firstCol, int lastCol) {
CellRangeAddress cra = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
context.writeSheetHolder().getSheet().addMergedRegion(cra);
}
@Override
public WriteContext writeContext() {
return context;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/builder/AbstractExcelWriterParameterBuilder.java
|
package ai.chat2db.excel.write.builder;
import java.util.ArrayList;
import java.util.Collection;
import ai.chat2db.excel.write.handler.WriteHandler;
import ai.chat2db.excel.metadata.AbstractParameterBuilder;
import ai.chat2db.excel.write.metadata.WriteBasicParameter;
/**
* Build ExcelBuilder
*
* @author Jiaju Zhuang
*/
public abstract class AbstractExcelWriterParameterBuilder<T extends AbstractExcelWriterParameterBuilder,
C extends WriteBasicParameter> extends AbstractParameterBuilder<T, C> {
/**
* Writes the head relative to the existing contents of the sheet. Indexes are zero-based.
*
* @param relativeHeadRowIndex
* @return
*/
public T relativeHeadRowIndex(Integer relativeHeadRowIndex) {
parameter().setRelativeHeadRowIndex(relativeHeadRowIndex);
return self();
}
/**
* Need Head
*/
public T needHead(Boolean needHead) {
parameter().setNeedHead(needHead);
return self();
}
/**
* Custom write handler
*
* @param writeHandler
* @return
*/
public T registerWriteHandler(WriteHandler writeHandler) {
if (parameter().getCustomWriteHandlerList() == null) {
parameter().setCustomWriteHandlerList(new ArrayList<WriteHandler>());
}
parameter().getCustomWriteHandlerList().add(writeHandler);
return self();
}
/**
* Use the default style.Default is true.
*
* @param useDefaultStyle
* @return
*/
public T useDefaultStyle(Boolean useDefaultStyle) {
parameter().setUseDefaultStyle(useDefaultStyle);
return self();
}
/**
* Whether to automatically merge headers.Default is true.
*
* @param automaticMergeHead
* @return
*/
public T automaticMergeHead(Boolean automaticMergeHead) {
parameter().setAutomaticMergeHead(automaticMergeHead);
return self();
}
/**
* Ignore the custom columns.
*/
public T excludeColumnIndexes(Collection<Integer> excludeColumnIndexes) {
parameter().setExcludeColumnIndexes(excludeColumnIndexes);
return self();
}
/**
* Ignore the custom columns.
*
* @deprecated use {@link #excludeColumnFieldNames(Collection)}
*/
public T excludeColumnFiledNames(Collection<String> excludeColumnFieldNames) {
parameter().setExcludeColumnFieldNames(excludeColumnFieldNames);
return self();
}
/**
* Ignore the custom columns.
*/
public T excludeColumnFieldNames(Collection<String> excludeColumnFieldNames) {
parameter().setExcludeColumnFieldNames(excludeColumnFieldNames);
return self();
}
/**
* Only output the custom columns.
*/
public T includeColumnIndexes(Collection<Integer> includeColumnIndexes) {
parameter().setIncludeColumnIndexes(includeColumnIndexes);
return self();
}
/**
* Only output the custom columns.
*
* @deprecated use {@link #includeColumnFieldNames(Collection)} spelling mistake
*/
@Deprecated
public T includeColumnFiledNames(Collection<String> includeColumnFieldNames) {
parameter().setIncludeColumnFieldNames(includeColumnFieldNames);
return self();
}
/**
* Only output the custom columns.
*/
public T includeColumnFieldNames(Collection<String> includeColumnFieldNames) {
parameter().setIncludeColumnFieldNames(includeColumnFieldNames);
return self();
}
/**
* Data will be order by {@link #includeColumnFieldNames} or {@link #includeColumnIndexes}.
*
* default is false.
*
* @since 3.3.0
**/
public T orderByIncludeColumn(Boolean orderByIncludeColumn) {
parameter().setOrderByIncludeColumn(orderByIncludeColumn);
return self();
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/builder/ExcelWriterBuilder.java
|
package ai.chat2db.excel.write.builder;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import ai.chat2db.excel.ExcelWriter;
import ai.chat2db.excel.support.ExcelTypeEnum;
import ai.chat2db.excel.write.metadata.WriteWorkbook;
/**
* Build ExcelBuilder
*
* @author Jiaju Zhuang
*/
public class ExcelWriterBuilder extends AbstractExcelWriterParameterBuilder<ExcelWriterBuilder, WriteWorkbook> {
/**
* Workbook
*/
private final WriteWorkbook writeWorkbook;
public ExcelWriterBuilder() {
this.writeWorkbook = new WriteWorkbook();
}
/**
* Default true
*
* @param autoCloseStream
* @return
*/
public ExcelWriterBuilder autoCloseStream(Boolean autoCloseStream) {
writeWorkbook.setAutoCloseStream(autoCloseStream);
return this;
}
/**
* Whether the encryption.
* <p>
* WARRING:Encryption is when the entire file is read into memory, so it is very memory intensive.
*
* @param password
* @return
*/
public ExcelWriterBuilder password(String password) {
writeWorkbook.setPassword(password);
return this;
}
/**
* Write excel in memory. Default false, the cache file is created and finally written to excel.
* <p>
* Comment and RichTextString are only supported in memory mode.
*/
public ExcelWriterBuilder inMemory(Boolean inMemory) {
writeWorkbook.setInMemory(inMemory);
return this;
}
/**
* Excel is also written in the event of an exception being thrown.The default false.
*/
public ExcelWriterBuilder writeExcelOnException(Boolean writeExcelOnException) {
writeWorkbook.setWriteExcelOnException(writeExcelOnException);
return this;
}
public ExcelWriterBuilder excelType(ExcelTypeEnum excelType) {
writeWorkbook.setExcelType(excelType);
return this;
}
public ExcelWriterBuilder file(OutputStream outputStream) {
writeWorkbook.setOutputStream(outputStream);
return this;
}
public ExcelWriterBuilder file(File outputFile) {
writeWorkbook.setFile(outputFile);
return this;
}
public ExcelWriterBuilder file(String outputPathName) {
return file(new File(outputPathName));
}
/**
* charset.
* Only work on the CSV file
*/
public ExcelWriterBuilder charset(Charset charset) {
writeWorkbook.setCharset(charset);
return this;
}
/**
* Set the encoding prefix in the csv file, otherwise the office may open garbled characters.
* Default true.
*/
public ExcelWriterBuilder withBom(Boolean withBom) {
writeWorkbook.setWithBom(withBom);
return this;
}
/**
* Template file.
* This file is read into memory, excessive cases can lead to OOM.
*/
public ExcelWriterBuilder withTemplate(InputStream templateInputStream) {
writeWorkbook.setTemplateInputStream(templateInputStream);
return this;
}
/**
* Template file.
* This file is read into memory, excessive cases can lead to OOM.
*/
public ExcelWriterBuilder withTemplate(File templateFile) {
writeWorkbook.setTemplateFile(templateFile);
return this;
}
/**
* Template file.
* This file is read into memory, excessive cases can lead to OOM.
*/
public ExcelWriterBuilder withTemplate(String pathName) {
return withTemplate(new File(pathName));
}
public ExcelWriter build() {
return new ExcelWriter(writeWorkbook);
}
public ExcelWriterSheetBuilder sheet() {
return sheet(null, null);
}
public ExcelWriterSheetBuilder sheet(Integer sheetNo) {
return sheet(sheetNo, null);
}
public ExcelWriterSheetBuilder sheet(String sheetName) {
return sheet(null, sheetName);
}
public ExcelWriterSheetBuilder sheet(Integer sheetNo, String sheetName) {
ExcelWriter excelWriter = build();
ExcelWriterSheetBuilder excelWriterSheetBuilder = new ExcelWriterSheetBuilder(excelWriter);
if (sheetNo != null) {
excelWriterSheetBuilder.sheetNo(sheetNo);
}
if (sheetName != null) {
excelWriterSheetBuilder.sheetName(sheetName);
}
return excelWriterSheetBuilder;
}
@Override
protected WriteWorkbook parameter() {
return writeWorkbook;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/builder/ExcelWriterSheetBuilder.java
|
package ai.chat2db.excel.write.builder;
import java.util.Collection;
import java.util.function.Supplier;
import ai.chat2db.excel.ExcelWriter;
import ai.chat2db.excel.exception.ExcelGenerateException;
import ai.chat2db.excel.write.metadata.WriteSheet;
import ai.chat2db.excel.write.metadata.fill.FillConfig;
/**
* Build sheet
*
* @author Jiaju Zhuang
*/
public class ExcelWriterSheetBuilder extends AbstractExcelWriterParameterBuilder<ExcelWriterSheetBuilder, WriteSheet> {
private ExcelWriter excelWriter;
/**
* Sheet
*/
private final WriteSheet writeSheet;
public ExcelWriterSheetBuilder() {
this.writeSheet = new WriteSheet();
}
public ExcelWriterSheetBuilder(ExcelWriter excelWriter) {
this.writeSheet = new WriteSheet();
this.excelWriter = excelWriter;
}
/**
* Starting from 0
*
* @param sheetNo
* @return
*/
public ExcelWriterSheetBuilder sheetNo(Integer sheetNo) {
writeSheet.setSheetNo(sheetNo);
return this;
}
/**
* sheet name
*
* @param sheetName
* @return
*/
public ExcelWriterSheetBuilder sheetName(String sheetName) {
writeSheet.setSheetName(sheetName);
return this;
}
public WriteSheet build() {
return writeSheet;
}
public void doWrite(Collection<?> data) {
if (excelWriter == null) {
throw new ExcelGenerateException("Must use 'EasyExcelFactory.write().sheet()' to call this method");
}
excelWriter.write(data, build());
excelWriter.finish();
}
public void doFill(Object data) {
doFill(data, null);
}
public void doFill(Object data, FillConfig fillConfig) {
if (excelWriter == null) {
throw new ExcelGenerateException("Must use 'EasyExcelFactory.write().sheet()' to call this method");
}
excelWriter.fill(data, fillConfig, build());
excelWriter.finish();
}
public void doWrite(Supplier<Collection<?>> supplier) {
doWrite(supplier.get());
}
public void doFill(Supplier<Object> supplier) {
doFill(supplier.get());
}
public void doFill(Supplier<Object> supplier, FillConfig fillConfig) {
doFill(supplier.get(), fillConfig);
}
public ExcelWriterTableBuilder table() {
return table(null);
}
public ExcelWriterTableBuilder table(Integer tableNo) {
ExcelWriterTableBuilder excelWriterTableBuilder = new ExcelWriterTableBuilder(excelWriter, build());
if (tableNo != null) {
excelWriterTableBuilder.tableNo(tableNo);
}
return excelWriterTableBuilder;
}
@Override
protected WriteSheet parameter() {
return writeSheet;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/builder/ExcelWriterTableBuilder.java
|
package ai.chat2db.excel.write.builder;
import java.util.Collection;
import java.util.function.Supplier;
import ai.chat2db.excel.ExcelWriter;
import ai.chat2db.excel.exception.ExcelGenerateException;
import ai.chat2db.excel.write.metadata.WriteSheet;
import ai.chat2db.excel.write.metadata.WriteTable;
/**
* Build sheet
*
* @author Jiaju Zhuang
*/
public class ExcelWriterTableBuilder extends AbstractExcelWriterParameterBuilder<ExcelWriterTableBuilder, WriteTable> {
private ExcelWriter excelWriter;
private WriteSheet writeSheet;
/**
* table
*/
private final WriteTable writeTable;
public ExcelWriterTableBuilder() {
this.writeTable = new WriteTable();
}
public ExcelWriterTableBuilder(ExcelWriter excelWriter, WriteSheet writeSheet) {
this.excelWriter = excelWriter;
this.writeSheet = writeSheet;
this.writeTable = new WriteTable();
}
/**
* Starting from 0
*
* @param tableNo
* @return
*/
public ExcelWriterTableBuilder tableNo(Integer tableNo) {
writeTable.setTableNo(tableNo);
return this;
}
public WriteTable build() {
return writeTable;
}
public void doWrite(Collection<?> data) {
if (excelWriter == null) {
throw new ExcelGenerateException("Must use 'EasyExcelFactory.write().sheet().table()' to call this method");
}
excelWriter.write(data, writeSheet, build());
excelWriter.finish();
}
public void doWrite(Supplier<Collection<?>> supplier) {
doWrite(supplier.get());
}
@Override
protected WriteTable parameter() {
return writeTable;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/executor/AbstractExcelWriteExecutor.java
|
package ai.chat2db.excel.write.executor;
import java.util.List;
import ai.chat2db.excel.context.WriteContext;
import ai.chat2db.excel.converters.Converter;
import ai.chat2db.excel.converters.ConverterKeyBuild;
import ai.chat2db.excel.converters.NullableObjectConverter;
import ai.chat2db.excel.converters.WriteConverterContext;
import ai.chat2db.excel.enums.CellDataTypeEnum;
import ai.chat2db.excel.exception.ExcelWriteDataConvertException;
import ai.chat2db.excel.metadata.data.CommentData;
import ai.chat2db.excel.metadata.data.FormulaData;
import ai.chat2db.excel.metadata.data.HyperlinkData;
import ai.chat2db.excel.metadata.data.ImageData;
import ai.chat2db.excel.metadata.data.WriteCellData;
import ai.chat2db.excel.metadata.property.ExcelContentProperty;
import ai.chat2db.excel.support.ExcelTypeEnum;
import ai.chat2db.excel.util.DateUtils;
import ai.chat2db.excel.util.FileTypeUtils;
import ai.chat2db.excel.util.ListUtils;
import ai.chat2db.excel.util.StyleUtil;
import ai.chat2db.excel.util.WorkBookUtil;
import ai.chat2db.excel.util.WriteHandlerUtils;
import ai.chat2db.excel.write.handler.context.CellWriteHandlerContext;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
/**
* Excel write Executor
*
* @author Jiaju Zhuang
*/
public abstract class AbstractExcelWriteExecutor implements ExcelWriteExecutor {
protected WriteContext writeContext;
public AbstractExcelWriteExecutor(WriteContext writeContext) {
this.writeContext = writeContext;
}
/**
* Transform the data and then to set into the cell
*
* @param cellWriteHandlerContext context
*/
protected void converterAndSet(CellWriteHandlerContext cellWriteHandlerContext) {
WriteCellData<?> cellData = convert(cellWriteHandlerContext);
cellWriteHandlerContext.setCellDataList(ListUtils.newArrayList(cellData));
cellWriteHandlerContext.setFirstCellData(cellData);
WriteHandlerUtils.afterCellDataConverted(cellWriteHandlerContext);
// Fill in picture information
fillImage(cellWriteHandlerContext, cellData.getImageDataList());
// Fill in comment information
fillComment(cellWriteHandlerContext, cellData.getCommentData());
// Fill in hyper link information
fillHyperLink(cellWriteHandlerContext, cellData.getHyperlinkData());
// Fill in formula information
fillFormula(cellWriteHandlerContext, cellData.getFormulaData());
// Fill index
cellData.setRowIndex(cellWriteHandlerContext.getRowIndex());
cellData.setColumnIndex(cellWriteHandlerContext.getColumnIndex());
if (cellData.getType() == null) {
cellData.setType(CellDataTypeEnum.EMPTY);
}
Cell cell = cellWriteHandlerContext.getCell();
switch (cellData.getType()) {
case STRING:
cell.setCellValue(cellData.getStringValue());
return;
case BOOLEAN:
cell.setCellValue(cellData.getBooleanValue());
return;
case NUMBER:
cell.setCellValue(cellData.getNumberValue().doubleValue());
return;
case DATE:
cell.setCellValue(cellData.getDateValue());
return;
case RICH_TEXT_STRING:
cell.setCellValue(StyleUtil
.buildRichTextString(writeContext.writeWorkbookHolder(), cellData.getRichTextStringDataValue()));
return;
case EMPTY:
return;
default:
throw new ExcelWriteDataConvertException(cellWriteHandlerContext,
"Not supported data:" + cellWriteHandlerContext.getOriginalValue() + " return type:"
+ cellData.getType()
+ "at row:" + cellWriteHandlerContext.getRowIndex());
}
}
private void fillFormula(CellWriteHandlerContext cellWriteHandlerContext, FormulaData formulaData) {
if (formulaData == null) {
return;
}
Cell cell = cellWriteHandlerContext.getCell();
if (formulaData.getFormulaValue() != null) {
cell.setCellFormula(formulaData.getFormulaValue());
}
}
private void fillHyperLink(CellWriteHandlerContext cellWriteHandlerContext, HyperlinkData hyperlinkData) {
if (hyperlinkData == null) {
return;
}
Integer rowIndex = cellWriteHandlerContext.getRowIndex();
Integer columnIndex = cellWriteHandlerContext.getColumnIndex();
Workbook workbook = cellWriteHandlerContext.getWriteWorkbookHolder().getWorkbook();
Cell cell = cellWriteHandlerContext.getCell();
CreationHelper helper = workbook.getCreationHelper();
Hyperlink hyperlink = helper.createHyperlink(StyleUtil.getHyperlinkType(hyperlinkData.getHyperlinkType()));
hyperlink.setAddress(hyperlinkData.getAddress());
hyperlink.setFirstRow(StyleUtil.getCellCoordinate(rowIndex, hyperlinkData.getFirstRowIndex(),
hyperlinkData.getRelativeFirstRowIndex()));
hyperlink.setFirstColumn(StyleUtil.getCellCoordinate(columnIndex, hyperlinkData.getFirstColumnIndex(),
hyperlinkData.getRelativeFirstColumnIndex()));
hyperlink.setLastRow(StyleUtil.getCellCoordinate(rowIndex, hyperlinkData.getLastRowIndex(),
hyperlinkData.getRelativeLastRowIndex()));
hyperlink.setLastColumn(StyleUtil.getCellCoordinate(columnIndex, hyperlinkData.getLastColumnIndex(),
hyperlinkData.getRelativeLastColumnIndex()));
cell.setHyperlink(hyperlink);
}
private void fillComment(CellWriteHandlerContext cellWriteHandlerContext, CommentData commentData) {
if (commentData == null) {
return;
}
ClientAnchor anchor;
Integer rowIndex = cellWriteHandlerContext.getRowIndex();
Integer columnIndex = cellWriteHandlerContext.getColumnIndex();
Sheet sheet = cellWriteHandlerContext.getWriteSheetHolder().getSheet();
Cell cell = cellWriteHandlerContext.getCell();
if (writeContext.writeWorkbookHolder().getExcelType() == ExcelTypeEnum.XLSX) {
anchor = new XSSFClientAnchor(StyleUtil.getCoordinate(commentData.getLeft()),
StyleUtil.getCoordinate(commentData.getTop()),
StyleUtil.getCoordinate(commentData.getRight()),
StyleUtil.getCoordinate(commentData.getBottom()),
StyleUtil.getCellCoordinate(columnIndex, commentData.getFirstColumnIndex(),
commentData.getRelativeFirstColumnIndex()),
StyleUtil.getCellCoordinate(rowIndex, commentData.getFirstRowIndex(),
commentData.getRelativeFirstRowIndex()),
StyleUtil.getCellCoordinate(columnIndex, commentData.getLastColumnIndex(),
commentData.getRelativeLastColumnIndex()) + 1,
StyleUtil.getCellCoordinate(rowIndex, commentData.getLastRowIndex(),
commentData.getRelativeLastRowIndex()) + 1);
} else {
anchor = new HSSFClientAnchor(StyleUtil.getCoordinate(commentData.getLeft()),
StyleUtil.getCoordinate(commentData.getTop()),
StyleUtil.getCoordinate(commentData.getRight()),
StyleUtil.getCoordinate(commentData.getBottom()),
(short)StyleUtil.getCellCoordinate(columnIndex, commentData.getFirstColumnIndex(),
commentData.getRelativeFirstColumnIndex()),
StyleUtil.getCellCoordinate(rowIndex, commentData.getFirstRowIndex(),
commentData.getRelativeFirstRowIndex()),
(short)(StyleUtil.getCellCoordinate(columnIndex, commentData.getLastColumnIndex(),
commentData.getRelativeLastColumnIndex()) + 1),
StyleUtil.getCellCoordinate(rowIndex, commentData.getLastRowIndex(),
commentData.getRelativeLastRowIndex()) + 1);
}
Comment comment = sheet.createDrawingPatriarch().createCellComment(anchor);
if (commentData.getRichTextStringData() != null) {
comment.setString(
StyleUtil.buildRichTextString(writeContext.writeWorkbookHolder(), commentData.getRichTextStringData()));
}
if (commentData.getAuthor() != null) {
comment.setAuthor(commentData.getAuthor());
}
cell.setCellComment(comment);
}
protected void fillImage(CellWriteHandlerContext cellWriteHandlerContext, List<ImageData> imageDataList) {
if (CollectionUtils.isEmpty(imageDataList)) {
return;
}
Integer rowIndex = cellWriteHandlerContext.getRowIndex();
Integer columnIndex = cellWriteHandlerContext.getColumnIndex();
Sheet sheet = cellWriteHandlerContext.getWriteSheetHolder().getSheet();
Workbook workbook = cellWriteHandlerContext.getWriteWorkbookHolder().getWorkbook();
Drawing<?> drawing = sheet.getDrawingPatriarch();
if (drawing == null) {
drawing = sheet.createDrawingPatriarch();
}
CreationHelper helper = sheet.getWorkbook().getCreationHelper();
for (ImageData imageData : imageDataList) {
int index = workbook.addPicture(imageData.getImage(),
FileTypeUtils.getImageTypeFormat(imageData.getImage()));
ClientAnchor anchor = helper.createClientAnchor();
if (imageData.getTop() != null) {
anchor.setDy1(StyleUtil.getCoordinate(imageData.getTop()));
}
if (imageData.getRight() != null) {
anchor.setDx2(-StyleUtil.getCoordinate(imageData.getRight()));
}
if (imageData.getBottom() != null) {
anchor.setDy2(-StyleUtil.getCoordinate(imageData.getBottom()));
}
if (imageData.getLeft() != null) {
anchor.setDx1(StyleUtil.getCoordinate(imageData.getLeft()));
}
anchor.setRow1(StyleUtil.getCellCoordinate(rowIndex, imageData.getFirstRowIndex(),
imageData.getRelativeFirstRowIndex()));
anchor.setCol1(StyleUtil.getCellCoordinate(columnIndex, imageData.getFirstColumnIndex(),
imageData.getRelativeFirstColumnIndex()));
anchor.setRow2(StyleUtil.getCellCoordinate(rowIndex, imageData.getLastRowIndex(),
imageData.getRelativeLastRowIndex()) + 1);
anchor.setCol2(StyleUtil.getCellCoordinate(columnIndex, imageData.getLastColumnIndex(),
imageData.getRelativeLastColumnIndex()) + 1);
if (imageData.getAnchorType() != null) {
anchor.setAnchorType(imageData.getAnchorType().getValue());
}
drawing.createPicture(anchor, index);
}
}
protected WriteCellData<?> convert(CellWriteHandlerContext cellWriteHandlerContext) {
// This means that the user has defined the data.
if (cellWriteHandlerContext.getOriginalFieldClass() == WriteCellData.class) {
if (cellWriteHandlerContext.getOriginalValue() == null) {
return new WriteCellData<>(CellDataTypeEnum.EMPTY);
}
WriteCellData<?> cellDataValue = (WriteCellData<?>)cellWriteHandlerContext.getOriginalValue();
if (cellDataValue.getType() != null) {
// Configuration information may not be read here
fillProperty(cellDataValue, cellWriteHandlerContext.getExcelContentProperty());
return cellDataValue;
} else {
if (cellDataValue.getData() == null) {
cellDataValue.setType(CellDataTypeEnum.EMPTY);
return cellDataValue;
}
}
WriteCellData<?> cellDataReturn = doConvert(cellWriteHandlerContext);
if (cellDataValue.getImageDataList() != null) {
cellDataReturn.setImageDataList(cellDataValue.getImageDataList());
}
if (cellDataValue.getCommentData() != null) {
cellDataReturn.setCommentData(cellDataValue.getCommentData());
}
if (cellDataValue.getHyperlinkData() != null) {
cellDataReturn.setHyperlinkData(cellDataValue.getHyperlinkData());
}
// The formula information is subject to user input
if (cellDataValue.getFormulaData() != null) {
cellDataReturn.setFormulaData(cellDataValue.getFormulaData());
}
if (cellDataValue.getWriteCellStyle() != null) {
cellDataReturn.setWriteCellStyle(cellDataValue.getWriteCellStyle());
}
return cellDataReturn;
}
return doConvert(cellWriteHandlerContext);
}
private void fillProperty(WriteCellData<?> cellDataValue, ExcelContentProperty excelContentProperty) {
switch (cellDataValue.getType()) {
case DATE:
String dateFormat = null;
if (excelContentProperty != null && excelContentProperty.getDateTimeFormatProperty() != null) {
dateFormat = excelContentProperty.getDateTimeFormatProperty().getFormat();
}
WorkBookUtil.fillDataFormat(cellDataValue, dateFormat, DateUtils.defaultDateFormat);
return;
case NUMBER:
String numberFormat = null;
if (excelContentProperty != null && excelContentProperty.getNumberFormatProperty() != null) {
numberFormat = excelContentProperty.getNumberFormatProperty().getFormat();
}
WorkBookUtil.fillDataFormat(cellDataValue, numberFormat, null);
return;
default:
return;
}
}
private WriteCellData<?> doConvert(CellWriteHandlerContext cellWriteHandlerContext) {
ExcelContentProperty excelContentProperty = cellWriteHandlerContext.getExcelContentProperty();
Converter<?> converter = null;
if (excelContentProperty != null) {
converter = excelContentProperty.getConverter();
}
if (converter == null) {
// csv is converted to string by default
if (writeContext.writeWorkbookHolder().getExcelType() == ExcelTypeEnum.CSV) {
cellWriteHandlerContext.setTargetCellDataType(CellDataTypeEnum.STRING);
}
converter = writeContext.currentWriteHolder().converterMap().get(
ConverterKeyBuild.buildKey(cellWriteHandlerContext.getOriginalFieldClass(),
cellWriteHandlerContext.getTargetCellDataType()));
}
if (cellWriteHandlerContext.getOriginalValue() == null && !(converter instanceof NullableObjectConverter)) {
return new WriteCellData<>(CellDataTypeEnum.EMPTY);
}
if (converter == null) {
throw new ExcelWriteDataConvertException(cellWriteHandlerContext,
"Can not find 'Converter' support class " + cellWriteHandlerContext.getOriginalFieldClass()
.getSimpleName() + ".");
}
WriteCellData<?> cellData;
try {
cellData = ((Converter<Object>)converter).convertToExcelData(
new WriteConverterContext<>(cellWriteHandlerContext.getOriginalValue(), excelContentProperty,
writeContext));
} catch (Exception e) {
throw new ExcelWriteDataConvertException(cellWriteHandlerContext,
"Convert data:" + cellWriteHandlerContext.getOriginalValue() + " error, at row:"
+ cellWriteHandlerContext.getRowIndex(), e);
}
if (cellData == null || cellData.getType() == null) {
throw new ExcelWriteDataConvertException(cellWriteHandlerContext,
"Convert data:" + cellWriteHandlerContext.getOriginalValue()
+ " return is null or return type is null, at row:"
+ cellWriteHandlerContext.getRowIndex());
}
return cellData;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/executor/ExcelWriteAddExecutor.java
|
package ai.chat2db.excel.write.executor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import ai.chat2db.excel.context.WriteContext;
import ai.chat2db.excel.enums.HeadKindEnum;
import ai.chat2db.excel.metadata.FieldCache;
import ai.chat2db.excel.metadata.FieldWrapper;
import ai.chat2db.excel.metadata.Head;
import ai.chat2db.excel.metadata.property.ExcelContentProperty;
import ai.chat2db.excel.support.cglib.beans.BeanMap;
import ai.chat2db.excel.util.BeanMapUtils;
import ai.chat2db.excel.util.ClassUtils;
import ai.chat2db.excel.util.FieldUtils;
import ai.chat2db.excel.util.WorkBookUtil;
import ai.chat2db.excel.util.WriteHandlerUtils;
import ai.chat2db.excel.write.handler.context.CellWriteHandlerContext;
import ai.chat2db.excel.write.handler.context.RowWriteHandlerContext;
import ai.chat2db.excel.write.metadata.CollectionRowData;
import ai.chat2db.excel.write.metadata.MapRowData;
import ai.chat2db.excel.write.metadata.RowData;
import ai.chat2db.excel.write.metadata.holder.WriteHolder;
import ai.chat2db.excel.write.metadata.holder.WriteSheetHolder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
/**
* Add the data into excel
*
* @author Jiaju Zhuang
*/
public class ExcelWriteAddExecutor extends AbstractExcelWriteExecutor {
public ExcelWriteAddExecutor(WriteContext writeContext) {
super(writeContext);
}
public void add(Collection<?> data) {
if (CollectionUtils.isEmpty(data)) {
data = new ArrayList<>();
}
WriteSheetHolder writeSheetHolder = writeContext.writeSheetHolder();
int newRowIndex = writeSheetHolder.getNewRowIndexAndStartDoWrite();
if (writeSheetHolder.isNew() && !writeSheetHolder.getExcelWriteHeadProperty().hasHead()) {
newRowIndex += writeContext.currentWriteHolder().relativeHeadRowIndex();
}
int relativeRowIndex = 0;
for (Object oneRowData : data) {
int lastRowIndex = relativeRowIndex + newRowIndex;
addOneRowOfDataToExcel(oneRowData, lastRowIndex, relativeRowIndex);
relativeRowIndex++;
}
}
private void addOneRowOfDataToExcel(Object oneRowData, int rowIndex, int relativeRowIndex) {
if (oneRowData == null) {
return;
}
RowWriteHandlerContext rowWriteHandlerContext = WriteHandlerUtils.createRowWriteHandlerContext(writeContext,
rowIndex, relativeRowIndex, Boolean.FALSE);
WriteHandlerUtils.beforeRowCreate(rowWriteHandlerContext);
Row row = WorkBookUtil.createRow(writeContext.writeSheetHolder().getSheet(), rowIndex);
rowWriteHandlerContext.setRow(row);
WriteHandlerUtils.afterRowCreate(rowWriteHandlerContext);
if (oneRowData instanceof Collection<?>) {
addBasicTypeToExcel(new CollectionRowData((Collection<?>)oneRowData), row, rowIndex, relativeRowIndex);
} else if (oneRowData instanceof Map) {
addBasicTypeToExcel(new MapRowData((Map<Integer, ?>)oneRowData), row, rowIndex, relativeRowIndex);
} else {
addJavaObjectToExcel(oneRowData, row, rowIndex, relativeRowIndex);
}
WriteHandlerUtils.afterRowDispose(rowWriteHandlerContext);
}
private void addBasicTypeToExcel(RowData oneRowData, Row row, int rowIndex, int relativeRowIndex) {
if (oneRowData.isEmpty()) {
return;
}
Map<Integer, Head> headMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadMap();
int dataIndex = 0;
int maxCellIndex = -1;
for (Map.Entry<Integer, Head> entry : headMap.entrySet()) {
if (dataIndex >= oneRowData.size()) {
return;
}
int columnIndex = entry.getKey();
Head head = entry.getValue();
doAddBasicTypeToExcel(oneRowData, head, row, rowIndex, relativeRowIndex, dataIndex++, columnIndex);
maxCellIndex = Math.max(maxCellIndex, columnIndex);
}
// Finish
if (dataIndex >= oneRowData.size()) {
return;
}
// fix https://github.com/CodePhiliaX/easyexcel-plus/issues/1702
// If there is data, it is written to the next cell
maxCellIndex++;
int size = oneRowData.size() - dataIndex;
for (int i = 0; i < size; i++) {
doAddBasicTypeToExcel(oneRowData, null, row, rowIndex, relativeRowIndex, dataIndex++, maxCellIndex++);
}
}
private void doAddBasicTypeToExcel(RowData oneRowData, Head head, Row row, int rowIndex, int relativeRowIndex,
int dataIndex, int columnIndex) {
ExcelContentProperty excelContentProperty = ClassUtils.declaredExcelContentProperty(null,
writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadClazz(),
head == null ? null : head.getFieldName(), writeContext.currentWriteHolder());
CellWriteHandlerContext cellWriteHandlerContext = WriteHandlerUtils.createCellWriteHandlerContext(writeContext,
row, rowIndex, head, columnIndex, relativeRowIndex, Boolean.FALSE, excelContentProperty);
WriteHandlerUtils.beforeCellCreate(cellWriteHandlerContext);
Cell cell = WorkBookUtil.createCell(row, columnIndex);
cellWriteHandlerContext.setCell(cell);
WriteHandlerUtils.afterCellCreate(cellWriteHandlerContext);
cellWriteHandlerContext.setOriginalValue(oneRowData.get(dataIndex));
cellWriteHandlerContext.setOriginalFieldClass(
FieldUtils.getFieldClass(cellWriteHandlerContext.getOriginalValue()));
converterAndSet(cellWriteHandlerContext);
WriteHandlerUtils.afterCellDispose(cellWriteHandlerContext);
}
private void addJavaObjectToExcel(Object oneRowData, Row row, int rowIndex, int relativeRowIndex) {
WriteHolder currentWriteHolder = writeContext.currentWriteHolder();
BeanMap beanMap = BeanMapUtils.create(oneRowData);
// Bean the contains of the Map Key method with poor performance,So to create a keySet here
Set<String> beanKeySet = new HashSet<>(beanMap.keySet());
Set<String> beanMapHandledSet = new HashSet<>();
int maxCellIndex = -1;
// If it's a class it needs to be cast by type
if (HeadKindEnum.CLASS.equals(writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadKind())) {
Map<Integer, Head> headMap = writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadMap();
for (Map.Entry<Integer, Head> entry : headMap.entrySet()) {
int columnIndex = entry.getKey();
Head head = entry.getValue();
String name = head.getFieldName();
if (!beanKeySet.contains(name)) {
continue;
}
ExcelContentProperty excelContentProperty = ClassUtils.declaredExcelContentProperty(beanMap,
currentWriteHolder.excelWriteHeadProperty().getHeadClazz(), name, currentWriteHolder);
CellWriteHandlerContext cellWriteHandlerContext = WriteHandlerUtils.createCellWriteHandlerContext(
writeContext, row, rowIndex, head, columnIndex, relativeRowIndex, Boolean.FALSE,
excelContentProperty);
WriteHandlerUtils.beforeCellCreate(cellWriteHandlerContext);
Cell cell = WorkBookUtil.createCell(row, columnIndex);
cellWriteHandlerContext.setCell(cell);
WriteHandlerUtils.afterCellCreate(cellWriteHandlerContext);
cellWriteHandlerContext.setOriginalValue(beanMap.get(name));
cellWriteHandlerContext.setOriginalFieldClass(head.getField().getType());
converterAndSet(cellWriteHandlerContext);
WriteHandlerUtils.afterCellDispose(cellWriteHandlerContext);
beanMapHandledSet.add(name);
maxCellIndex = Math.max(maxCellIndex, columnIndex);
}
}
// Finish
if (beanMapHandledSet.size() == beanMap.size()) {
return;
}
maxCellIndex++;
FieldCache fieldCache = ClassUtils.declaredFields(oneRowData.getClass(), writeContext.currentWriteHolder());
for (Map.Entry<Integer, FieldWrapper> entry : fieldCache.getSortedFieldMap().entrySet()) {
FieldWrapper field = entry.getValue();
String fieldName = field.getFieldName();
boolean uselessData = !beanKeySet.contains(fieldName) || beanMapHandledSet.contains(fieldName);
if (uselessData) {
continue;
}
Object value = beanMap.get(fieldName);
ExcelContentProperty excelContentProperty = ClassUtils.declaredExcelContentProperty(beanMap,
currentWriteHolder.excelWriteHeadProperty().getHeadClazz(), fieldName, currentWriteHolder);
CellWriteHandlerContext cellWriteHandlerContext = WriteHandlerUtils.createCellWriteHandlerContext(
writeContext, row, rowIndex, null, maxCellIndex, relativeRowIndex, Boolean.FALSE, excelContentProperty);
WriteHandlerUtils.beforeCellCreate(cellWriteHandlerContext);
// fix https://github.com/CodePhiliaX/easyexcel-plus/issues/1870
// If there is data, it is written to the next cell
Cell cell = WorkBookUtil.createCell(row, maxCellIndex);
cellWriteHandlerContext.setCell(cell);
WriteHandlerUtils.afterCellCreate(cellWriteHandlerContext);
cellWriteHandlerContext.setOriginalValue(value);
cellWriteHandlerContext.setOriginalFieldClass(FieldUtils.getFieldClass(beanMap, fieldName, value));
converterAndSet(cellWriteHandlerContext);
WriteHandlerUtils.afterCellDispose(cellWriteHandlerContext);
maxCellIndex++;
}
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/executor/ExcelWriteExecutor.java
|
package ai.chat2db.excel.write.executor;
/**
* Excel write Executor
*
* @author Jiaju Zhuang
*/
public interface ExcelWriteExecutor {
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/executor/ExcelWriteFillExecutor.java
|
package ai.chat2db.excel.write.executor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import ai.chat2db.excel.context.WriteContext;
import ai.chat2db.excel.enums.CellDataTypeEnum;
import ai.chat2db.excel.enums.WriteDirectionEnum;
import ai.chat2db.excel.enums.WriteTemplateAnalysisCellTypeEnum;
import ai.chat2db.excel.exception.ExcelGenerateException;
import ai.chat2db.excel.metadata.data.WriteCellData;
import ai.chat2db.excel.metadata.property.ExcelContentProperty;
import ai.chat2db.excel.util.BeanMapUtils;
import ai.chat2db.excel.util.ClassUtils;
import ai.chat2db.excel.util.FieldUtils;
import ai.chat2db.excel.util.ListUtils;
import ai.chat2db.excel.util.MapUtils;
import ai.chat2db.excel.util.StringUtils;
import ai.chat2db.excel.util.WriteHandlerUtils;
import ai.chat2db.excel.write.handler.context.CellWriteHandlerContext;
import ai.chat2db.excel.write.handler.context.RowWriteHandlerContext;
import ai.chat2db.excel.write.metadata.fill.AnalysisCell;
import ai.chat2db.excel.write.metadata.fill.FillConfig;
import ai.chat2db.excel.write.metadata.fill.FillWrapper;
import ai.chat2db.excel.write.metadata.holder.WriteSheetHolder;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.collections4.CollectionUtils;
import ai.chat2db.excel.util.PoiUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
/**
* Fill the data into excel
*
* @author Jiaju Zhuang
*/
public class ExcelWriteFillExecutor extends AbstractExcelWriteExecutor {
private static final String ESCAPE_FILL_PREFIX = "\\\\\\{";
private static final String ESCAPE_FILL_SUFFIX = "\\\\\\}";
private static final String FILL_PREFIX = "{";
private static final String FILL_SUFFIX = "}";
private static final char IGNORE_CHAR = '\\';
private static final String COLLECTION_PREFIX = ".";
/**
* Fields to replace in the template
*/
private final Map<UniqueDataFlagKey, List<AnalysisCell>> templateAnalysisCache = MapUtils.newHashMap();
/**
* Collection fields to replace in the template
*/
private final Map<UniqueDataFlagKey, List<AnalysisCell>> templateCollectionAnalysisCache = MapUtils.newHashMap();
/**
* Style cache for collection fields
*/
private final Map<UniqueDataFlagKey, Map<AnalysisCell, CellStyle>> collectionFieldStyleCache
= MapUtils.newHashMap();
/**
* Row height cache for collection
*/
private final Map<UniqueDataFlagKey, Short> collectionRowHeightCache = MapUtils.newHashMap();
/**
* Last index cache for collection fields
*/
private final Map<UniqueDataFlagKey, Map<AnalysisCell, Integer>> collectionLastIndexCache = MapUtils.newHashMap();
private final Map<UniqueDataFlagKey, Integer> relativeRowIndexMap = MapUtils.newHashMap();
/**
* The unique data encoding for this fill
*/
private UniqueDataFlagKey currentUniqueDataFlag;
public ExcelWriteFillExecutor(WriteContext writeContext) {
super(writeContext);
}
public void fill(Object data, FillConfig fillConfig) {
if (data == null) {
data = new HashMap<String, Object>(16);
}
if (fillConfig == null) {
fillConfig = FillConfig.builder().build();
}
fillConfig.init();
Object realData;
// The data prefix that is populated this time
String currentDataPrefix;
if (data instanceof FillWrapper) {
FillWrapper fillWrapper = (FillWrapper)data;
currentDataPrefix = fillWrapper.getName();
realData = fillWrapper.getCollectionData();
} else {
realData = data;
currentDataPrefix = null;
}
currentUniqueDataFlag = uniqueDataFlag(writeContext.writeSheetHolder(), currentDataPrefix);
// processing data
if (realData instanceof Collection) {
List<AnalysisCell> analysisCellList = readTemplateData(templateCollectionAnalysisCache);
Collection<?> collectionData = (Collection<?>)realData;
if (CollectionUtils.isEmpty(collectionData)) {
return;
}
Iterator<?> iterator = collectionData.iterator();
if (WriteDirectionEnum.VERTICAL.equals(fillConfig.getDirection()) && fillConfig.getForceNewRow()) {
shiftRows(collectionData.size(), analysisCellList);
}
while (iterator.hasNext()) {
doFill(analysisCellList, iterator.next(), fillConfig, getRelativeRowIndex());
}
} else {
doFill(readTemplateData(templateAnalysisCache), realData, fillConfig, null);
}
}
private void shiftRows(int size, List<AnalysisCell> analysisCellList) {
if (CollectionUtils.isEmpty(analysisCellList)) {
return;
}
int maxRowIndex = 0;
Map<AnalysisCell, Integer> collectionLastIndexMap = collectionLastIndexCache.get(currentUniqueDataFlag);
for (AnalysisCell analysisCell : analysisCellList) {
if (collectionLastIndexMap != null) {
Integer lastRowIndex = collectionLastIndexMap.get(analysisCell);
if (lastRowIndex != null) {
if (lastRowIndex > maxRowIndex) {
maxRowIndex = lastRowIndex;
}
continue;
}
}
if (analysisCell.getRowIndex() > maxRowIndex) {
maxRowIndex = analysisCell.getRowIndex();
}
}
Sheet cachedSheet = writeContext.writeSheetHolder().getCachedSheet();
int lastRowIndex = cachedSheet.getLastRowNum();
if (maxRowIndex >= lastRowIndex) {
return;
}
Sheet sheet = writeContext.writeSheetHolder().getCachedSheet();
int number = size;
if (collectionLastIndexMap == null) {
number--;
}
if (number <= 0) {
return;
}
sheet.shiftRows(maxRowIndex + 1, lastRowIndex, number, true, false);
// The current data is greater than unity rowindex increase
increaseRowIndex(templateAnalysisCache, number, maxRowIndex);
increaseRowIndex(templateCollectionAnalysisCache, number, maxRowIndex);
}
private void increaseRowIndex(Map<UniqueDataFlagKey, List<AnalysisCell>> templateAnalysisCache, int number,
int maxRowIndex) {
for (Map.Entry<UniqueDataFlagKey, List<AnalysisCell>> entry : templateAnalysisCache.entrySet()) {
UniqueDataFlagKey uniqueDataFlagKey = entry.getKey();
if (!Objects.equals(currentUniqueDataFlag.getSheetNo(), uniqueDataFlagKey.getSheetNo()) || !Objects.equals(
currentUniqueDataFlag.getSheetName(), uniqueDataFlagKey.getSheetName())) {
continue;
}
for (AnalysisCell analysisCell : entry.getValue()) {
if (analysisCell.getRowIndex() > maxRowIndex) {
analysisCell.setRowIndex(analysisCell.getRowIndex() + number);
}
}
}
}
private void doFill(List<AnalysisCell> analysisCellList, Object oneRowData, FillConfig fillConfig,
Integer relativeRowIndex) {
if (CollectionUtils.isEmpty(analysisCellList) || oneRowData == null) {
return;
}
Map dataMap;
if (oneRowData instanceof Map) {
dataMap = (Map)oneRowData;
} else {
dataMap = BeanMapUtils.create(oneRowData);
}
Set<String> dataKeySet = new HashSet<>(dataMap.keySet());
RowWriteHandlerContext rowWriteHandlerContext = WriteHandlerUtils.createRowWriteHandlerContext(writeContext,
null, relativeRowIndex, Boolean.FALSE);
for (AnalysisCell analysisCell : analysisCellList) {
CellWriteHandlerContext cellWriteHandlerContext = WriteHandlerUtils.createCellWriteHandlerContext(
writeContext, null, analysisCell.getRowIndex(), null, analysisCell.getColumnIndex(),
relativeRowIndex, Boolean.FALSE, ExcelContentProperty.EMPTY);
if (analysisCell.getOnlyOneVariable()) {
String variable = analysisCell.getVariableList().get(0);
if (!dataKeySet.contains(variable)) {
continue;
}
Object value = dataMap.get(variable);
ExcelContentProperty excelContentProperty = ClassUtils.declaredExcelContentProperty(dataMap,
writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadClazz(), variable,
writeContext.currentWriteHolder());
cellWriteHandlerContext.setExcelContentProperty(excelContentProperty);
createCell(analysisCell, fillConfig, cellWriteHandlerContext, rowWriteHandlerContext);
cellWriteHandlerContext.setOriginalValue(value);
cellWriteHandlerContext.setOriginalFieldClass(FieldUtils.getFieldClass(dataMap, variable, value));
converterAndSet(cellWriteHandlerContext);
WriteCellData<?> cellData = cellWriteHandlerContext.getFirstCellData();
// Restyle
if (fillConfig.getAutoStyle()) {
Optional.ofNullable(collectionFieldStyleCache.get(currentUniqueDataFlag))
.map(collectionFieldStyleMap -> collectionFieldStyleMap.get(analysisCell))
.ifPresent(cellData::setOriginCellStyle);
}
} else {
StringBuilder cellValueBuild = new StringBuilder();
int index = 0;
List<WriteCellData<?>> cellDataList = new ArrayList<>();
cellWriteHandlerContext.setExcelContentProperty(ExcelContentProperty.EMPTY);
cellWriteHandlerContext.setIgnoreFillStyle(Boolean.TRUE);
createCell(analysisCell, fillConfig, cellWriteHandlerContext, rowWriteHandlerContext);
Cell cell = cellWriteHandlerContext.getCell();
for (String variable : analysisCell.getVariableList()) {
cellValueBuild.append(analysisCell.getPrepareDataList().get(index++));
if (!dataKeySet.contains(variable)) {
continue;
}
Object value = dataMap.get(variable);
ExcelContentProperty excelContentProperty = ClassUtils.declaredExcelContentProperty(dataMap,
writeContext.currentWriteHolder().excelWriteHeadProperty().getHeadClazz(), variable,
writeContext.currentWriteHolder());
cellWriteHandlerContext.setOriginalValue(value);
cellWriteHandlerContext.setOriginalFieldClass(FieldUtils.getFieldClass(dataMap, variable, value));
cellWriteHandlerContext.setExcelContentProperty(excelContentProperty);
cellWriteHandlerContext.setTargetCellDataType(CellDataTypeEnum.STRING);
WriteCellData<?> cellData = convert(cellWriteHandlerContext);
cellDataList.add(cellData);
CellDataTypeEnum type = cellData.getType();
if (type != null) {
switch (type) {
case STRING:
cellValueBuild.append(cellData.getStringValue());
break;
case BOOLEAN:
cellValueBuild.append(cellData.getBooleanValue());
break;
case NUMBER:
cellValueBuild.append(cellData.getNumberValue());
break;
default:
break;
}
}
}
cellValueBuild.append(analysisCell.getPrepareDataList().get(index));
cell.setCellValue(cellValueBuild.toString());
cellWriteHandlerContext.setCellDataList(cellDataList);
if (CollectionUtils.isNotEmpty(cellDataList)) {
cellWriteHandlerContext.setFirstCellData(cellDataList.get(0));
}
// Restyle
if (fillConfig.getAutoStyle()) {
Optional.ofNullable(collectionFieldStyleCache.get(currentUniqueDataFlag))
.map(collectionFieldStyleMap -> collectionFieldStyleMap.get(analysisCell))
.ifPresent(cell::setCellStyle);
}
}
WriteHandlerUtils.afterCellDispose(cellWriteHandlerContext);
}
// In the case of the fill line may be called many times
if (rowWriteHandlerContext.getRow() != null) {
WriteHandlerUtils.afterRowDispose(rowWriteHandlerContext);
}
}
private Integer getRelativeRowIndex() {
Integer relativeRowIndex = relativeRowIndexMap.get(currentUniqueDataFlag);
if (relativeRowIndex == null) {
relativeRowIndex = 0;
} else {
relativeRowIndex++;
}
relativeRowIndexMap.put(currentUniqueDataFlag, relativeRowIndex);
return relativeRowIndex;
}
private void createCell(AnalysisCell analysisCell, FillConfig fillConfig,
CellWriteHandlerContext cellWriteHandlerContext, RowWriteHandlerContext rowWriteHandlerContext) {
Sheet cachedSheet = writeContext.writeSheetHolder().getCachedSheet();
if (WriteTemplateAnalysisCellTypeEnum.COMMON.equals(analysisCell.getCellType())) {
Row row = cachedSheet.getRow(analysisCell.getRowIndex());
cellWriteHandlerContext.setRow(row);
Cell cell = row.getCell(analysisCell.getColumnIndex());
cellWriteHandlerContext.setCell(cell);
rowWriteHandlerContext.setRow(row);
rowWriteHandlerContext.setRowIndex(analysisCell.getRowIndex());
return;
}
Sheet sheet = writeContext.writeSheetHolder().getSheet();
Map<AnalysisCell, Integer> collectionLastIndexMap = collectionLastIndexCache
.computeIfAbsent(currentUniqueDataFlag, key -> MapUtils.newHashMap());
boolean isOriginalCell = false;
Integer lastRowIndex;
Integer lastColumnIndex;
switch (fillConfig.getDirection()) {
case VERTICAL:
lastRowIndex = collectionLastIndexMap.get(analysisCell);
if (lastRowIndex == null) {
lastRowIndex = analysisCell.getRowIndex();
collectionLastIndexMap.put(analysisCell, lastRowIndex);
isOriginalCell = true;
} else {
collectionLastIndexMap.put(analysisCell, ++lastRowIndex);
}
lastColumnIndex = analysisCell.getColumnIndex();
break;
case HORIZONTAL:
lastRowIndex = analysisCell.getRowIndex();
lastColumnIndex = collectionLastIndexMap.get(analysisCell);
if (lastColumnIndex == null) {
lastColumnIndex = analysisCell.getColumnIndex();
collectionLastIndexMap.put(analysisCell, lastColumnIndex);
isOriginalCell = true;
} else {
collectionLastIndexMap.put(analysisCell, ++lastColumnIndex);
}
break;
default:
throw new ExcelGenerateException("The wrong direction.");
}
Row row = createRowIfNecessary(sheet, cachedSheet, lastRowIndex, fillConfig, analysisCell, isOriginalCell,
rowWriteHandlerContext);
cellWriteHandlerContext.setRow(row);
cellWriteHandlerContext.setRowIndex(lastRowIndex);
cellWriteHandlerContext.setColumnIndex(lastColumnIndex);
Cell cell = createCellIfNecessary(row, lastColumnIndex, cellWriteHandlerContext);
cellWriteHandlerContext.setCell(cell);
if (isOriginalCell) {
Map<AnalysisCell, CellStyle> collectionFieldStyleMap = collectionFieldStyleCache.computeIfAbsent(
currentUniqueDataFlag, key -> MapUtils.newHashMap());
collectionFieldStyleMap.put(analysisCell, cell.getCellStyle());
}
}
private Cell createCellIfNecessary(Row row, Integer lastColumnIndex,
CellWriteHandlerContext cellWriteHandlerContext) {
Cell cell = row.getCell(lastColumnIndex);
if (cell != null) {
return cell;
}
WriteHandlerUtils.beforeCellCreate(cellWriteHandlerContext);
cell = row.createCell(lastColumnIndex);
cellWriteHandlerContext.setCell(cell);
WriteHandlerUtils.afterCellCreate(cellWriteHandlerContext);
return cell;
}
private Row createRowIfNecessary(Sheet sheet, Sheet cachedSheet, Integer lastRowIndex, FillConfig fillConfig,
AnalysisCell analysisCell, boolean isOriginalCell, RowWriteHandlerContext rowWriteHandlerContext) {
rowWriteHandlerContext.setRowIndex(lastRowIndex);
Row row = sheet.getRow(lastRowIndex);
if (row != null) {
checkRowHeight(analysisCell, fillConfig, isOriginalCell, row);
rowWriteHandlerContext.setRow(row);
return row;
}
row = cachedSheet.getRow(lastRowIndex);
if (row == null) {
rowWriteHandlerContext.setRowIndex(lastRowIndex);
WriteHandlerUtils.beforeRowCreate(rowWriteHandlerContext);
if (fillConfig.getForceNewRow()) {
row = cachedSheet.createRow(lastRowIndex);
} else {
// The last row of the middle disk inside empty rows, resulting in cachedSheet can not get inside.
// Will throw Attempting to write a row[" + rownum + "] " + "in the range [0," + this._sh
// .getLastRowNum() + "] that is already written to disk.
try {
row = sheet.createRow(lastRowIndex);
} catch (IllegalArgumentException ignore) {
row = cachedSheet.createRow(lastRowIndex);
}
}
rowWriteHandlerContext.setRow(row);
checkRowHeight(analysisCell, fillConfig, isOriginalCell, row);
WriteHandlerUtils.afterRowCreate(rowWriteHandlerContext);
} else {
checkRowHeight(analysisCell, fillConfig, isOriginalCell, row);
rowWriteHandlerContext.setRow(row);
}
return row;
}
private void checkRowHeight(AnalysisCell analysisCell, FillConfig fillConfig, boolean isOriginalCell, Row row) {
if (!analysisCell.getFirstRow() || !WriteDirectionEnum.VERTICAL.equals(fillConfig.getDirection())) {
return;
}
// fix https://github.com/CodePhiliaX/easyexcel-plus/issues/1869
if (isOriginalCell && PoiUtils.customHeight(row)) {
collectionRowHeightCache.put(currentUniqueDataFlag, row.getHeight());
return;
}
if (fillConfig.getAutoStyle()) {
Short rowHeight = collectionRowHeightCache.get(currentUniqueDataFlag);
if (rowHeight != null) {
row.setHeight(rowHeight);
}
}
}
private List<AnalysisCell> readTemplateData(Map<UniqueDataFlagKey, List<AnalysisCell>> analysisCache) {
List<AnalysisCell> analysisCellList = analysisCache.get(currentUniqueDataFlag);
if (analysisCellList != null) {
return analysisCellList;
}
Sheet sheet = writeContext.writeSheetHolder().getCachedSheet();
Map<UniqueDataFlagKey, Set<Integer>> firstRowCache = MapUtils.newHashMapWithExpectedSize(8);
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
if (cell == null) {
continue;
}
String preparedData = prepareData(cell, i, j, firstRowCache);
// Prevent empty data from not being replaced
if (preparedData != null) {
cell.setCellValue(preparedData);
}
}
}
return analysisCache.get(currentUniqueDataFlag);
}
/**
* To prepare data
*
* @param cell cell
* @param rowIndex row index
* @param columnIndex column index
* @param firstRowCache first row cache
* @return Returns the data that the cell needs to replace
*/
private String prepareData(Cell cell, int rowIndex, int columnIndex,
Map<UniqueDataFlagKey, Set<Integer>> firstRowCache) {
if (!CellType.STRING.equals(cell.getCellType())) {
return null;
}
String value = cell.getStringCellValue();
if (StringUtils.isEmpty(value)) {
return null;
}
StringBuilder preparedData = new StringBuilder();
AnalysisCell analysisCell = null;
int startIndex = 0;
int length = value.length();
int lastPrepareDataIndex = 0;
out:
while (startIndex < length) {
int prefixIndex = value.indexOf(FILL_PREFIX, startIndex);
if (prefixIndex < 0) {
break;
}
if (prefixIndex != 0) {
char prefixPrefixChar = value.charAt(prefixIndex - 1);
if (prefixPrefixChar == IGNORE_CHAR) {
startIndex = prefixIndex + 1;
continue;
}
}
int suffixIndex = -1;
while (suffixIndex == -1 && startIndex < length) {
suffixIndex = value.indexOf(FILL_SUFFIX, startIndex + 1);
if (suffixIndex < 0) {
break out;
}
startIndex = suffixIndex + 1;
char prefixSuffixChar = value.charAt(suffixIndex - 1);
if (prefixSuffixChar == IGNORE_CHAR) {
suffixIndex = -1;
}
}
if (analysisCell == null) {
analysisCell = initAnalysisCell(rowIndex, columnIndex);
}
String variable = value.substring(prefixIndex + 1, suffixIndex);
if (StringUtils.isEmpty(variable)) {
continue;
}
int collectPrefixIndex = variable.indexOf(COLLECTION_PREFIX);
if (collectPrefixIndex > -1) {
if (collectPrefixIndex != 0) {
analysisCell.setPrefix(variable.substring(0, collectPrefixIndex));
}
variable = variable.substring(collectPrefixIndex + 1);
if (StringUtils.isEmpty(variable)) {
continue;
}
analysisCell.setCellType(WriteTemplateAnalysisCellTypeEnum.COLLECTION);
}
analysisCell.getVariableList().add(variable);
if (lastPrepareDataIndex == prefixIndex) {
analysisCell.getPrepareDataList().add(StringUtils.EMPTY);
// fix https://github.com/CodePhiliaX/easyexcel-plus/issues/2035
if (lastPrepareDataIndex != 0) {
analysisCell.setOnlyOneVariable(Boolean.FALSE);
}
} else {
String data = convertPrepareData(value.substring(lastPrepareDataIndex, prefixIndex));
preparedData.append(data);
analysisCell.getPrepareDataList().add(data);
analysisCell.setOnlyOneVariable(Boolean.FALSE);
}
lastPrepareDataIndex = suffixIndex + 1;
}
// fix https://github.com/CodePhiliaX/easyexcel-plus/issues/1552
// When read template, XLSX data may be in `is` labels, and set the time set in `v` label, lead to can't set
// up successfully, so all data format to empty first.
if (analysisCell != null && CollectionUtils.isNotEmpty(analysisCell.getVariableList())) {
cell.setBlank();
}
return dealAnalysisCell(analysisCell, value, rowIndex, lastPrepareDataIndex, length, firstRowCache,
preparedData);
}
private String dealAnalysisCell(AnalysisCell analysisCell, String value, int rowIndex, int lastPrepareDataIndex,
int length, Map<UniqueDataFlagKey, Set<Integer>> firstRowCache, StringBuilder preparedData) {
if (analysisCell != null) {
if (lastPrepareDataIndex == length) {
analysisCell.getPrepareDataList().add(StringUtils.EMPTY);
} else {
analysisCell.getPrepareDataList().add(convertPrepareData(value.substring(lastPrepareDataIndex)));
analysisCell.setOnlyOneVariable(Boolean.FALSE);
}
UniqueDataFlagKey uniqueDataFlag = uniqueDataFlag(writeContext.writeSheetHolder(),
analysisCell.getPrefix());
if (WriteTemplateAnalysisCellTypeEnum.COMMON.equals(analysisCell.getCellType())) {
List<AnalysisCell> analysisCellList = templateAnalysisCache.computeIfAbsent(uniqueDataFlag,
key -> ListUtils.newArrayList());
analysisCellList.add(analysisCell);
} else {
Set<Integer> uniqueFirstRowCache = firstRowCache.computeIfAbsent(uniqueDataFlag,
key -> new HashSet<>());
if (!uniqueFirstRowCache.contains(rowIndex)) {
analysisCell.setFirstRow(Boolean.TRUE);
uniqueFirstRowCache.add(rowIndex);
}
List<AnalysisCell> collectionAnalysisCellList = templateCollectionAnalysisCache.computeIfAbsent(
uniqueDataFlag, key -> ListUtils.newArrayList());
collectionAnalysisCellList.add(analysisCell);
}
return preparedData.toString();
}
return null;
}
private AnalysisCell initAnalysisCell(Integer rowIndex, Integer columnIndex) {
AnalysisCell analysisCell = new AnalysisCell();
analysisCell.setRowIndex(rowIndex);
analysisCell.setColumnIndex(columnIndex);
analysisCell.setOnlyOneVariable(Boolean.TRUE);
List<String> variableList = ListUtils.newArrayList();
analysisCell.setVariableList(variableList);
List<String> prepareDataList = ListUtils.newArrayList();
analysisCell.setPrepareDataList(prepareDataList);
analysisCell.setCellType(WriteTemplateAnalysisCellTypeEnum.COMMON);
analysisCell.setFirstRow(Boolean.FALSE);
return analysisCell;
}
private String convertPrepareData(String prepareData) {
prepareData = prepareData.replaceAll(ESCAPE_FILL_PREFIX, FILL_PREFIX);
prepareData = prepareData.replaceAll(ESCAPE_FILL_SUFFIX, FILL_SUFFIX);
return prepareData;
}
private UniqueDataFlagKey uniqueDataFlag(WriteSheetHolder writeSheetHolder, String wrapperName) {
return new UniqueDataFlagKey(writeSheetHolder.getSheetNo(), writeSheetHolder.getSheetName(), wrapperName);
}
@Getter
@Setter
@EqualsAndHashCode
@AllArgsConstructor
public static class UniqueDataFlagKey {
private Integer sheetNo;
private String sheetName;
private String wrapperName;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/AbstractCellWriteHandler.java
|
package ai.chat2db.excel.write.handler;
import java.util.List;
import ai.chat2db.excel.metadata.Head;
import ai.chat2db.excel.metadata.data.WriteCellData;
import ai.chat2db.excel.write.metadata.holder.WriteSheetHolder;
import ai.chat2db.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
/**
* Abstract cell write handler
*
* @author Jiaju Zhuang
* @deprecated Please use it directly {@link CellWriteHandler}
**/
@Deprecated
public abstract class AbstractCellWriteHandler implements CellWriteHandler {
@Override
public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
Head head, Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
WriteCellData<?> cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/AbstractRowWriteHandler.java
|
package ai.chat2db.excel.write.handler;
import ai.chat2db.excel.write.metadata.holder.WriteSheetHolder;
import ai.chat2db.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Row;
/**
* Abstract row write handler
*
* @author Jiaju Zhuang
* @deprecated Please use it directly {@link RowWriteHandler}
**/
@Deprecated
public abstract class AbstractRowWriteHandler implements RowWriteHandler {
@Override
public void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer rowIndex,
Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Integer relativeRowIndex, Boolean isHead) {
}
@Override
public void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Integer relativeRowIndex, Boolean isHead) {
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/AbstractSheetWriteHandler.java
|
package ai.chat2db.excel.write.handler;
import ai.chat2db.excel.write.metadata.holder.WriteSheetHolder;
import ai.chat2db.excel.write.metadata.holder.WriteWorkbookHolder;
/**
* Abstract sheet write handler
*
* @author Jiaju Zhuang
* @deprecated Please use it directly {@link SheetWriteHandler}
**/
@Deprecated
public abstract class AbstractSheetWriteHandler implements SheetWriteHandler {
@Override
public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
}
@Override
public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/AbstractWorkbookWriteHandler.java
|
package ai.chat2db.excel.write.handler;
import ai.chat2db.excel.write.metadata.holder.WriteWorkbookHolder;
/**
* Abstract workbook write handler
*
* @author Jiaju Zhuang
* @deprecated Please use it directly {@link WorkbookWriteHandler}
**/
@Deprecated
public abstract class AbstractWorkbookWriteHandler implements WorkbookWriteHandler {
@Override
public void beforeWorkbookCreate() {
}
@Override
public void afterWorkbookCreate(WriteWorkbookHolder writeWorkbookHolder) {
}
@Override
public void afterWorkbookDispose(WriteWorkbookHolder writeWorkbookHolder) {
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/CellWriteHandler.java
|
package ai.chat2db.excel.write.handler;
import java.util.List;
import ai.chat2db.excel.metadata.Head;
import ai.chat2db.excel.metadata.data.WriteCellData;
import ai.chat2db.excel.write.handler.context.CellWriteHandlerContext;
import ai.chat2db.excel.write.metadata.holder.WriteSheetHolder;
import ai.chat2db.excel.write.metadata.holder.WriteTableHolder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
/**
* intercepts handle cell creation
*
* @author Jiaju Zhuang
*/
public interface CellWriteHandler extends WriteHandler {
/**
* Called before create the cell
*
* @param context
*/
default void beforeCellCreate(CellWriteHandlerContext context) {
beforeCellCreate(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getRow(),
context.getHeadData(), context.getColumnIndex(), context.getRelativeRowIndex(), context.getHead());
}
/**
* Called before create the cell
*
* @param writeSheetHolder
* @param writeTableHolder Nullable.It is null without using table writes.
* @param row
* @param head Nullable.It is null in the case of fill data and without head.
* @param columnIndex
* @param relativeRowIndex Nullable.It is null in the case of fill data.
* @param isHead It will always be false when fill data.
*/
default void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {}
/**
* Called after the cell is created
*
* @param context
*/
default void afterCellCreate(CellWriteHandlerContext context) {
afterCellCreate(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getCell(),
context.getHeadData(), context.getRelativeRowIndex(), context.getHead());
}
/**
* Called after the cell is created
*
* @param writeSheetHolder
* @param writeTableHolder Nullable.It is null without using table writes.
* @param cell
* @param head Nullable.It is null in the case of fill data and without head.
* @param relativeRowIndex Nullable.It is null in the case of fill data.
* @param isHead It will always be false when fill data.
*/
default void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell,
Head head, Integer relativeRowIndex, Boolean isHead) {}
/**
* Called after the cell data is converted
*
* @param context
*/
default void afterCellDataConverted(CellWriteHandlerContext context) {
WriteCellData<?> writeCellData = CollectionUtils.isNotEmpty(context.getCellDataList()) ? context
.getCellDataList().get(0) : null;
afterCellDataConverted(context.getWriteSheetHolder(), context.getWriteTableHolder(), writeCellData,
context.getCell(), context.getHeadData(), context.getRelativeRowIndex(), context.getHead());
}
/**
* Called after the cell data is converted
*
* @param writeSheetHolder
* @param writeTableHolder Nullable.It is null without using table writes.
* @param cell
* @param head Nullable.It is null in the case of fill data and without head.
* @param cellData Nullable.It is null in the case of add header.
* @param relativeRowIndex Nullable.It is null in the case of fill data.
* @param isHead It will always be false when fill data.
*/
default void afterCellDataConverted(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
WriteCellData<?> cellData, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {}
/**
* Called after all operations on the cell have been completed
*
* @param context
*/
default void afterCellDispose(CellWriteHandlerContext context) {
afterCellDispose(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getCellDataList(),
context.getCell(), context.getHeadData(), context.getRelativeRowIndex(), context.getHead());
}
/**
* Called after all operations on the cell have been completed
*
* @param writeSheetHolder
* @param writeTableHolder Nullable.It is null without using table writes.
* @param cell
* @param head Nullable.It is null in the case of fill data and without head.
* @param cellDataList Nullable.It is null in the case of add header.There may be several when fill the data.
* @param relativeRowIndex Nullable.It is null in the case of fill data.
* @param isHead It will always be false when fill data.
*/
default void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder,
List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/DefaultWriteHandlerLoader.java
|
package ai.chat2db.excel.write.handler;
import java.util.ArrayList;
import java.util.List;
import ai.chat2db.excel.support.ExcelTypeEnum;
import ai.chat2db.excel.write.handler.impl.DefaultRowWriteHandler;
import ai.chat2db.excel.write.handler.impl.DimensionWorkbookWriteHandler;
import ai.chat2db.excel.write.handler.impl.FillStyleCellWriteHandler;
import ai.chat2db.excel.write.style.DefaultStyle;
/**
* Load default handler
*
* @author Jiaju Zhuang
*/
public class DefaultWriteHandlerLoader {
public static final List<WriteHandler> DEFAULT_WRITE_HANDLER_LIST = new ArrayList<>();
static {
DEFAULT_WRITE_HANDLER_LIST.add(new DimensionWorkbookWriteHandler());
DEFAULT_WRITE_HANDLER_LIST.add(new DefaultRowWriteHandler());
DEFAULT_WRITE_HANDLER_LIST.add(new FillStyleCellWriteHandler());
}
/**
* Load default handler
*
* @return
*/
public static List<WriteHandler> loadDefaultHandler(Boolean useDefaultStyle, ExcelTypeEnum excelType) {
List<WriteHandler> handlerList = new ArrayList<>();
switch (excelType) {
case XLSX:
handlerList.add(new DimensionWorkbookWriteHandler());
handlerList.add(new DefaultRowWriteHandler());
handlerList.add(new FillStyleCellWriteHandler());
if (useDefaultStyle) {
handlerList.add(new DefaultStyle());
}
break;
case XLS:
handlerList.add(new DefaultRowWriteHandler());
handlerList.add(new FillStyleCellWriteHandler());
if (useDefaultStyle) {
handlerList.add(new DefaultStyle());
}
break;
case CSV:
handlerList.add(new DefaultRowWriteHandler());
handlerList.add(new FillStyleCellWriteHandler());
break;
default:
break;
}
return handlerList;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/RowWriteHandler.java
|
package ai.chat2db.excel.write.handler;
import ai.chat2db.excel.write.handler.context.RowWriteHandlerContext;
import ai.chat2db.excel.write.metadata.holder.WriteSheetHolder;
import ai.chat2db.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.ss.usermodel.Row;
/**
* intercepts handle row creation
*
* @author Jiaju Zhuang
*/
public interface RowWriteHandler extends WriteHandler {
/**
* Called before create the row
*
* @param context
*/
default void beforeRowCreate(RowWriteHandlerContext context) {
beforeRowCreate(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getRowIndex(),
context.getRelativeRowIndex(), context.getHead());
}
/**
* Called before create the row
*
* @param writeSheetHolder
* @param writeTableHolder Nullable.It is null without using table writes.
* @param rowIndex
* @param relativeRowIndex Nullable.It is null in the case of fill data.
* @param isHead Nullable.It is null in the case of fill data.
*/
default void beforeRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Integer rowIndex,
Integer relativeRowIndex, Boolean isHead) {}
/**
* Called after the row is created
*
* @param context
*/
default void afterRowCreate(RowWriteHandlerContext context) {
afterRowCreate(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getRow(),
context.getRelativeRowIndex(), context.getHead());
}
/**
* Called after the row is created
*
* @param writeSheetHolder
* @param writeTableHolder Nullable.It is null without using table writes.
* @param row
* @param relativeRowIndex Nullable.It is null in the case of fill data.
* @param isHead Nullable.It is null in the case of fill data.
*/
default void afterRowCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Integer relativeRowIndex, Boolean isHead) {}
/**
* Called after all operations on the row have been completed.
* In the case of the fill , may be called many times.
*
* @param context
*/
default void afterRowDispose(RowWriteHandlerContext context) {
afterRowDispose(context.getWriteSheetHolder(), context.getWriteTableHolder(), context.getRow(),
context.getRelativeRowIndex(), context.getHead());
}
/**
* Called after all operations on the row have been completed.
* In the case of the fill , may be called many times.
*
* @param writeSheetHolder
* @param writeTableHolder Nullable.It is null without using table writes.
* @param row
* @param relativeRowIndex Nullable.It is null in the case of fill data.
* @param isHead Nullable.It is null in the case of fill data.
*/
default void afterRowDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row,
Integer relativeRowIndex, Boolean isHead) {}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/SheetWriteHandler.java
|
package ai.chat2db.excel.write.handler;
import ai.chat2db.excel.write.handler.context.SheetWriteHandlerContext;
import ai.chat2db.excel.write.metadata.holder.WriteSheetHolder;
import ai.chat2db.excel.write.metadata.holder.WriteWorkbookHolder;
/**
* intercepts handle sheet creation
*
* @author Jiaju Zhuang
*/
public interface SheetWriteHandler extends WriteHandler {
/**
* Called before create the sheet
*
* @param context
*/
default void beforeSheetCreate(SheetWriteHandlerContext context) {
beforeSheetCreate(context.getWriteWorkbookHolder(), context.getWriteSheetHolder());
}
/**
* Called before create the sheet
*
* @param writeWorkbookHolder
* @param writeSheetHolder
*/
default void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {}
/**
* Called after the sheet is created
*
* @param context
*/
default void afterSheetCreate(SheetWriteHandlerContext context) {
afterSheetCreate(context.getWriteWorkbookHolder(), context.getWriteSheetHolder());
}
/**
* Called after the sheet is created
*
* @param writeWorkbookHolder
* @param writeSheetHolder
*/
default void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/WorkbookWriteHandler.java
|
package ai.chat2db.excel.write.handler;
import ai.chat2db.excel.write.handler.context.WorkbookWriteHandlerContext;
import ai.chat2db.excel.write.metadata.holder.WriteWorkbookHolder;
/**
* intercepts handle Workbook creation
*
* @author Jiaju Zhuang
*/
public interface WorkbookWriteHandler extends WriteHandler {
/**
* Called before create the workbook
*
* @param context
*/
default void beforeWorkbookCreate(WorkbookWriteHandlerContext context) {
beforeWorkbookCreate();
}
/**
* Called before create the workbook
*/
default void beforeWorkbookCreate() {}
/**
* Called after the workbook is created
*
* @param context
*/
default void afterWorkbookCreate(WorkbookWriteHandlerContext context) {
afterWorkbookCreate(context.getWriteWorkbookHolder());
}
/**
* Called after the workbook is created
*
* @param writeWorkbookHolder
*/
default void afterWorkbookCreate(WriteWorkbookHolder writeWorkbookHolder) {}
/**
* Called after all operations on the workbook have been completed
*
* @param context
*/
default void afterWorkbookDispose(WorkbookWriteHandlerContext context) {
afterWorkbookDispose(context.getWriteWorkbookHolder());
}
/**
* Called after all operations on the workbook have been completed
*
* @param writeWorkbookHolder
*/
default void afterWorkbookDispose(WriteWorkbookHolder writeWorkbookHolder) {}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/WriteHandler.java
|
package ai.chat2db.excel.write.handler;
import ai.chat2db.excel.event.Handler;
/**
* intercepts handle excel write
*
* @author Jiaju Zhuang
*/
public interface WriteHandler extends Handler {}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/chain/CellHandlerExecutionChain.java
|
package ai.chat2db.excel.write.handler.chain;
import ai.chat2db.excel.write.handler.CellWriteHandler;
import ai.chat2db.excel.write.handler.context.CellWriteHandlerContext;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Execute the cell handler chain
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class CellHandlerExecutionChain {
/**
* next chain
*/
private CellHandlerExecutionChain next;
/**
* handler
*/
private CellWriteHandler handler;
public CellHandlerExecutionChain(CellWriteHandler handler) {
this.handler = handler;
}
public void beforeCellCreate(CellWriteHandlerContext context) {
this.handler.beforeCellCreate(context);
if (this.next != null) {
this.next.beforeCellCreate(context);
}
}
public void afterCellCreate(CellWriteHandlerContext context) {
this.handler.afterCellCreate(context);
if (this.next != null) {
this.next.afterCellCreate(context);
}
}
public void afterCellDataConverted(CellWriteHandlerContext context) {
this.handler.afterCellDataConverted(context);
if (this.next != null) {
this.next.afterCellDataConverted(context);
}
}
public void afterCellDispose(CellWriteHandlerContext context) {
this.handler.afterCellDispose(context);
if (this.next != null) {
this.next.afterCellDispose(context);
}
}
public void addLast(CellWriteHandler handler) {
CellHandlerExecutionChain context = this;
while (context.next != null) {
context = context.next;
}
context.next = new CellHandlerExecutionChain(handler);
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/chain/RowHandlerExecutionChain.java
|
package ai.chat2db.excel.write.handler.chain;
import ai.chat2db.excel.write.handler.RowWriteHandler;
import ai.chat2db.excel.write.handler.context.RowWriteHandlerContext;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Execute the row handler chain
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class RowHandlerExecutionChain {
/**
* next chain
*/
private RowHandlerExecutionChain next;
/**
* handler
*/
private RowWriteHandler handler;
public RowHandlerExecutionChain(RowWriteHandler handler) {
this.handler = handler;
}
public void beforeRowCreate(RowWriteHandlerContext context) {
this.handler.beforeRowCreate(context);
if (this.next != null) {
this.next.beforeRowCreate(context);
}
}
public void afterRowCreate(RowWriteHandlerContext context) {
this.handler.afterRowCreate(context);
if (this.next != null) {
this.next.afterRowCreate(context);
}
}
public void afterRowDispose(RowWriteHandlerContext context) {
this.handler.afterRowDispose(context);
if (this.next != null) {
this.next.afterRowDispose(context);
}
}
public void addLast(RowWriteHandler handler) {
RowHandlerExecutionChain context = this;
while (context.next != null) {
context = context.next;
}
context.next = new RowHandlerExecutionChain(handler);
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/chain/SheetHandlerExecutionChain.java
|
package ai.chat2db.excel.write.handler.chain;
import ai.chat2db.excel.write.handler.SheetWriteHandler;
import ai.chat2db.excel.write.handler.context.SheetWriteHandlerContext;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Execute the sheet handler chain
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class SheetHandlerExecutionChain {
/**
* next chain
*/
private SheetHandlerExecutionChain next;
/**
* handler
*/
private SheetWriteHandler handler;
public SheetHandlerExecutionChain(SheetWriteHandler handler) {
this.handler = handler;
}
public void beforeSheetCreate(SheetWriteHandlerContext context) {
this.handler.beforeSheetCreate(context);
if (this.next != null) {
this.next.beforeSheetCreate(context);
}
}
public void afterSheetCreate(SheetWriteHandlerContext context) {
this.handler.afterSheetCreate(context);
if (this.next != null) {
this.next.afterSheetCreate(context);
}
}
public void addLast(SheetWriteHandler handler) {
SheetHandlerExecutionChain context = this;
while (context.next != null) {
context = context.next;
}
context.next = new SheetHandlerExecutionChain(handler);
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/chain/WorkbookHandlerExecutionChain.java
|
package ai.chat2db.excel.write.handler.chain;
import ai.chat2db.excel.write.handler.WorkbookWriteHandler;
import ai.chat2db.excel.write.handler.context.WorkbookWriteHandlerContext;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* Execute the workbook handler chain
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class WorkbookHandlerExecutionChain {
/**
* next chain
*/
private WorkbookHandlerExecutionChain next;
/**
* handler
*/
private WorkbookWriteHandler handler;
public WorkbookHandlerExecutionChain(WorkbookWriteHandler handler) {
this.handler = handler;
}
public void beforeWorkbookCreate(WorkbookWriteHandlerContext context) {
this.handler.beforeWorkbookCreate(context);
if (this.next != null) {
this.next.beforeWorkbookCreate(context);
}
}
public void afterWorkbookCreate(WorkbookWriteHandlerContext context) {
this.handler.afterWorkbookCreate(context);
if (this.next != null) {
this.next.afterWorkbookCreate(context);
}
}
public void afterWorkbookDispose(WorkbookWriteHandlerContext context) {
this.handler.afterWorkbookDispose(context);
if (this.next != null) {
this.next.afterWorkbookDispose(context);
}
}
public void addLast(WorkbookWriteHandler handler) {
WorkbookHandlerExecutionChain context = this;
while (context.next != null) {
context = context.next;
}
context.next = new WorkbookHandlerExecutionChain(handler);
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/context/CellWriteHandlerContext.java
|
package ai.chat2db.excel.write.handler.context;
import java.util.List;
import ai.chat2db.excel.write.handler.impl.FillStyleCellWriteHandler;
import ai.chat2db.excel.context.WriteContext;
import ai.chat2db.excel.enums.CellDataTypeEnum;
import ai.chat2db.excel.metadata.Head;
import ai.chat2db.excel.metadata.data.WriteCellData;
import ai.chat2db.excel.metadata.property.ExcelContentProperty;
import ai.chat2db.excel.write.metadata.holder.WriteSheetHolder;
import ai.chat2db.excel.write.metadata.holder.WriteTableHolder;
import ai.chat2db.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
/**
* cell context
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
public class CellWriteHandlerContext {
/**
* write context
*/
private WriteContext writeContext;
/**
* workbook
*/
private WriteWorkbookHolder writeWorkbookHolder;
/**
* sheet
*/
private WriteSheetHolder writeSheetHolder;
/**
* table .Nullable.It is null without using table writes.
*/
private WriteTableHolder writeTableHolder;
/**
* row
*/
private Row row;
/**
* index
*/
private Integer rowIndex;
/**
* cell
*/
private Cell cell;
/**
* index
*/
private Integer columnIndex;
/**
* Nullable.It is null in the case of fill data.
*/
private Integer relativeRowIndex;
/**
* Nullable.It is null in the case of fill data.
*/
private Head headData;
/**
* Nullable.It is null in the case of add header.There may be several when fill the data.
*/
private List<WriteCellData<?>> cellDataList;
/**
* Nullable.
* It is null in the case of add header.
* In the case of write there must be not null.
* firstCellData == cellDataList.get(0)
*/
private WriteCellData<?> firstCellData;
/**
* Nullable.It is null in the case of fill data.
*/
private Boolean head;
/**
* Field annotation configuration information.
*/
private ExcelContentProperty excelContentProperty;
/**
* The value of the original
*/
private Object originalValue;
/**
* The original field type
*/
private Class<?> originalFieldClass;
/**
* Target cell data type
*/
private CellDataTypeEnum targetCellDataType;
/**
* Ignore the filling pattern and the {@code FillStyleCellWriteHandler} will not work.
*
* @see FillStyleCellWriteHandler
*/
private Boolean ignoreFillStyle;
public CellWriteHandlerContext(WriteContext writeContext,
WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder,
WriteTableHolder writeTableHolder, Row row, Integer rowIndex, Cell cell, Integer columnIndex,
Integer relativeRowIndex, Head headData, List<WriteCellData<?>> cellDataList, WriteCellData<?> firstCellData,
Boolean head, ExcelContentProperty excelContentProperty) {
this.writeContext = writeContext;
this.writeWorkbookHolder = writeWorkbookHolder;
this.writeSheetHolder = writeSheetHolder;
this.writeTableHolder = writeTableHolder;
this.row = row;
this.rowIndex = rowIndex;
this.cell = cell;
this.columnIndex = columnIndex;
this.relativeRowIndex = relativeRowIndex;
this.headData = headData;
this.cellDataList = cellDataList;
this.firstCellData = firstCellData;
this.head = head;
this.excelContentProperty = excelContentProperty;
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/context/RowWriteHandlerContext.java
|
package ai.chat2db.excel.write.handler.context;
import ai.chat2db.excel.context.WriteContext;
import ai.chat2db.excel.write.metadata.holder.WriteSheetHolder;
import ai.chat2db.excel.write.metadata.holder.WriteTableHolder;
import ai.chat2db.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.apache.poi.ss.usermodel.Row;
/**
* row context
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@AllArgsConstructor
public class RowWriteHandlerContext {
/**
* write context
*/
private WriteContext writeContext;
/**
* workbook
*/
private WriteWorkbookHolder writeWorkbookHolder;
/**
* sheet
*/
private WriteSheetHolder writeSheetHolder;
/**
* table .Nullable.It is null without using table writes.
*/
private WriteTableHolder writeTableHolder;
/**
* row index
*/
private Integer rowIndex;
/**
* row
*/
private Row row;
/**
* Nullable.It is null in the case of fill data.
*/
private Integer relativeRowIndex;
/**
* Nullable.It is null in the case of fill data.
*/
private Boolean head;
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/context/SheetWriteHandlerContext.java
|
package ai.chat2db.excel.write.handler.context;
import ai.chat2db.excel.context.WriteContext;
import ai.chat2db.excel.write.metadata.holder.WriteSheetHolder;
import ai.chat2db.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* sheet context
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@AllArgsConstructor
public class SheetWriteHandlerContext {
/**
* write context
*/
private WriteContext writeContext;
/**
* workbook
*/
private WriteWorkbookHolder writeWorkbookHolder;
/**
* sheet
*/
private WriteSheetHolder writeSheetHolder;
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/context/WorkbookWriteHandlerContext.java
|
package ai.chat2db.excel.write.handler.context;
import ai.chat2db.excel.context.WriteContext;
import ai.chat2db.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* workbook context
*
* @author Jiaju Zhuang
*/
@Getter
@Setter
@EqualsAndHashCode
@AllArgsConstructor
public class WorkbookWriteHandlerContext {
/**
* write context
*/
private WriteContext writeContext;
/**
* workbook
*/
private WriteWorkbookHolder writeWorkbookHolder;
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/impl/DefaultRowWriteHandler.java
|
package ai.chat2db.excel.write.handler.impl;
import ai.chat2db.excel.write.handler.RowWriteHandler;
import ai.chat2db.excel.write.handler.context.RowWriteHandlerContext;
import lombok.extern.slf4j.Slf4j;
/**
* Default row handler.
*
* @author Jiaju Zhuang
*/
@Slf4j
public class DefaultRowWriteHandler implements RowWriteHandler {
@Override
public void afterRowDispose(RowWriteHandlerContext context) {
context.getWriteSheetHolder().setLastRowIndex(context.getRowIndex());
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/impl/DimensionWorkbookWriteHandler.java
|
package ai.chat2db.excel.write.handler.impl;
import java.lang.reflect.Field;
import java.util.Map;
import ai.chat2db.excel.write.handler.WorkbookWriteHandler;
import ai.chat2db.excel.util.FieldUtils;
import ai.chat2db.excel.write.metadata.holder.WriteSheetHolder;
import ai.chat2db.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorksheet;
/**
* Handle the problem of unable to write dimension.
*
* https://github.com/CodePhiliaX/easyexcel-plus/issues/1282
*
* @author Jiaju Zhuang
*/
@Slf4j
public class DimensionWorkbookWriteHandler implements WorkbookWriteHandler {
private static final String XSSF_SHEET_MEMBER_VARIABLE_NAME = "_sh";
private static final Field XSSF_SHEET_FIELD = FieldUtils.getField(SXSSFSheet.class, XSSF_SHEET_MEMBER_VARIABLE_NAME,
true);
@Override
public void afterWorkbookDispose(WriteWorkbookHolder writeWorkbookHolder) {
if (writeWorkbookHolder == null || writeWorkbookHolder.getWorkbook() == null) {
return;
}
if (!(writeWorkbookHolder.getWorkbook() instanceof SXSSFWorkbook)) {
return;
}
Map<Integer, WriteSheetHolder> writeSheetHolderMap = writeWorkbookHolder.getHasBeenInitializedSheetIndexMap();
if (MapUtils.isEmpty(writeSheetHolderMap)) {
return;
}
for (WriteSheetHolder writeSheetHolder : writeSheetHolderMap.values()) {
if (writeSheetHolder.getSheet() == null || !(writeSheetHolder.getSheet() instanceof SXSSFSheet)) {
continue;
}
SXSSFSheet sxssfSheet = ((SXSSFSheet)writeSheetHolder.getSheet());
XSSFSheet xssfSheet;
try {
xssfSheet = (XSSFSheet)XSSF_SHEET_FIELD.get(sxssfSheet);
} catch (IllegalAccessException e) {
log.debug("Can not found _sh.", e);
continue;
}
if (xssfSheet == null) {
continue;
}
CTWorksheet ctWorksheet = xssfSheet.getCTWorksheet();
if (ctWorksheet == null) {
continue;
}
int headSize = 0;
if (MapUtils.isNotEmpty(writeSheetHolder.getExcelWriteHeadProperty().getHeadMap())) {
headSize = writeSheetHolder.getExcelWriteHeadProperty().getHeadMap().size();
if (headSize > 0) {
headSize--;
}
}
Integer lastRowIndex = writeSheetHolder.getLastRowIndex();
if (lastRowIndex == null) {
lastRowIndex = 0;
}
ctWorksheet.getDimension().setRef(
"A1:" + CellReference.convertNumToColString(headSize) + (lastRowIndex + 1));
}
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/handler/impl/FillStyleCellWriteHandler.java
|
package ai.chat2db.excel.write.handler.impl;
import ai.chat2db.excel.write.handler.CellWriteHandler;
import ai.chat2db.excel.constant.OrderConstant;
import ai.chat2db.excel.metadata.data.WriteCellData;
import ai.chat2db.excel.util.BooleanUtils;
import ai.chat2db.excel.write.handler.context.CellWriteHandlerContext;
import ai.chat2db.excel.write.metadata.holder.WriteWorkbookHolder;
import ai.chat2db.excel.write.metadata.style.WriteCellStyle;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.CellStyle;
/**
* fill cell style.
*
* @author Jiaju Zhuang
*/
@Slf4j
public class FillStyleCellWriteHandler implements CellWriteHandler {
@Override
public int order() {
return OrderConstant.FILL_STYLE;
}
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
if (BooleanUtils.isTrue(context.getIgnoreFillStyle())) {
return;
}
WriteCellData<?> cellData = context.getFirstCellData();
if (cellData == null) {
return;
}
WriteCellStyle writeCellStyle = cellData.getWriteCellStyle();
CellStyle originCellStyle = cellData.getOriginCellStyle();
if (writeCellStyle == null && originCellStyle == null) {
return;
}
WriteWorkbookHolder writeWorkbookHolder = context.getWriteWorkbookHolder();
context.getCell().setCellStyle(writeWorkbookHolder.createCellStyle(writeCellStyle, originCellStyle));
}
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/merge/AbstractMergeStrategy.java
|
package ai.chat2db.excel.write.merge;
import ai.chat2db.excel.write.handler.CellWriteHandler;
import ai.chat2db.excel.write.handler.context.CellWriteHandlerContext;
import ai.chat2db.excel.metadata.Head;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
/**
* Merge strategy
*
* @author Jiaju Zhuang
*/
public abstract class AbstractMergeStrategy implements CellWriteHandler {
@Override
public void afterCellDispose(CellWriteHandlerContext context) {
if (context.getHead()) {
return;
}
merge(context.getWriteSheetHolder().getSheet(), context.getCell(), context.getHeadData(),
context.getRelativeRowIndex());
}
/**
* merge
*
* @param sheet
* @param cell
* @param head
* @param relativeRowIndex
*/
protected abstract void merge(Sheet sheet, Cell cell, Head head, Integer relativeRowIndex);
}
|
0
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write
|
java-sources/ai/chat2db/excel/easyexcel-plus-core/0.0.1/ai/chat2db/excel/write/merge/LoopMergeStrategy.java
|
package ai.chat2db.excel.write.merge;
import ai.chat2db.excel.write.handler.RowWriteHandler;
import ai.chat2db.excel.write.handler.context.RowWriteHandlerContext;
import ai.chat2db.excel.metadata.property.LoopMergeProperty;
import org.apache.poi.ss.util.CellRangeAddress;
/**
* The regions of the loop merge
*
* @author Jiaju Zhuang
*/
public class LoopMergeStrategy implements RowWriteHandler {
/**
* Each row
*/
private final int eachRow;
/**
* Extend column
*/
private final int columnExtend;
/**
* The number of the current column
*/
private final int columnIndex;
public LoopMergeStrategy(int eachRow, int columnIndex) {
this(eachRow, 1, columnIndex);
}
public LoopMergeStrategy(int eachRow, int columnExtend, int columnIndex) {
if (eachRow < 1) {
throw new IllegalArgumentException("EachRows must be greater than 1");
}
if (columnExtend < 1) {
throw new IllegalArgumentException("ColumnExtend must be greater than 1");
}
if (columnExtend == 1 && eachRow == 1) {
throw new IllegalArgumentException("ColumnExtend or eachRows must be greater than 1");
}
if (columnIndex < 0) {
throw new IllegalArgumentException("ColumnIndex must be greater than 0");
}
this.eachRow = eachRow;
this.columnExtend = columnExtend;
this.columnIndex = columnIndex;
}
public LoopMergeStrategy(LoopMergeProperty loopMergeProperty, Integer columnIndex) {
this(loopMergeProperty.getEachRow(), loopMergeProperty.getColumnExtend(), columnIndex);
}
@Override
public void afterRowDispose(RowWriteHandlerContext context) {
if (context.getHead() || context.getRelativeRowIndex() == null) {
return;
}
if (context.getRelativeRowIndex() % eachRow == 0) {
CellRangeAddress cellRangeAddress = new CellRangeAddress(context.getRowIndex(),
context.getRowIndex() + eachRow - 1,
columnIndex, columnIndex + columnExtend - 1);
context.getWriteSheetHolder().getSheet().addMergedRegionUnsafe(cellRangeAddress);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.