diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7c9de045e..cacb75ad0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -86,7 +86,7 @@ jobs: restore-keys: | ${{ runner.os }}-m2 - name: Test with Maven - run: ./mvnw clean package -B -Dmaven.test.skip=false -pl fesod-common,fesod-shaded,fesod-sheet + run: ./mvnw clean package -B -Dmaven.test.skip=false -pl fesod-common,fesod-shaded,fesod-sheet,fesod-examples/fesod-sheet-examples - name: Publish Unit Test Results uses: EnricoMi/publish-unit-test-result-action@v2 if: (!cancelled()) diff --git a/fesod-examples/fesod-sheet-examples/pom.xml b/fesod-examples/fesod-sheet-examples/pom.xml index 24c6b151b..3c01afb2b 100644 --- a/fesod-examples/fesod-sheet-examples/pom.xml +++ b/fesod-examples/fesod-sheet-examples/pom.xml @@ -33,15 +33,72 @@ jar Fesod Sheet Examples + + false + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*Test.java + **/*ITCase.java + + + 1 + false + + + + + + org.apache.fesod fesod-sheet ${project.version} + + + ch.qos.logback + logback-classic + ${logback-classic.version} + + + + org.apache.logging.log4j + log4j-to-slf4j + + + + com.alibaba.fastjson2 + fastjson2 + + org.springframework.boot spring-boot-starter-web + + + + org.junit.jupiter + junit-jupiter + test + + + + org.springframework.boot + spring-boot-starter-test test diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/advanced/CustomConverterExample.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/advanced/CustomConverterExample.java new file mode 100644 index 000000000..dc4e1f798 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/advanced/CustomConverterExample.java @@ -0,0 +1,136 @@ +/* + * 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 org.apache.fesod.sheet.examples.advanced; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.context.AnalysisContext; +import org.apache.fesod.sheet.examples.advanced.converter.CustomStringStringConverter; +import org.apache.fesod.sheet.examples.advanced.data.CustomConverterData; +import org.apache.fesod.sheet.examples.util.ExampleFileUtil; +import org.apache.fesod.sheet.read.listener.ReadListener; + +/** + * Demonstrates registering a custom converter at the builder level for read and write. + * + *

Scenario

+ *

You need the same data transformation applied to ALL fields of a matching type, + * not just a specific annotated field. For example, adding a "Custom:" prefix to every + * string column, or encrypting/decrypting all string values.

+ * + *

Key Concepts: Per-Field vs. Global Converter Registration

+ * + * + * + * + * + * + * + * + * + * + * + * + *
ApproachScopeHow
Per-fieldSingle field only{@code @ExcelProperty(converter = MyConverter.class)}
Global (this example)All fields matching Java type + Excel type{@code .registerConverter(new MyConverter())} on the builder
+ * + *

How It Works

+ *
    + *
  1. Write: The {@link CustomStringStringConverter} is registered on the write builder. + * During write, every {@code String} field is transformed (prefixed with "Custom:").
  2. + *
  3. Read: The same converter is registered on the read builder. + * During read, every string cell is transformed back through the converter.
  4. + *
+ * + *

Converter Resolution Priority

+ *
+ * 1. Field-level converter (@ExcelProperty(converter = ...))  ← highest
+ * 2. Builder-level converter (.registerConverter(...))         ← this example
+ * 3. Built-in default converter                                ← lowest
+ * 
+ * + *

Related Examples

+ * + * + * @see CustomStringStringConverter + * @see org.apache.fesod.sheet.converters.Converter + */ +@Slf4j +public class CustomConverterExample { + + public static void main(String[] args) { + String fileName = ExampleFileUtil.getTempPath("customConverter" + System.currentTimeMillis() + ".xlsx"); + customConverterWrite(fileName); + customConverterRead(fileName); + } + + /** + * Writes data with a globally registered converter that prefixes all string values. + * + *

The {@link CustomStringStringConverter} transforms "String0" → "Custom:String0" + * for every string field in the data model.

+ */ + public static void customConverterWrite(String fileName) { + FesodSheet.write(fileName, CustomConverterData.class) + .registerConverter(new CustomStringStringConverter()) + .sheet("CustomConverter") + .doWrite(data()); + log.info("Successfully wrote file with custom converter: {}", fileName); + } + + /** + * Reads the previously written file with the same converter registered. + * + *

The converter's {@code convertToJavaData()} method is applied during read, + * transforming cell values as they are parsed.

+ */ + public static void customConverterRead(String fileName) { + FesodSheet.read(fileName, CustomConverterData.class, new ReadListener() { + @Override + public void invoke(CustomConverterData data, AnalysisContext context) { + log.info("Read data with custom converter: {}", data); + } + + @Override + public void doAfterAllAnalysed(AnalysisContext context) { + log.info("Custom converter read completed"); + } + }) + .registerConverter(new CustomStringStringConverter()) + .sheet() + .doRead(); + } + + private static List data() { + List list = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + CustomConverterData data = new CustomConverterData(); + data.setString("String" + i); + data.setDate(new Date()); + data.setDoubleData(0.56); + list.add(data); + } + return list; + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/advanced/LargeFileWriteExample.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/advanced/LargeFileWriteExample.java new file mode 100644 index 000000000..d6bd78327 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/advanced/LargeFileWriteExample.java @@ -0,0 +1,132 @@ +/* + * 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 org.apache.fesod.sheet.examples.advanced; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.ExcelWriter; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.examples.util.ExampleFileUtil; +import org.apache.fesod.sheet.examples.write.data.DemoData; +import org.apache.fesod.sheet.util.FileUtils; +import org.apache.fesod.sheet.write.handler.WorkbookWriteHandler; +import org.apache.fesod.sheet.write.handler.context.WorkbookWriteHandlerContext; +import org.apache.fesod.sheet.write.metadata.WriteSheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; + +/** + * Demonstrates writing very large Excel files (100,000+ rows) with memory optimization. + * + *

Scenario

+ *

You need to export a large dataset (e.g., database dump, log analysis) that would + * exhaust memory if all rows were held at once. Fesod uses Apache POI's streaming + * API (SXSSF) internally, but temporary XML files can consume significant disk space.

+ * + *

Key Optimization: Temporary File Compression

+ *

When POI writes large XLSX files, it creates temporary XML files on disk + * (one per sheet). These can be several times larger than the final file. + * Enabling compression via {@code setCompressTempFiles(true)} significantly reduces + * disk usage at the cost of slightly more CPU.

+ * + *

Architecture

+ *
+ * Data (in memory, batched)        Fesod          POI/SXSSF
+ *     │                              │                 │
+ *     ├─ 100 rows batch ───────────▶ write() ──────▶ temp XML (compressed)
+ *     ├─ 100 rows batch ───────────▶ write() ──────▶ temp XML (append)
+ *     │  ... (1000 batches)           │                 │
+ *     └─ close() ──────────────────▶ finalize ─────▶ final .xlsx
+ * 
+ * + *

Performance Tips

+ *
    + *
  • Use {@code ExcelWriter} (try-with-resources) for batch writing instead of + * loading all data with {@code doWrite()}.
  • + *
  • Enable temp file compression for disk-constrained environments.
  • + *
  • Tune batch size (100 rows here) based on your row width and available memory.
  • + *
  • Monitor temp directory size: {@code FileUtils.getPoiFilesPath()}.
  • + *
+ * + *

Expected Result

+ *

Writes 100,000 rows (1000 batches x 100 rows) to a single sheet without + * OutOfMemoryError, using compressed temp files on disk.

+ * + *

Related Examples

+ *
    + *
  • {@link org.apache.fesod.sheet.examples.write.BasicWriteExample} — Simple small-file write.
  • + *
+ * + * @see ExcelWriter + * @see org.apache.poi.xssf.streaming.SXSSFWorkbook#setCompressTempFiles(boolean) + */ +@Slf4j +public class LargeFileWriteExample { + + public static void main(String[] args) { + compressedTemporaryFile(); + } + + /** + * Writes 100,000 rows in batches with compressed temporary files. + * + *

Uses a {@link WorkbookWriteHandler} to access the underlying POI + * {@link SXSSFWorkbook} and enable temp file compression. Writing is done + * in 1,000 batches of 100 rows each via the {@link ExcelWriter} API.

+ */ + public static void compressedTemporaryFile() { + log.info("Temporary XML files are stored at: {}", FileUtils.getPoiFilesPath()); + String fileName = ExampleFileUtil.getTempPath("largeFile" + System.currentTimeMillis() + ".xlsx"); + + try (ExcelWriter excelWriter = FesodSheet.write(fileName, DemoData.class) + .registerWriteHandler(new WorkbookWriteHandler() { + @Override + public void afterWorkbookCreate(WorkbookWriteHandlerContext context) { + Workbook workbook = context.getWriteWorkbookHolder().getWorkbook(); + if (workbook instanceof SXSSFWorkbook) { + // Enable temporary file compression. + ((SXSSFWorkbook) workbook).setCompressTempFiles(true); + } + } + }) + .build()) { + WriteSheet writeSheet = FesodSheet.writerSheet("Template").build(); + // Write 100,000 rows in batches. + for (int i = 0; i < 1000; i++) { + excelWriter.write(data(), writeSheet); + } + } + log.info("Successfully wrote large file: {}", fileName); + } + + private static List data() { + List list = new ArrayList<>(); + for (int i = 0; i < 100; i++) { + DemoData data = new DemoData(); + data.setString("String" + i); + data.setDate(new Date()); + data.setDoubleData(0.56); + list.add(data); + } + return list; + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/advanced/PasswordProtectionExample.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/advanced/PasswordProtectionExample.java new file mode 100644 index 000000000..572609433 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/advanced/PasswordProtectionExample.java @@ -0,0 +1,141 @@ +/* + * 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 org.apache.fesod.sheet.examples.advanced; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.context.AnalysisContext; +import org.apache.fesod.sheet.examples.util.ExampleFileUtil; +import org.apache.fesod.sheet.examples.write.data.DemoData; +import org.apache.fesod.sheet.read.listener.ReadListener; + +/** + * Demonstrates reading and writing password-protected Excel files. + * + *

Scenario

+ *

You need to protect sensitive data (financial reports, personal information) + * with Excel's built-in password encryption. Fesod supports both writing encrypted + * files and reading them with the correct password.

+ * + *

Key Concepts

+ *
    + *
  • {@code .password("xxx")} — Available on both read and write builders. + * For write, it encrypts the output file. For read, it decrypts the input file.
  • + *
  • Uses Excel's native encryption (AES for .xlsx), compatible with all Excel versions.
  • + *
  • Without the correct password, reading will throw an + * {@code EncryptedDocumentException}.
  • + *
+ * + *

Usage

+ *
{@code
+ * // Write with password
+ * FesodSheet.write(fileName).password("secret").head(MyData.class).sheet().doWrite(data);
+ *
+ * // Read with password
+ * FesodSheet.read(fileName, MyData.class, listener).password("secret").sheet().doRead();
+ * }
+ * + *

Security Notes

+ *
    + *
  • Excel password protection encrypts the file content, making it unreadable + * without the password.
  • + *
  • In production, avoid hardcoding passwords — use configuration or secrets management.
  • + *
+ * + *

Related Examples

+ *
    + *
  • {@link org.apache.fesod.sheet.examples.write.BasicWriteExample} — Write without encryption.
  • + *
  • {@link org.apache.fesod.sheet.examples.read.BasicReadExample} — Read without encryption.
  • + *
+ * + * @see FesodSheet#write(String) + * @see FesodSheet#read(String, Class, org.apache.fesod.sheet.read.listener.ReadListener) + */ +@Slf4j +public class PasswordProtectionExample { + + public static void main(String[] args) { + String fileName = ExampleFileUtil.getTempPath("password" + System.currentTimeMillis() + ".xlsx"); + String password = "password123"; + + log.info("Starting password protection example..."); + passwordWrite(fileName, password); + passwordRead(fileName, password); + } + + /** + * Writes an Excel file encrypted with the given password. + * + *

The output file can only be opened in Excel (or read by Fesod) with + * the matching password. The encryption is applied at the file level.

+ * + * @param fileName output file path + * @param password encryption password + */ + public static void passwordWrite(String fileName, String password) { + FesodSheet.write(fileName) + .password(password) + .head(DemoData.class) + .sheet("PasswordSheet") + .doWrite(data()); + log.info("Successfully wrote password-protected file: {}", fileName); + } + + /** + * Reads a password-protected Excel file. + * + *

The password must match the one used during write. If incorrect, + * an {@code EncryptedDocumentException} will be thrown.

+ * + * @param fileName input file path + * @param password decryption password + */ + public static void passwordRead(String fileName, String password) { + FesodSheet.read(fileName, DemoData.class, new ReadListener() { + @Override + public void invoke(DemoData data, AnalysisContext context) { + log.info("Read password-protected data: {}", data); + } + + @Override + public void doAfterAllAnalysed(AnalysisContext context) { + log.info("Password-protected file read completed"); + } + }) + .password(password) + .sheet() + .doRead(); + } + + private static List data() { + List list = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + DemoData data = new DemoData(); + data.setString("String" + i); + data.setDate(new Date()); + data.setDoubleData(0.56); + list.add(data); + } + return list; + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/advanced/converter/CustomStringStringConverter.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/advanced/converter/CustomStringStringConverter.java new file mode 100644 index 000000000..eeaded15f --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/advanced/converter/CustomStringStringConverter.java @@ -0,0 +1,86 @@ +/* + * 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 org.apache.fesod.sheet.examples.advanced.converter; + +import org.apache.fesod.sheet.converters.Converter; +import org.apache.fesod.sheet.enums.CellDataTypeEnum; +import org.apache.fesod.sheet.metadata.GlobalConfiguration; +import org.apache.fesod.sheet.metadata.data.ReadCellData; +import org.apache.fesod.sheet.metadata.data.WriteCellData; +import org.apache.fesod.sheet.metadata.property.ExcelContentProperty; + +/** + * Custom String-to-String converter that adds a "Custom:" prefix during both read and write. + * + *

Conversion Behavior

+ *
+ * Read:  Excel cell "Hello"  →  Java string "Custom:Hello"
+ * Write: Java string "Hello" →  Excel cell "Custom:Hello"
+ * 
+ * + *

Difference from Read Converter

+ *

Unlike {@link org.apache.fesod.sheet.examples.read.converters.CustomStringStringConverter} + * (which uses the newer {@code ReadConverterContext}/{@code WriteConverterContext} API), + * this converter uses the legacy method signatures with + * {@link ExcelContentProperty} and {@link GlobalConfiguration} parameters. + * Both approaches are supported by Fesod.

+ * + *

API Versions

+ * + * + * + * + * + * + * + * + * + * + * + * + *
StyleMethod SignatureUsed By
New (recommended){@code convertToJavaData(ReadConverterContext)}read/converters/ package
Legacy (still supported){@code convertToJavaData(ReadCellData, ExcelContentProperty, GlobalConfiguration)}this class
+ * + * @see Converter + * @see org.apache.fesod.sheet.examples.advanced.CustomConverterExample + */ +public class CustomStringStringConverter implements Converter { + + @Override + public Class supportJavaTypeKey() { + return String.class; + } + + @Override + public CellDataTypeEnum supportExcelTypeKey() { + return CellDataTypeEnum.STRING; + } + + @Override + public String convertToJavaData( + ReadCellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { + return "Custom:" + cellData.getStringValue(); + } + + @Override + public WriteCellData convertToExcelData( + String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { + return new WriteCellData<>("Custom:" + value); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/advanced/data/CustomConverterData.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/advanced/data/CustomConverterData.java new file mode 100644 index 000000000..3c7d7500b --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/advanced/data/CustomConverterData.java @@ -0,0 +1,79 @@ +/* + * 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 org.apache.fesod.sheet.examples.advanced.data; + +import java.util.Date; +import lombok.Data; +import org.apache.fesod.sheet.annotation.ExcelProperty; +import org.apache.fesod.sheet.annotation.format.DateTimeFormat; +import org.apache.fesod.sheet.annotation.format.NumberFormat; +import org.apache.fesod.sheet.examples.advanced.converter.CustomStringStringConverter; + +/** + * Data model demonstrating three types of data conversion during Excel read/write. + * + *

This class uses a custom converter, a date format annotation, and a number format + * annotation to control how Excel cell values are converted to and from Java objects.

+ * + *

Conversion Mapping

+ *
+ * Field      | Type   | Annotation / Converter                    | Excel Cell → Java Value
+ * ───────────|────────|───────────────────────────────────────────|────────────────────────
+ * string     | String | @ExcelProperty(converter=Custom...)        | "Hello" → "Custom:Hello"
+ * date       | Date   | @DateTimeFormat("yyyy-MM-dd HH:mm:ss")    | 2025-01-01 → Date object
+ * doubleData | Double | @NumberFormat("#.##%")                     | 0.56 → 0.56 (displayed as "56%")
+ * 
+ * + *

Converter Types

+ *
    + *
  • Custom converter ({@link CustomStringStringConverter}) — Implements + * {@link org.apache.fesod.sheet.converters.Converter} for full control over the + * transformation logic. Applied via {@code @ExcelProperty(converter = ...)}.
  • + *
  • Date format ({@code @DateTimeFormat}) — Specifies the date pattern used + * when converting between Excel date cells and {@link java.util.Date} objects.
  • + *
  • Number format ({@code @NumberFormat}) — Specifies the number pattern used + * when converting between Excel numeric cells and {@link Double} values.
  • + *
+ * + * @see CustomStringStringConverter + * @see DateTimeFormat + * @see NumberFormat + */ +@Data +public class CustomConverterData { + + /** + * Custom converter. + */ + @ExcelProperty(converter = CustomStringStringConverter.class) + private String string; + + /** + * Date format. + */ + @DateTimeFormat("yyyy-MM-dd HH:mm:ss") + private Date date; + + /** + * Number format. + */ + @NumberFormat("#.##%") + private Double doubleData; +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/fill/FillBasicExample.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/fill/FillBasicExample.java new file mode 100644 index 000000000..8cb5f3d7b --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/fill/FillBasicExample.java @@ -0,0 +1,115 @@ +/* + * 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 org.apache.fesod.sheet.examples.fill; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.examples.fill.data.FillData; +import org.apache.fesod.sheet.examples.util.ExampleFileUtil; + +/** + * Demonstrates filling data into a pre-designed Excel template with placeholders. + * + *

Scenario

+ *

You have a pre-formatted Excel template (designed by a non-developer) with + * placeholder variables like {@code {name}} and {@code {number}}. You want to fill in + * actual data at runtime without rebuilding the layout programmatically.

+ * + *

Template Format

+ *

The template file ({@code templates/simple.xlsx}) contains cells with placeholders:

+ *
+ * Template:        | Name: {name}  | Score: {number} |
+ *                       ↓                  ↓
+ * Filled result:   | Name: Zhang San | Score: 5.2 |
+ * 
+ * + *

Two Data Sources

+ *
    + *
  • Object-based — Create a {@link FillData} object. Fesod maps field names + * to template placeholders automatically.
  • + *
  • Map-based — Use a {@code Map} where keys match placeholder names. + * Useful when the structure is dynamic or you don't want to create a POJO.
  • + *
+ * + *

Placeholder Syntax

+ *
    + *
  • {@code {fieldName}} — Replaced by a single value (for simple fills).
  • + *
  • {@code {.fieldName}} — Replaced by a list of values (for list fills, + * see {@link FillComplexExample}).
  • + *
+ * + *

When to Use Fill vs. Write

+ *
    + *
  • Fill — When you have a pre-designed template with specific formatting, + * merged cells, formulas, charts, or complex layouts.
  • + *
  • Write — When generating a simple tabular report from scratch.
  • + *
+ * + *

Related Examples

+ *
    + *
  • {@link FillComplexExample} — Fill templates with list data (multiple rows).
  • + *
  • {@link org.apache.fesod.sheet.examples.write.BasicWriteExample} — Write from scratch.
  • + *
+ * + * @see FesodSheet#write(String) + * @see FillData + */ +@Slf4j +public class FillBasicExample { + + public static void main(String[] args) { + simpleFill(); + } + + /** + * Fills a simple template using both object-based and map-based data sources. + * + *

Demonstrates two equivalent approaches: + *

    + *
  1. Object fill — Uses a {@link FillData} POJO. The field names must match + * the placeholder names in the template.
  2. + *
  3. Map fill — Uses a {@code Map}. The map keys must match + * the placeholder names. More flexible for dynamic structures.
  4. + *
+ * Both produce identical output files.

+ */ + public static void simpleFill() { + String templateFileName = ExampleFileUtil.getExamplePath("templates" + File.separator + "simple.xlsx"); + + // Option 1: Fill based on an object + String fileName = ExampleFileUtil.getTempPath("simpleFill" + System.currentTimeMillis() + ".xlsx"); + FillData fillData = new FillData(); + fillData.setName("Zhang San"); + fillData.setNumber(5.2); + FesodSheet.write(fileName).withTemplate(templateFileName).sheet().doFill(fillData); + log.info("Successfully wrote file: {}", fileName); + + // Option 2: Fill based on a Map + fileName = ExampleFileUtil.getTempPath("simpleFillMap" + System.currentTimeMillis() + ".xlsx"); + Map map = new HashMap<>(); + map.put("name", "Zhang San"); + map.put("number", 5.2); + FesodSheet.write(fileName).withTemplate(templateFileName).sheet().doFill(map); + log.info("Successfully wrote file: {}", fileName); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/fill/FillComplexExample.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/fill/FillComplexExample.java new file mode 100644 index 000000000..af80ce0c4 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/fill/FillComplexExample.java @@ -0,0 +1,122 @@ +/* + * 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 org.apache.fesod.sheet.examples.fill; + +import java.io.File; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.ExcelWriter; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.examples.fill.data.FillData; +import org.apache.fesod.sheet.examples.util.ExampleFileUtil; +import org.apache.fesod.sheet.write.metadata.WriteSheet; + +/** + * Demonstrates filling list data into a template with repeating rows. + * + *

Scenario

+ *

Your template has a list area that should expand with multiple rows of data — + * for example, an invoice with line items, or a report with multiple data rows. + * The template uses {@code {.fieldName}} (dot prefix) placeholders to mark the + * repeating area.

+ * + *

Template Format

+ *

The template file ({@code templates/list.xlsx}) contains a single row with + * list placeholders:

+ *
+ * Template:        | {.name}       | {.number} | {.date}     |
+ *                       ↓               ↓           ↓
+ * Filled result:   | Zhang San0    | 5.2       | 2025-01-01  |
+ *                  | Zhang San1    | 5.2       | 2025-01-02  |
+ *                  | ...           | ...       | ...         |
+ * 
+ * + *

Two Fill Strategies

+ * + *

Strategy 1: Single-Pass Fill

+ *

Load all data into memory and fill at once with {@code doFill(list)}. + * Simple but requires all data in memory.

+ * + *

Strategy 2: Multi-Pass Fill (Memory-Efficient)

+ *

Use {@link ExcelWriter} to fill in batches. Fesod uses file-based caching + * between passes, keeping memory usage low for large datasets.

+ *
{@code
+ * try (ExcelWriter writer = FesodSheet.write(fileName).withTemplate(template).build()) {
+ *     WriteSheet sheet = FesodSheet.writerSheet().build();
+ *     writer.fill(batch1, sheet);  // First batch
+ *     writer.fill(batch2, sheet);  // Second batch
+ * }
+ * }
+ * + *

Related Examples

+ *
    + *
  • {@link FillBasicExample} — Simple single-value template fills.
  • + *
+ * + * @see ExcelWriter#fill(Object, WriteSheet) + * @see FillData + */ +@Slf4j +public class FillComplexExample { + + public static void main(String[] args) { + listFill(); + } + + /** + * Fills a list template using both single-pass and multi-pass strategies. + * + *

Single-pass: All 10 rows loaded into memory, filled in one call.
+ * Multi-pass: Two batches of 10 rows each, filled via {@link ExcelWriter} + * with file-backed caching for lower memory usage.

+ */ + public static void listFill() { + String templateFileName = ExampleFileUtil.getExamplePath("templates" + File.separator + "list.xlsx"); + + // Option 1: Load all data into memory at once and fill + String fileName = ExampleFileUtil.getTempPath("listFill" + System.currentTimeMillis() + ".xlsx"); + FesodSheet.write(fileName).withTemplate(templateFileName).sheet().doFill(data()); + log.info("Successfully wrote file: {}", fileName); + + // Option 2: Fill in multiple passes, using file caching (saves memory) + fileName = ExampleFileUtil.getTempPath("listFillMultiple" + System.currentTimeMillis() + ".xlsx"); + try (ExcelWriter excelWriter = + FesodSheet.write(fileName).withTemplate(templateFileName).build()) { + WriteSheet writeSheet = FesodSheet.writerSheet().build(); + excelWriter.fill(data(), writeSheet); + excelWriter.fill(data(), writeSheet); + } + log.info("Successfully wrote file: {}", fileName); + } + + private static List data() { + List list = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + FillData fillData = new FillData(); + fillData.setName("Zhang San" + i); + fillData.setNumber(5.2); + fillData.setDate(new Date()); + list.add(fillData); + } + return list; + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue1663/FillData.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/fill/data/FillData.java similarity index 50% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue1663/FillData.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/fill/data/FillData.java index f00fa5343..4045dd7a8 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue1663/FillData.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/fill/data/FillData.java @@ -17,16 +17,40 @@ * under the License. */ -package org.apache.fesod.sheet.temp.issue1663; +package org.apache.fesod.sheet.examples.fill.data; +import java.util.Date; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; +/** + * Data model for template fill operations. + * + *

Field names must exactly match the placeholder names in the Excel template. + * For example, if the template contains {@code {name}}, this class must have + * a field named {@code name} (or a getter {@code getName()}).

+ * + *

Template Placeholder Mapping

+ *
+ * Template Placeholder → Java Field
+ * ────────────────────────────────────
+ * {name}    or {.name}   → name   (String)
+ * {number}  or {.number} → number (double)
+ * {date}    or {.date}   → date   (Date)
+ * 
+ * + *

{@code @ExcelProperty} annotations are NOT needed for fill operations — + * the mapping is by field name to placeholder name.

+ * + * @see org.apache.fesod.sheet.examples.fill.FillBasicExample + * @see org.apache.fesod.sheet.examples.fill.FillComplexExample + */ @Getter @Setter @EqualsAndHashCode public class FillData { private String name; private double number; + private Date date; } diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/quickstart/SimpleReadExample.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/quickstart/SimpleReadExample.java new file mode 100644 index 000000000..fb7ab16c7 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/quickstart/SimpleReadExample.java @@ -0,0 +1,102 @@ +/* + * 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 org.apache.fesod.sheet.examples.quickstart; + +import com.alibaba.fastjson2.JSON; +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.examples.quickstart.data.DemoData; +import org.apache.fesod.sheet.examples.util.ExampleFileUtil; +import org.apache.fesod.sheet.read.listener.PageReadListener; + +/** + * The simplest way to read an Excel file with Apache Fesod. + * + *

Scenario

+ *

You have an Excel file ({@code .xlsx} or {@code .xls}) and want to parse it into Java objects + * with minimal boilerplate. This is the recommended starting point for new users.

+ * + *

Key Concepts

+ *
    + *
  • {@link PageReadListener} — A built-in listener that collects rows into pages (default 100 rows per page) + * and delivers them via a lambda callback. Ideal for simple use cases.
  • + *
  • {@link DemoData} — A POJO annotated with {@link org.apache.fesod.sheet.annotation.ExcelProperty} + * to map Excel columns to Java fields by header name.
  • + *
  • Fesod reads row-by-row in a streaming fashion, so memory usage stays low even for large files.
  • + *
+ * + *

Expected Behavior

+ *

When run against the bundled {@code demo.xlsx}, each row is logged as a JSON string:

+ *
{@code
+ * Read a row of data: {"string":"String0","date":"2025-01-01","doubleData":0.56}
+ * Read a row of data: {"string":"String1","date":"2025-01-02","doubleData":0.56}
+ * ...
+ * }
+ * + *

Related Examples

+ *
    + *
  • {@link org.apache.fesod.sheet.examples.read.BasicReadExample} — Uses a custom {@code ReadListener} + * with batch-save logic for production scenarios.
  • + *
  • {@link org.apache.fesod.sheet.examples.quickstart.SimpleWriteExample} — The write counterpart.
  • + *
+ * + * @see FesodSheet#read(String, Class, org.apache.fesod.sheet.read.listener.ReadListener) + * @see PageReadListener + * @see DemoData + */ +@Slf4j +public class SimpleReadExample { + + public static void main(String[] args) { + simpleRead(); + } + + /** + * Reads an Excel file in three simple steps. + * + *
    + *
  1. Define a data model — Create a POJO with {@code @ExcelProperty} annotations + * (see {@link DemoData}).
  2. + *
  3. Provide a listener — {@link PageReadListener} buffers rows and delivers them + * in batches via a lambda. You can also implement {@link org.apache.fesod.sheet.read.listener.ReadListener} + * directly for full control.
  4. + *
  5. Call the builder — {@code FesodSheet.read(...).sheet().doRead()} starts + * the streaming parse, invoking your listener for each page of data.
  6. + *
+ * + *

Note: The file is read in a streaming fashion. Once {@code doRead()} returns, + * all rows have been processed and resources are automatically released.

+ */ + public static void simpleRead() { + String fileName = ExampleFileUtil.getExamplePath("demo.xlsx"); + log.info("Reading file: {}", fileName); + + // Specify the class to read the data, then read the first sheet. + FesodSheet.read(fileName, DemoData.class, new PageReadListener(dataList -> { + for (DemoData demoData : dataList) { + log.info("Read a row of data: {}", JSON.toJSONString(demoData)); + } + })) + .sheet() + .doRead(); + + log.info("Successfully read file: {}", fileName); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/quickstart/SimpleWriteExample.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/quickstart/SimpleWriteExample.java new file mode 100644 index 000000000..143d09cc6 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/quickstart/SimpleWriteExample.java @@ -0,0 +1,107 @@ +/* + * 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 org.apache.fesod.sheet.examples.quickstart; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.examples.quickstart.data.DemoData; +import org.apache.fesod.sheet.examples.util.ExampleFileUtil; + +/** + * The simplest way to write an Excel file with Apache Fesod. + * + *

Scenario

+ *

You have a list of Java objects and want to export them to an Excel file ({@code .xlsx}). + * This is the recommended starting point for new users who need to generate Excel reports.

+ * + *

Key Concepts

+ *
    + *
  • {@link FesodSheet#write(String, Class)} — Creates a write builder bound to a file path and data class.
  • + *
  • {@link DemoData} — A POJO annotated with {@link org.apache.fesod.sheet.annotation.ExcelProperty} + * to define column headers. Fields annotated with {@link org.apache.fesod.sheet.annotation.ExcelIgnore} + * are excluded from the output.
  • + *
  • {@code .sheet("Template")} — Names the worksheet tab in the output file.
  • + *
  • {@code .doWrite(data)} — Terminal operation that writes all data and closes the file.
  • + *
+ * + *

Expected Output

+ *

Generates an Excel file with headers derived from {@code @ExcelProperty} annotations:

+ *
+ * | String Title | Date Title          | Number Title |
+ * |------------- |---------------------|--------------|
+ * | String0      | 2025-01-01 00:00:00 | 0.56         |
+ * | String1      | 2025-01-01 00:00:00 | 0.56         |
+ * | ...          | ...                 | ...          |
+ * 
+ * + *

Related Examples

+ *
    + *
  • {@link org.apache.fesod.sheet.examples.write.StyleWriteExample} — Customize header and content styles.
  • + *
  • {@link org.apache.fesod.sheet.examples.write.MergeWriteExample} — Merge cells during write.
  • + *
  • {@link org.apache.fesod.sheet.examples.quickstart.SimpleReadExample} — The read counterpart.
  • + *
+ * + * @see FesodSheet#write(String, Class) + * @see DemoData + */ +@Slf4j +public class SimpleWriteExample { + + public static void main(String[] args) { + simpleWrite(); + } + + /** + * Writes a list of {@link DemoData} objects to an Excel file in two simple steps. + * + *
    + *
  1. Define a data model — Create a POJO with {@code @ExcelProperty} annotations + * (see {@link DemoData}). The annotation value becomes the column header.
  2. + *
  3. Call the builder — {@code FesodSheet.write(fileName, DemoData.class).sheet("name").doWrite(list)} + * generates the file. The builder handles file creation, header writing, and resource cleanup.
  4. + *
+ * + *

Output location: The file is written to the system temp directory. + * Check the log output for the exact path.

+ */ + public static void simpleWrite() { + // Write to system temp directory for output files + String fileName = ExampleFileUtil.getTempPath("demo" + System.currentTimeMillis() + ".xlsx"); + + // Specify the class to write, then write to the first sheet named "Template" + FesodSheet.write(fileName, DemoData.class).sheet("Template").doWrite(data()); + log.info("Successfully wrote file: {}", fileName); + } + + private static List data() { + List list = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + DemoData data = new DemoData(); + data.setString("String" + i); + data.setDate(new Date()); + data.setDoubleData(0.56); + list.add(data); + } + return list; + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/quickstart/data/DemoData.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/quickstart/data/DemoData.java new file mode 100644 index 000000000..a2b394274 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/quickstart/data/DemoData.java @@ -0,0 +1,84 @@ +/* + * 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 org.apache.fesod.sheet.examples.quickstart.data; + +import java.util.Date; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import org.apache.fesod.sheet.annotation.ExcelIgnore; +import org.apache.fesod.sheet.annotation.ExcelProperty; + +/** + * Data model for the quickstart examples, mapping Java fields to Excel columns. + * + *

Column Mapping

+ *

Each field annotated with {@link ExcelProperty} maps to an Excel column by header name. + * The generated Excel file will have these columns:

+ *
+ * | String Title | Date Title          | Number Title |
+ * |------------- |---------------------|--------------|
+ * | (string)     | (date)              | (doubleData) |
+ * 
+ * + *

Annotations Used

+ *
    + *
  • {@link ExcelProperty} — Maps a field to an Excel column by header name or index.
  • + *
  • {@link ExcelIgnore} — Excludes a field from both reading and writing. + * Useful for internal/transient fields like IDs or computed values.
  • + *
+ * + *

Supported Field Types

+ *

Fesod automatically converts between Excel cell types and common Java types: + * {@code String}, {@code Date}, {@code Double}, {@code Integer}, {@code BigDecimal}, etc. + * For custom conversions, see + * {@link org.apache.fesod.sheet.examples.read.data.ConverterData}.

+ * + * @see ExcelProperty + * @see ExcelIgnore + */ +@Getter +@Setter +@EqualsAndHashCode +public class DemoData { + /** + * String Title + */ + @ExcelProperty("String Title") + private String string; + + /** + * Date Title + */ + @ExcelProperty("Date Title") + private Date date; + + /** + * Number Title + */ + @ExcelProperty("Number Title") + private Double doubleData; + + /** + * Ignore this field + */ + @ExcelIgnore + private String ignore; +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/BasicReadExample.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/BasicReadExample.java new file mode 100644 index 000000000..940488473 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/BasicReadExample.java @@ -0,0 +1,97 @@ +/* + * 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 org.apache.fesod.sheet.examples.read; + +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.examples.read.data.DemoData; +import org.apache.fesod.sheet.examples.read.listeners.DemoDataListener; +import org.apache.fesod.sheet.examples.util.ExampleFileUtil; + +/** + * Demonstrates the standard pattern for reading Excel files with a custom {@link DemoDataListener}. + * + *

Scenario

+ *

You need to read an Excel file and process rows in batches (e.g., inserting into a database + * every 100 rows). This is the production-recommended pattern for reading Excel files with Fesod.

+ * + *

Key Concepts

+ *
    + *
  • {@link DemoDataListener} — A custom {@link org.apache.fesod.sheet.read.listener.ReadListener} + * that implements batch caching and database persistence. See the listener class for + * the full lifecycle details.
  • + *
  • {@link DemoData} — POJO model class mapping Excel columns via {@code @ExcelProperty}.
  • + *
  • Unlike {@link org.apache.fesod.sheet.examples.quickstart.SimpleReadExample} which uses + * the convenience {@code PageReadListener}, this approach gives full control over + * the row processing lifecycle.
  • + *
+ * + *

Listener Lifecycle

+ *
+ * File opened
+ *     │
+ *     ├─ invoke(data, context)       ← called for each data row
+ *     │   └─ batch save every 100 rows
+ *     │
+ *     └─ doAfterAllAnalysed(context) ← called once after last row
+ *         └─ final batch save
+ * 
+ * + *

Expected Behavior

+ *

Each row is logged as JSON. Every 100 rows (or at end of file), a batch save is triggered.

+ * + *

Related Examples

+ *
    + *
  • {@link org.apache.fesod.sheet.examples.quickstart.SimpleReadExample} — Simpler lambda-based approach.
  • + *
  • {@link ConverterReadExample} — Read with data format conversion.
  • + *
  • {@link MultiSheetReadExample} — Read multiple sheets from one file.
  • + *
+ * + * @see DemoDataListener + * @see org.apache.fesod.sheet.read.listener.ReadListener + */ +@Slf4j +public class BasicReadExample { + + public static void main(String[] args) { + basicRead(); + } + + /** + * Reads an Excel file using a custom {@link DemoDataListener}. + * + *

The listener handles row-by-row processing with batch persistence. + * A new listener instance is created per read operation to avoid shared state issues.

+ * + *

Important: Never reuse a listener instance across multiple read operations + * or make it a Spring singleton — it holds mutable state (the cached data list).

+ */ + public static void basicRead() { + String fileName = ExampleFileUtil.getExamplePath("demo.xlsx"); + log.info("Reading file: {}", fileName); + + // Specify the class to read the data, then read the first sheet. + FesodSheet.read(fileName, DemoData.class, new DemoDataListener()) + .sheet() + .doRead(); + + log.info("Successfully read file: {}", fileName); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/ConverterReadExample.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/ConverterReadExample.java new file mode 100644 index 000000000..6406ffae1 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/ConverterReadExample.java @@ -0,0 +1,101 @@ +/* + * 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 org.apache.fesod.sheet.examples.read; + +import com.alibaba.fastjson2.JSON; +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.examples.read.data.ConverterData; +import org.apache.fesod.sheet.examples.util.ExampleFileUtil; +import org.apache.fesod.sheet.read.listener.PageReadListener; + +/** + * Demonstrates reading Excel files with data format converters. + * + *

Scenario

+ *

Your Excel file contains dates and numbers in specific formats (e.g., "2025-01-01 12:30:00" + * or "56.00%"), and you want them read as formatted {@code String} values rather than raw types. + * Or you need a completely custom transformation for a column.

+ * + *

Key Concepts

+ *
    + *
  • {@link org.apache.fesod.sheet.annotation.format.DateTimeFormat} — Converts date cells + * to formatted strings using the specified pattern (e.g., {@code "yyyy-MM-dd HH:mm:ss"}).
  • + *
  • {@link org.apache.fesod.sheet.annotation.format.NumberFormat} — Converts number cells + * to formatted strings using {@link java.text.DecimalFormat} patterns (e.g., {@code "#.##%"}).
  • + *
  • {@link org.apache.fesod.sheet.examples.read.converters.CustomStringStringConverter} — + * A custom converter that prepends "Custom:" to string values, demonstrating + * the {@link org.apache.fesod.sheet.converters.Converter} interface.
  • + *
+ * + *

Data Class Mapping ({@link ConverterData})

+ *
+ * Excel Cell           → Java Field (String)
+ * ─────────────────────────────────────────
+ * "Hello"              → "Custom:Hello"       (via CustomStringStringConverter)
+ * 2025-01-01 12:30:00  → "2025-01-01 12:30:00" (via @DateTimeFormat)
+ * 0.56                 → "56%"                (via @NumberFormat("#.##%"))
+ * 
+ * + *

Expected Behavior

+ *

All fields in {@link ConverterData} are {@code String} type. Fesod applies the configured + * converter/format to transform the raw Excel cell value before setting the field.

+ * + *

Related Examples

+ *
    + *
  • {@link org.apache.fesod.sheet.examples.advanced.CustomConverterExample} — + * Register a custom converter at the builder level (applies to all matching fields).
  • + *
  • {@link BasicReadExample} — Read without converters (automatic type mapping).
  • + *
+ * + * @see ConverterData + * @see org.apache.fesod.sheet.converters.Converter + * @see org.apache.fesod.sheet.annotation.format.DateTimeFormat + * @see org.apache.fesod.sheet.annotation.format.NumberFormat + */ +@Slf4j +public class ConverterReadExample { + + public static void main(String[] args) { + converterRead(); + } + + /** + * Reads an Excel file with converters and format annotations applied. + * + *

Uses {@link PageReadListener} for simplicity. The actual conversion happens + * transparently during parsing — by the time your listener receives the data, + * all fields are already converted according to their annotations.

+ */ + public static void converterRead() { + String fileName = ExampleFileUtil.getExamplePath("demo.xlsx"); + log.info("Reading file with converters: {}", fileName); + + FesodSheet.read(fileName, ConverterData.class, new PageReadListener(dataList -> { + for (ConverterData data : dataList) { + log.info("Read a row of data with converter: {}", JSON.toJSONString(data)); + } + })) + .sheet() + .doRead(); + + log.info("Successfully read file: {}", fileName); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/ExceptionHandlingExample.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/ExceptionHandlingExample.java new file mode 100644 index 000000000..84843a9ec --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/ExceptionHandlingExample.java @@ -0,0 +1,99 @@ +/* + * 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 org.apache.fesod.sheet.examples.read; + +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.examples.read.data.ExceptionDemoData; +import org.apache.fesod.sheet.examples.read.listeners.ExceptionListener; +import org.apache.fesod.sheet.examples.util.ExampleFileUtil; + +/** + * Demonstrates graceful error handling when reading Excel files with data conversion issues. + * + *

Scenario

+ *

Your Excel file contains messy or inconsistent data — for example, a column expected to be + * a date contains plain text like "N/A". Instead of failing the entire read, you want to: + *

    + *
  • Log the problematic row and column
  • + *
  • Skip the bad row
  • + *
  • Continue processing the remaining rows
  • + *
+ * + *

Key Concepts

+ *
    + *
  • {@link org.apache.fesod.sheet.read.listener.ReadListener#onException(Exception, org.apache.fesod.sheet.context.AnalysisContext)} + * — Override this method to intercept conversion errors. If you don't rethrow, + * parsing continues to the next row.
  • + *
  • {@link org.apache.fesod.sheet.exception.ExcelDataConvertException} — Thrown when a cell value + * cannot be converted to the target Java type. Provides {@code getRowIndex()}, + * {@code getColumnIndex()}, and {@code getCellData()} for precise error reporting.
  • + *
  • {@link ExceptionDemoData} — Intentionally uses {@code Date} type for a string column + * to trigger conversion errors.
  • + *
+ * + *

Error Handling Flow

+ *
+ * Row parsed
+ *     │
+ *     ├─ Conversion succeeds → invoke(data, context)
+ *     │
+ *     └─ Conversion fails → onException(ex, context)
+ *         ├─ Log error, DON'T rethrow → skip row, continue parsing
+ *         └─ Rethrow exception → stop parsing immediately
+ * 
+ * + *

Expected Behavior

+ *

Rows with valid dates are processed normally. Rows with incompatible data are logged + * with their exact row/column position and skipped.

+ * + *

Related Examples

+ *
    + *
  • {@link BasicReadExample} — Read without error handling (default: exceptions propagate).
  • + *
+ * + * @see org.apache.fesod.sheet.exception.ExcelDataConvertException + * @see ExceptionListener + */ +@Slf4j +public class ExceptionHandlingExample { + + public static void main(String[] args) { + exceptionRead(); + } + + /** + * Reads an Excel file with an {@link ExceptionListener} that catches and logs conversion errors. + * + *

The {@link ExceptionDemoData} model intentionally maps a string column to {@code Date}, + * causing {@link org.apache.fesod.sheet.exception.ExcelDataConvertException} to be thrown. + * The listener catches these errors, logs them, and lets parsing continue.

+ */ + public static void exceptionRead() { + String fileName = ExampleFileUtil.getExamplePath("demo.xlsx"); + log.info("Reading file with exception handling: {}", fileName); + + FesodSheet.read(fileName, ExceptionDemoData.class, new ExceptionListener()) + .sheet() + .doRead(); + + log.info("Successfully read file: {}", fileName); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/IndexOrNameReadExample.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/IndexOrNameReadExample.java new file mode 100644 index 000000000..19c3ec128 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/IndexOrNameReadExample.java @@ -0,0 +1,101 @@ +/* + * 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 org.apache.fesod.sheet.examples.read; + +import com.alibaba.fastjson2.JSON; +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.examples.read.data.IndexOrNameData; +import org.apache.fesod.sheet.examples.util.ExampleFileUtil; +import org.apache.fesod.sheet.read.listener.PageReadListener; + +/** + * Demonstrates reading Excel columns by positional index or header name. + * + *

Scenario

+ *

Your Excel file may have columns in an unpredictable order, or you only need a subset + * of columns. Instead of relying on field declaration order, you can explicitly map fields + * to columns by index (0-based position) or by header name.

+ * + *

Key Concepts

+ *
    + *
  • {@code @ExcelProperty(index = 2)} — Forces the field to read from the 3rd column (0-based), + * regardless of header name or field order.
  • + *
  • {@code @ExcelProperty("String")} — Matches the column whose header text is "String". + * This is resilient to column reordering.
  • + *
  • Priority: {@code index} > {@code order} > default field declaration order. + * If both {@code index} and name are specified, {@code index} takes priority.
  • + *
+ * + *

Mapping Example ({@link IndexOrNameData})

+ *
+ * Excel Layout:  | String | Date       | Number |
+ * Column Index:  |   0    |     1      |    2   |
+ *
+ * IndexOrNameData.doubleData  ← Column index 2 ("Number")
+ * IndexOrNameData.string      ← Header name "String" (Column 0)
+ * IndexOrNameData.date        ← Header name "Date" (Column 1)
+ * 
+ * + *

When to Use

+ *
    + *
  • Excel columns may be shuffled by users (use name matching).
  • + *
  • You need only specific columns from a wide spreadsheet (use index).
  • + *
  • Different Excel versions have different column orders (use name matching).
  • + *
+ * + *

Related Examples

+ *
    + *
  • {@link BasicReadExample} — Default column matching by field order.
  • + *
  • {@link NoModelReadExample} — Read without any model (raw map data).
  • + *
+ * + * @see IndexOrNameData + * @see org.apache.fesod.sheet.annotation.ExcelProperty + */ +@Slf4j +public class IndexOrNameReadExample { + + public static void main(String[] args) { + indexOrNameRead(); + } + + /** + * Reads using {@link IndexOrNameData} which combines index-based and name-based column matching. + * + *

The {@code doubleData} field reads from column index 2, while {@code string} and + * {@code date} fields match by header name. This flexible approach handles varying + * column layouts gracefully.

+ */ + public static void indexOrNameRead() { + String fileName = ExampleFileUtil.getExamplePath("demo.xlsx"); + log.info("Reading file with index/name mapping: {}", fileName); + + FesodSheet.read(fileName, IndexOrNameData.class, new PageReadListener(dataList -> { + for (IndexOrNameData data : dataList) { + log.info("Read a row of data with index or name: {}", JSON.toJSONString(data)); + } + })) + .sheet() + .doRead(); + + log.info("Successfully read file: {}", fileName); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/MultiSheetReadExample.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/MultiSheetReadExample.java new file mode 100644 index 000000000..4d11f0de9 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/MultiSheetReadExample.java @@ -0,0 +1,116 @@ +/* + * 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 org.apache.fesod.sheet.examples.read; + +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.ExcelReader; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.examples.read.data.DemoData; +import org.apache.fesod.sheet.examples.read.listeners.DemoDataListener; +import org.apache.fesod.sheet.examples.util.ExampleFileUtil; +import org.apache.fesod.sheet.read.metadata.ReadSheet; + +/** + * Demonstrates reading multiple sheets from a single Excel workbook. + * + *

Scenario

+ *

Your Excel workbook contains multiple sheets (tabs), each with its own data. + * You need to read some or all of them, potentially with different data models + * or listeners for each sheet.

+ * + *

Two Approaches

+ * + *

Approach 1: Read All Sheets ({@code doReadAll()})

+ *

Reads every sheet in the workbook using the same data model and listener. + * Simplest approach when all sheets share the same structure.

+ *
{@code
+ * FesodSheet.read(fileName, DemoData.class, new DemoDataListener()).doReadAll();
+ * }
+ * + *

Approach 2: Read Selected Sheets ({@code ExcelReader})

+ *

Creates an {@link ExcelReader} and configures individual {@link ReadSheet} objects. + * Each sheet can have its own data model, listener, and configuration. + * The {@code ExcelReader} must be closed after use (use try-with-resources).

+ *
{@code
+ * try (ExcelReader reader = FesodSheet.read(fileName).build()) {
+ *     ReadSheet sheet1 = FesodSheet.readSheet(0).head(TypeA.class).registerReadListener(listenerA).build();
+ *     ReadSheet sheet2 = FesodSheet.readSheet(1).head(TypeB.class).registerReadListener(listenerB).build();
+ *     reader.read(sheet1, sheet2);
+ * }
+ * }
+ * + *

Expected Behavior

+ *

Each sheet's rows are delivered to its respective listener in order. + * When using {@code doReadAll()}, all sheets share the same listener instance, + * so the listener receives rows from all sheets sequentially.

+ * + *

Related Examples

+ *
    + *
  • {@link BasicReadExample} — Single-sheet read.
  • + *
  • {@link NoModelReadExample} — Read without a data model.
  • + *
+ * + * @see ExcelReader + * @see ReadSheet + * @see FesodSheet#readSheet(Integer) + */ +@Slf4j +public class MultiSheetReadExample { + + public static void main(String[] args) { + repeatedRead(); + } + + /** + * Demonstrates both approaches for reading multiple sheets. + * + *

Approach 1 uses {@code doReadAll()} for simplicity.
+ * Approach 2 uses {@code ExcelReader} with individual {@code ReadSheet} configurations + * for full control over each sheet's data model and listener.

+ * + *

Note: In Approach 2, the {@link ExcelReader} is wrapped in try-with-resources + * to ensure proper resource cleanup. Always close the reader after use.

+ */ + public static void repeatedRead() { + String fileName = ExampleFileUtil.getExamplePath("demo.xlsx"); + log.info("Reading multiple sheets from file: {}", fileName); + + // 1. Read all sheets + FesodSheet.read(fileName, DemoData.class, new DemoDataListener()).doReadAll(); + log.info("Read all sheets completed"); + + // 2. Read specific sheets + try (ExcelReader excelReader = FesodSheet.read(fileName).build()) { + // Create ReadSheet objects for each sheet you want to read. + ReadSheet readSheet1 = FesodSheet.readSheet(0) + .head(DemoData.class) + .registerReadListener(new DemoDataListener()) + .build(); + ReadSheet readSheet2 = FesodSheet.readSheet(1) + .head(DemoData.class) + .registerReadListener(new DemoDataListener()) + .build(); + + // Read multiple sheets at once. + excelReader.read(readSheet1, readSheet2); + } + log.info("Successfully read file: {}", fileName); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/NoModelReadExample.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/NoModelReadExample.java new file mode 100644 index 000000000..4fe9c311f --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/NoModelReadExample.java @@ -0,0 +1,92 @@ +/* + * 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 org.apache.fesod.sheet.examples.read; + +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.examples.read.listeners.NoModelDataListener; +import org.apache.fesod.sheet.examples.util.ExampleFileUtil; + +/** + * Demonstrates reading an Excel file without defining a Java data model. + * + *

Scenario

+ *

You don't know the Excel file's structure at compile time, or you want a quick way + * to inspect any Excel file without creating a POJO. Each row is returned as a + * {@code Map} where the key is the column index (0-based) + * and the value is the cell content as a string.

+ * + *

Key Concepts

+ *
    + *
  • Omit the data class parameter from {@code FesodSheet.read()} — Fesod will use + * {@code Map} as the default row type.
  • + *
  • {@link NoModelDataListener} extends + * {@link org.apache.fesod.sheet.event.AnalysisEventListener}{@code >} + * to receive raw map data.
  • + *
  • All cell values are converted to strings, regardless of the original Excel cell type.
  • + *
+ * + *

Row Data Format

+ *
+ * Excel Row:  | Hello | 2025-01-01 | 0.56 |
+ *                 ↓           ↓         ↓
+ * Map:  {0: "Hello", 1: "2025-01-01", 2: "0.56"}
+ * 
+ * + *

When to Use

+ *
    + *
  • Building generic Excel import tools that handle arbitrary file structures.
  • + *
  • Quick prototyping or debugging — inspect what's in a file.
  • + *
  • Schema-free processing where columns are dynamic.
  • + *
+ * + *

Related Examples

+ *
    + *
  • {@link BasicReadExample} — Type-safe read with a data model (recommended for production).
  • + *
  • {@link IndexOrNameReadExample} — Flexible column matching with index or name.
  • + *
+ * + * @see NoModelDataListener + * @see org.apache.fesod.sheet.event.AnalysisEventListener + */ +@Slf4j +public class NoModelReadExample { + + public static void main(String[] args) { + noModelRead(); + } + + /** + * Reads an Excel file without specifying a data class. + * + *

When no class is provided to {@code FesodSheet.read()}, each row arrives + * as a {@code Map}. The {@link NoModelDataListener} processes + * these maps with the same batch-save pattern used in typed listeners.

+ */ + public static void noModelRead() { + String fileName = ExampleFileUtil.getExamplePath("demo.xlsx"); + log.info("Reading file (no model): {}", fileName); + + // No need to specify a class, just use NoModelDataListener. + FesodSheet.read(fileName, new NoModelDataListener()).sheet().doRead(); + + log.info("Successfully read file: {}", fileName); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/CustomStringStringConverter.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/converters/CustomStringStringConverter.java similarity index 53% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/CustomStringStringConverter.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/converters/CustomStringStringConverter.java index f553a38bc..8e6551b6b 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/CustomStringStringConverter.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/converters/CustomStringStringConverter.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.demo.read; +package org.apache.fesod.sheet.examples.read.converters; import org.apache.fesod.sheet.converters.Converter; import org.apache.fesod.sheet.converters.ReadConverterContext; @@ -26,9 +26,36 @@ import org.apache.fesod.sheet.metadata.data.WriteCellData; /** - * String and string converter + * Custom converter that transforms string cell values by prepending a prefix. * + *

Scenario

+ *

You need custom transformation logic that goes beyond simple formatting — + * for example, adding prefixes, decrypting values, or looking up reference data. + * Implement the {@link Converter} interface to create a reusable converter.

* + *

How It Works

+ *
    + *
  • Read: Excel cell "Hello" → Java string "Custom:Hello"
  • + *
  • Write: Java string "Hello" → Excel cell "Hello" (passthrough)
  • + *
+ * + *

Registration

+ *

Converters can be registered in two ways:

+ *
    + *
  1. Per-field: {@code @ExcelProperty(converter = CustomStringStringConverter.class)} + * on a specific field (see {@link org.apache.fesod.sheet.examples.read.data.ConverterData}).
  2. + *
  3. Global: {@code .registerConverter(new CustomStringStringConverter())} on the builder + * (see {@link org.apache.fesod.sheet.examples.advanced.CustomConverterExample}). + * Applies to all fields matching the Java type + Excel type key.
  4. + *
+ * + *

Type Keys

+ *

{@link #supportJavaTypeKey()} returns {@code String.class} and + * {@link #supportExcelTypeKey()} returns {@code CellDataTypeEnum.STRING}, + * meaning this converter handles String↔String conversions only.

+ * + * @see Converter + * @see org.apache.fesod.sheet.annotation.ExcelProperty#converter() */ public class CustomStringStringConverter implements Converter { @@ -42,24 +69,11 @@ public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.STRING; } - /** - * This method is called when reading data from Excel. - * - * @param context The context containing the cell data read from Excel. - * @return The converted Java data. - */ @Override public String convertToJavaData(ReadConverterContext context) { return "Custom:" + context.getReadCellData().getStringValue(); } - /** - * This method is called when writing data to Excel. - * (This is not relevant in this context and can be ignored.) - * - * @param context The context containing the Java data to be written. - * @return The converted Excel data. - */ @Override public WriteCellData convertToExcelData(WriteConverterContext context) { return new WriteCellData<>(context.getValue()); diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/data/ConverterData.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/data/ConverterData.java new file mode 100644 index 000000000..c5c0e718d --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/data/ConverterData.java @@ -0,0 +1,82 @@ +/* + * 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 org.apache.fesod.sheet.examples.read.data; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import org.apache.fesod.sheet.annotation.ExcelProperty; +import org.apache.fesod.sheet.annotation.format.DateTimeFormat; +import org.apache.fesod.sheet.annotation.format.NumberFormat; +import org.apache.fesod.sheet.examples.read.converters.CustomStringStringConverter; + +/** + * Data model demonstrating three types of data conversion during Excel reading. + * + *

All fields in this class are {@code String} type, but Fesod applies converters + * and format annotations to transform the raw Excel cell values before setting them.

+ * + *

Conversion Mapping

+ *
+ * Field      | Annotation / Converter                    | Excel Cell → Java Value
+ * ───────────|───────────────────────────────────────────|────────────────────────
+ * string     | @ExcelProperty(converter=Custom...)        | "Hello" → "Custom:Hello"
+ * date       | @DateTimeFormat("yyyy-MM-dd HH:mm:ss")    | 2025-01-01 → "2025-01-01 00:00:00"
+ * doubleData | @NumberFormat("#.##%")                     | 0.56 → "56%"
+ * 
+ * + *

Converter Types

+ *
    + *
  • Custom converter ({@link CustomStringStringConverter}) — Implements + * {@link org.apache.fesod.sheet.converters.Converter} for full control over the + * transformation logic. Applied via {@code @ExcelProperty(converter = ...)}.
  • + *
  • Date format ({@code @DateTimeFormat}) — Uses {@link java.text.SimpleDateFormat} + * patterns to format date cells as strings.
  • + *
  • Number format ({@code @NumberFormat}) — Uses {@link java.text.DecimalFormat} + * patterns to format numeric cells as strings.
  • + *
+ * + * @see CustomStringStringConverter + * @see org.apache.fesod.sheet.annotation.format.DateTimeFormat + * @see org.apache.fesod.sheet.annotation.format.NumberFormat + */ +@Getter +@Setter +@EqualsAndHashCode +public class ConverterData { + + /** + * Custom converter. + */ + @ExcelProperty(converter = CustomStringStringConverter.class) + private String string; + + /** + * Date format. + */ + @DateTimeFormat("yyyy-MM-dd HH:mm:ss") + private String date; + + /** + * Number format. + */ + @NumberFormat("#.##%") + private String doubleData; +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/data/DemoDAO.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/data/DemoDAO.java new file mode 100644 index 000000000..50112e54b --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/data/DemoDAO.java @@ -0,0 +1,54 @@ +/* + * 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 org.apache.fesod.sheet.examples.read.data; + +import java.util.List; + +/** + * Mock Data Access Object (DAO) simulating database persistence for examples. + * + *

In production, replace the {@code save()} method body with actual database operations + * (e.g., JDBC batch insert, MyBatis, or JPA). The batch pattern used in + * {@link org.apache.fesod.sheet.examples.read.listeners.DemoDataListener} calls this + * DAO every 100 rows to balance memory usage and database round-trips.

+ * + *

Example production implementation:

+ *
{@code
+ * public void save(List list) {
+ *     // Using Spring JdbcTemplate batch insert
+ *     jdbcTemplate.batchUpdate(
+ *         "INSERT INTO demo (string, date, double_data) VALUES (?, ?, ?)",
+ *         list, list.size(),
+ *         (ps, data) -> {
+ *             ps.setString(1, data.getString());
+ *             ps.setDate(2, new java.sql.Date(data.getDate().getTime()));
+ *             ps.setDouble(3, data.getDoubleData());
+ *         });
+ * }
+ * }
+ * + * @see org.apache.fesod.sheet.examples.read.listeners.DemoDataListener + */ +public class DemoDAO { + + public void save(List list) { + // In actual use, you can use batch insert here. + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/csv/CsvData.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/data/DemoData.java similarity index 51% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/csv/CsvData.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/data/DemoData.java index f7c8319d7..c1d124c49 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/csv/CsvData.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/data/DemoData.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.temp.csv; +package org.apache.fesod.sheet.examples.read.data; import java.util.Date; import lombok.EqualsAndHashCode; @@ -27,24 +27,49 @@ import org.apache.fesod.sheet.annotation.ExcelProperty; /** - * TODO + * Data model for the read examples, mapping Excel columns to Java fields. * + *

This class demonstrates the standard pattern for Fesod data models: + * annotate fields with {@link ExcelProperty} to map them to Excel columns by header name. + * Use {@link ExcelIgnore} to exclude fields that should not participate in reading or writing.

* + *

Column Mapping

+ *
+ * Excel Column:      | String Title | Date Title          | Number Title |
+ * Java Field:        | string       | date                | doubleData   |
+ * Java Type:         | String       | Date                | Double       |
+ * 
+ * + *

The {@code ignore} field is excluded from Excel operations via {@code @ExcelIgnore}, + * making it suitable for internal-only data like database IDs or computed values.

+ * + * @see ExcelProperty + * @see ExcelIgnore */ @Getter @Setter @EqualsAndHashCode -public class CsvData { - @ExcelProperty("字符串标题") +public class DemoData { + /** + * String Title + */ + @ExcelProperty("String Title") private String string; - @ExcelProperty("日期标题") + /** + * Date Title + */ + @ExcelProperty("Date Title") private Date date; - @ExcelProperty("数字标题") + /** + * Number Title + */ + @ExcelProperty("Number Title") private Double doubleData; + /** - * 忽略这个字段 + * Ignore this field */ @ExcelIgnore private String ignore; diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/ExceptionDemoData.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/data/ExceptionDemoData.java similarity index 55% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/ExceptionDemoData.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/data/ExceptionDemoData.java index 77e0e0f70..e2a72a29a 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/ExceptionDemoData.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/data/ExceptionDemoData.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.demo.read; +package org.apache.fesod.sheet.examples.read.data; import java.util.Date; import lombok.EqualsAndHashCode; @@ -25,17 +25,25 @@ import lombok.Setter; /** - * Basic data class. The order here is consistent with the order in the Excel file. + * Data model intentionally designed to trigger conversion errors during reading. * + *

This class maps all Excel data to a single {@code Date} field. When the Excel file + * contains string values (e.g., "String Title") that cannot be parsed as dates, + * Fesod throws an {@link org.apache.fesod.sheet.exception.ExcelDataConvertException}.

* - **/ + *

Used by {@link org.apache.fesod.sheet.examples.read.ExceptionHandlingExample} to + * demonstrate the {@code onException()} callback in + * {@link org.apache.fesod.sheet.examples.read.listeners.ExceptionListener}.

+ * + * @see org.apache.fesod.sheet.examples.read.ExceptionHandlingExample + * @see org.apache.fesod.sheet.exception.ExcelDataConvertException + */ @Getter @Setter @EqualsAndHashCode public class ExceptionDemoData { - /** - * Using a Date to receive a string will definitely cause an error. + * Using a Date to receive a string will cause an error. */ private Date date; } diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/IndexOrNameData.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/data/IndexOrNameData.java similarity index 50% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/IndexOrNameData.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/data/IndexOrNameData.java index 9290584e7..8c61767ee 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/IndexOrNameData.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/data/IndexOrNameData.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.demo.read; +package org.apache.fesod.sheet.examples.read.data; import java.util.Date; import lombok.EqualsAndHashCode; @@ -26,22 +26,38 @@ import org.apache.fesod.sheet.annotation.ExcelProperty; /** - * Basic data class + * Data model demonstrating mixed index-based and name-based column matching. * + *

Mapping Strategy

+ *
+ * Field       | Annotation                  | Matches Column
+ * ────────────|─────────────────────────────|───────────────
+ * doubleData  | @ExcelProperty(index = 2)   | Column 3 (by position)
+ * string      | @ExcelProperty("String")    | Header "String" (by name)
+ * date        | @ExcelProperty("Date")      | Header "Date" (by name)
+ * 
* - **/ + *

Priority Rules

+ *

When both {@code index} and name are specified on the same field, {@code index} wins. + * The full priority order is: {@code index} > {@code order} > field declaration order.

+ * + *

Tip: Use index-based matching when the Excel column position is fixed and known. + * Use name-based matching when users might reorder columns but headers remain consistent.

+ * + * @see org.apache.fesod.sheet.annotation.ExcelProperty + * @see org.apache.fesod.sheet.examples.read.IndexOrNameReadExample + */ @Getter @Setter @EqualsAndHashCode public class IndexOrNameData { /** - * Force reading the third column. It is not recommended to use both index and name at the same time. - * Either use index only or use name only for matching within a single object. + * Force reading the third column. */ @ExcelProperty(index = 2) private Double doubleData; /** - * Match by name. Note that if the name is duplicated, only one field will be populated with data. + * Match by name. */ @ExcelProperty("String") private String string; diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/listeners/DemoDataListener.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/listeners/DemoDataListener.java new file mode 100644 index 000000000..e35d86ee2 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/listeners/DemoDataListener.java @@ -0,0 +1,144 @@ +/* + * 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 org.apache.fesod.sheet.examples.read.listeners; + +import com.alibaba.fastjson2.JSON; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.common.util.ListUtils; +import org.apache.fesod.sheet.context.AnalysisContext; +import org.apache.fesod.sheet.examples.read.data.DemoDAO; +import org.apache.fesod.sheet.examples.read.data.DemoData; +import org.apache.fesod.sheet.read.listener.ReadListener; + +/** + * Production-pattern listener demonstrating batch read-and-persist for Excel data. + * + *

Scenario

+ *

Reading a large Excel file (thousands or millions of rows) and inserting the data + * into a database. Loading all rows into memory at once would cause an OutOfMemoryError. + * This listener accumulates rows in a small batch and persists every {@value #BATCH_COUNT} + * rows, then clears the cache.

+ * + *

Lifecycle

+ *
+ * ┌───────────────────────────────────────────────────────────────────┐
+ * │  invoke(data, context)  ← called once per data row              │
+ * │    └─ add to cachedDataList                                    │
+ * │    └─ if cache.size() >= 100 → saveData() → clear cache       │
+ * ├───────────────────────────────────────────────────────────────────┤
+ * │  doAfterAllAnalysed(context)  ← called once after last row      │
+ * │    └─ saveData() for remaining rows in cache                   │
+ * └───────────────────────────────────────────────────────────────────┘
+ * 
+ * + *

Thread Safety & Lifecycle

+ *

IMPORTANT: This class must NOT be managed by Spring (or any IoC container) as a + * singleton. Create a new instance for each read operation because: + *

    + *
  • The {@code cachedDataList} is mutable state that must not be shared.
  • + *
  • Reusing a listener across files would mix data from different files.
  • + *
+ * + *

Spring Integration

+ *

If you need to inject Spring beans (e.g., a real DAO), use the constructor that + * accepts a {@link DemoDAO} parameter. Create the listener in your service method:

+ *
{@code
+ * @Service
+ * public class ExcelService {
+ *     @Autowired
+ *     private DemoDAO demoDAO;
+ *
+ *     public void importExcel(String fileName) {
+ *         // Create a NEW listener for each read, passing the Spring-managed DAO
+ *         FesodSheet.read(fileName, DemoData.class, new DemoDataListener(demoDAO))
+ *             .sheet().doRead();
+ *     }
+ * }
+ * }
+ * + * @see ReadListener + * @see org.apache.fesod.sheet.examples.read.BasicReadExample + */ +@Slf4j +public class DemoDataListener implements ReadListener { + + /** + * Store data in the database every 100 records. + */ + private static final int BATCH_COUNT = 100; + /** + * Cached data + */ + private List cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); + /** + * Mock DAO + */ + private DemoDAO demoDAO; + + public DemoDataListener() { + // This is a demo, so a new instance is created here. + demoDAO = new DemoDAO(); + } + + /** + * If Spring is used, please use this constructor. + * + * @param demoDAO + */ + public DemoDataListener(DemoDAO demoDAO) { + this.demoDAO = demoDAO; + } + + /** + * This method will be called for each data parsed. + * + * @param data one row value. + * @param context + */ + @Override + public void invoke(DemoData data, AnalysisContext context) { + log.info("Parsed one row of data: {}", JSON.toJSONString(data)); + cachedDataList.add(data); + if (cachedDataList.size() >= BATCH_COUNT) { + saveData(); + cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); + } + } + + /** + * This method will be called after all data has been parsed. + * + * @param context + */ + @Override + public void doAfterAllAnalysed(AnalysisContext context) { + saveData(); + log.info("All data has been parsed!"); + } + + /** + * Save data to database. + */ + private void saveData() { + log.info("{} records saved to database!", cachedDataList.size()); + demoDAO.save(cachedDataList); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoExceptionListener.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/listeners/ExceptionListener.java similarity index 58% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoExceptionListener.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/listeners/ExceptionListener.java index f6b0c0b30..d3e57fdb7 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoExceptionListener.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/listeners/ExceptionListener.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.demo.read; +package org.apache.fesod.sheet.examples.read.listeners; import com.alibaba.fastjson2.JSON; import java.util.List; @@ -25,37 +25,53 @@ import lombok.extern.slf4j.Slf4j; import org.apache.fesod.common.util.ListUtils; import org.apache.fesod.sheet.context.AnalysisContext; +import org.apache.fesod.sheet.examples.read.data.ExceptionDemoData; import org.apache.fesod.sheet.exception.ExcelDataConvertException; import org.apache.fesod.sheet.metadata.data.ReadCellData; import org.apache.fesod.sheet.read.listener.ReadListener; /** - * Read and convert exceptions. + * Listener that demonstrates graceful exception handling during Excel reading. * + *

Scenario

+ *

When reading an Excel file with inconsistent data (e.g., text in a date column), + * Fesod throws an {@link ExcelDataConvertException}. This listener catches those errors, + * logs diagnostic information, and allows parsing to continue for the remaining rows.

* + *

Key Methods

+ *
    + *
  • {@link #onException(Exception, AnalysisContext)} — Intercepts any exception during parsing. + * If the exception is an {@code ExcelDataConvertException}, logs the exact row, column, + * and cell value that caused the error. Not rethrowing the exception tells Fesod + * to skip this row and continue.
  • + *
  • {@link #invokeHead(Map, AnalysisContext)} — Called when the header row is parsed. + * Receives a map of column index → {@link ReadCellData} containing header cell information.
  • + *
  • {@link #invoke(ExceptionDemoData, AnalysisContext)} — Called for each successfully + * converted data row.
  • + *
  • {@link #doAfterAllAnalysed(AnalysisContext)} — Called after the last row. + * Persists any remaining cached data.
  • + *
+ * + *

Error Handling Strategy

+ *
+ * onException() is called:
+ *     ├─ ExcelDataConvertException → log row/column/value, continue
+ *     └─ Other exception → log message, continue (or rethrow to stop)
+ * 
+ * + * @see ExcelDataConvertException + * @see org.apache.fesod.sheet.examples.read.ExceptionHandlingExample */ @Slf4j -public class DemoExceptionListener implements ReadListener { +public class ExceptionListener implements ReadListener { - /** - * Save to the database every 5 records. In actual use, it can be set to 100 records, and then clear the list to facilitate memory recycling. - */ - private static final int BATCH_COUNT = 5; + private static final int BATCH_COUNT = 100; private List cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); - /** - * This interface will be called in case of conversion exceptions or other exceptions. If an exception is thrown here, reading will be stopped. If no exception is thrown, the next line will continue to be read. - * - * @param exception The exception that occurred. - * @param context The analysis context. - * @throws Exception If an exception needs to be propagated. - */ @Override public void onException(Exception exception, AnalysisContext context) { log.error("Parsing failed, but continue parsing the next line: {}", exception.getMessage()); - // If it is a cell conversion exception, the specific row number can be obtained. - // If the header information is needed, use it in conjunction with invokeHeadMap. if (exception instanceof ExcelDataConvertException) { ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception; log.error( @@ -66,12 +82,6 @@ public void onException(Exception exception, AnalysisContext context) { } } - /** - * This method will return the header row line by line. - * - * @param headMap The header map containing column index and cell data. - * @param context The analysis context. - */ @Override public void invokeHead(Map> headMap, AnalysisContext context) { log.info("Parsed a header row: {}", JSON.toJSONString(headMap)); @@ -80,6 +90,7 @@ public void invokeHead(Map> headMap, AnalysisContext co @Override public void invoke(ExceptionDemoData data, AnalysisContext context) { log.info("Parsed a data row: {}", JSON.toJSONString(data)); + cachedDataList.add(data); if (cachedDataList.size() >= BATCH_COUNT) { saveData(); cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); @@ -92,11 +103,7 @@ public void doAfterAllAnalysed(AnalysisContext context) { log.info("All data parsing completed!"); } - /** - * Save data to the database. - */ private void saveData() { - log.info("{} records, starting to save to the database!", cachedDataList.size()); - log.info("Data saved to the database successfully!"); + log.info("{} records saved to database!", cachedDataList.size()); } } diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/NoModelDataListener.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/listeners/NoModelDataListener.java similarity index 62% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/NoModelDataListener.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/listeners/NoModelDataListener.java index 16c805f8f..046b5ec05 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/NoModelDataListener.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/read/listeners/NoModelDataListener.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.demo.read; +package org.apache.fesod.sheet.examples.read.listeners; import com.alibaba.fastjson2.JSON; import java.util.List; @@ -28,17 +28,41 @@ import org.apache.fesod.sheet.event.AnalysisEventListener; /** - * Directly receive data using a map. + * Listener for schema-free Excel reading without a data model. * + *

Scenario

+ *

When you don't have (or don't want) a POJO mapped to the Excel structure, + * this listener receives each row as a {@code Map} where: + *

    + *
  • Key = column index (0-based)
  • + *
  • Value = cell content as a string
  • + *
* + *

Key Differences from Typed Listeners

+ *
    + *
  • Extends {@link AnalysisEventListener}{@code >} instead of + * implementing {@code ReadListener}.
  • + *
  • No {@code @ExcelProperty} annotations needed — all columns are automatically included.
  • + *
  • All values arrive as strings, even if the Excel cell is numeric or date type.
  • + *
+ * + *

When to Use

+ *
    + *
  • Generic Excel import tools that accept any file layout.
  • + *
  • Quick data inspection / debugging.
  • + *
  • Dynamic column handling where structure is unknown at compile time.
  • + *
+ * + * @see org.apache.fesod.sheet.examples.read.NoModelReadExample + * @see AnalysisEventListener */ @Slf4j public class NoModelDataListener extends AnalysisEventListener> { /** - * Save to the database every 5 records. In actual use, it can be set to 100 records, and then clear the list to facilitate memory recycling. + * Save to the database every 100 records. */ - private static final int BATCH_COUNT = 5; + private static final int BATCH_COUNT = 100; private List> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/util/ExampleDataGenerator.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/util/ExampleDataGenerator.java new file mode 100644 index 000000000..7b01414cd --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/util/ExampleDataGenerator.java @@ -0,0 +1,62 @@ +/* + * 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 org.apache.fesod.sheet.examples.util; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * Utility class for generating sample data used across examples. + * + *

Provides convenient methods to create test data lists for demonstrating + * Fesod's features. In production, data would come from databases, APIs, or user input.

+ */ +public class ExampleDataGenerator { + + /** + * Generates a list of strings. + * + * @param count number of strings to generate + * @return list of strings + */ + public static List generateStrings(int count) { + List list = new ArrayList<>(); + for (int i = 0; i < count; i++) { + list.add("Data " + i); + } + return list; + } + + /** + * Generates a list of dates. + * + * @param count number of dates to generate + * @return list of dates + */ + public static List generateDates(int count) { + List list = new ArrayList<>(); + long now = System.currentTimeMillis(); + for (int i = 0; i < count; i++) { + list.add(new Date(now + i * 1000 * 60 * 60 * 24)); + } + return list; + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/util/ExampleFileUtil.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/util/ExampleFileUtil.java new file mode 100644 index 000000000..0bfbc75d4 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/util/ExampleFileUtil.java @@ -0,0 +1,85 @@ +/* + * 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 org.apache.fesod.sheet.examples.util; + +import java.io.File; +import java.nio.file.Files; +import lombok.SneakyThrows; + +/** + * Utility class for locating example input files and generating output file paths. + * + *

File Locations

+ *
    + *
  • Input files: Located in the classpath under {@code example/} directory + * (e.g., {@code src/main/resources/example/demo.xlsx}). + * Access via {@link #getExamplePath(String)}.
  • + *
  • Output files: Written to the system temp directory to avoid polluting + * the project workspace. Access via {@link #getTempPath(String)}.
  • + *
+ * + *

Usage

+ *
{@code
+ * // Get path to an input example file
+ * String input = ExampleFileUtil.getExamplePath("demo.xlsx");
+ * String template = ExampleFileUtil.getExamplePath("templates/simple.xlsx");
+ *
+ * // Get path for an output file (in temp directory)
+ * String output = ExampleFileUtil.getTempPath("result.xlsx");
+ * }
+ */ +public class ExampleFileUtil { + + public static final String EXAMPLE = "example"; + + public static String getPath() { + java.net.URL resource = ExampleFileUtil.class.getClassLoader().getResource(""); + if (resource == null) { + throw new IllegalStateException("Cannot find classpath root resource"); + } + return resource.getPath(); + } + + /** + * Get the path to a file in the example resource directory. + * + * @param fileName the file name relative to the example directory (e.g., "demo.xlsx" or "templates/simple.xlsx") + * @return the full path to the file + */ + public static String getExamplePath(String fileName) { + java.net.URL resource = ExampleFileUtil.class.getClassLoader().getResource(EXAMPLE + "/" + fileName); + if (resource != null) { + return resource.getPath(); + } + // Fallback to classpath root + example path + return getPath() + EXAMPLE + File.separator + fileName; + } + + /** + * Get the path to write output files in the system temp directory. + * + * @param fileName the output file name + * @return the full path to the output file in temp directory + */ + @SneakyThrows + public static String getTempPath(String fileName) { + return Files.createTempDirectory("fesod-sheet-examples").toAbsolutePath() + File.separator + fileName; + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/DownloadData.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/DownloadData.java similarity index 66% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/DownloadData.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/DownloadData.java index 0cfe55918..ce1e00058 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/DownloadData.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/DownloadData.java @@ -17,29 +17,29 @@ * under the License. */ -package org.apache.fesod.sheet.demo.web; +package org.apache.fesod.sheet.examples.web; import java.util.Date; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; /** - * 基础数据类 + * Data model for the web download example. * + *

Represents a row in the downloaded Excel file. In production, this would + * typically be populated from a database query or service call.

* - **/ + *

Headers are generated from field names by default ("string", "date", "doubleData"). + * Add {@code @ExcelProperty("Custom Header")} annotations for user-friendly column names.

+ * + * @see org.apache.fesod.sheet.examples.web.WebExampleController#download(javax.servlet.http.HttpServletResponse) + */ @Getter @Setter @EqualsAndHashCode public class DownloadData { - @ExcelProperty("字符串标题") private String string; - - @ExcelProperty("日期标题") private Date date; - - @ExcelProperty("数字标题") private Double doubleData; } diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/FesodApplication.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/FesodWebApplication.java similarity index 58% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/FesodApplication.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/FesodWebApplication.java index b20c65533..2063063b3 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/FesodApplication.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/FesodWebApplication.java @@ -17,15 +17,30 @@ * under the License. */ -package org.apache.fesod.sheet.demo.web; +package org.apache.fesod.sheet.examples.web; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +/** + * Spring Boot application entry point for the web examples. + * + *

Start this application to run the web-based Excel download/upload examples. + * The {@link WebExampleController} provides the following endpoints:

+ *
    + *
  • {@code GET /download} — Download an Excel file.
  • + *
  • {@code POST /upload} — Upload and parse an Excel file.
  • + *
+ * + *

Note: This application requires Spring Boot and Servlet API dependencies. + * It is provided as a reference for integrating Fesod into web applications.

+ * + * @see WebExampleController + */ @SpringBootApplication -public class FesodApplication { +public class FesodWebApplication { public static void main(String[] args) { - SpringApplication.run(FesodApplication.class, args); + SpringApplication.run(FesodWebApplication.class, args); } } diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/WriteWithColorTest.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/UploadDAO.java similarity index 50% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/WriteWithColorTest.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/UploadDAO.java index 463ca905b..373a9573b 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/WriteWithColorTest.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/UploadDAO.java @@ -17,32 +17,29 @@ * under the License. */ -package org.apache.fesod.sheet.demo.write; +package org.apache.fesod.sheet.examples.web; -import java.util.LinkedList; import java.util.List; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.Test; +import org.springframework.stereotype.Repository; /** - * Class for testing colors + * Mock DAO (Data Access Object) for web upload persistence. * + *

In production, this would be a real Spring {@code @Repository} with database + * operations (e.g., JDBC batch insert, MyBatis mapper, or JPA repository). + * The {@link UploadDataListener} calls {@code save()} every 100 rows. + * + *

Spring lifecycle: This is a Spring-managed singleton bean ({@code @Repository}). + * It's safe as a singleton because it holds no mutable state — unlike the listener, + * which must be created new for each upload.

+ * + * @see UploadDataListener + * @see org.apache.fesod.sheet.examples.web.WebExampleController */ -public class WriteWithColorTest { - - @Test - public void write() { - String fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx"; - FesodSheet.write(fileName, ColorDemoData.class).sheet("模板").doWrite(this::data); - System.out.println(fileName); - } +@Repository +public class UploadDAO { - private List data() { - List list = new LinkedList<>(); - for (int i = 0; i < 10; i++) { - list.add(new ColorDemoData("name" + i, i, "男")); - } - return list; + public void save(List list) { + // In actual use, you can use batch insert here. } } diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/UploadData.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/UploadData.java similarity index 69% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/UploadData.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/UploadData.java index e60db3e4e..fb83aa4ec 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/UploadData.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/UploadData.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.demo.web; +package org.apache.fesod.sheet.examples.web; import java.util.Date; import lombok.EqualsAndHashCode; @@ -25,10 +25,15 @@ import lombok.Setter; /** - * 基础数据类 + * Data model for the web upload example. * + *

Represents a row in the uploaded Excel file. Fesod automatically maps + * Excel columns to these fields during the upload read operation. + * Field types must be compatible with Excel cell types for automatic conversion.

* - **/ + * @see org.apache.fesod.sheet.examples.web.UploadDataListener + * @see org.apache.fesod.sheet.examples.web.WebExampleController#upload(MultipartFile) + */ @Getter @Setter @EqualsAndHashCode diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/UploadDataListener.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/UploadDataListener.java similarity index 51% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/UploadDataListener.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/UploadDataListener.java index 50f443bd1..4faf58a9c 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/UploadDataListener.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/UploadDataListener.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.demo.web; +package org.apache.fesod.sheet.examples.web; import com.alibaba.fastjson2.JSON; import java.util.List; @@ -27,74 +27,57 @@ import org.apache.fesod.sheet.read.listener.ReadListener; /** - * 模板的读取类 + * Listener for processing uploaded Excel data in a web environment. * + *

Scenario

+ *

When a user uploads an Excel file via a web form, this listener processes the rows + * in batches and persists them using the injected {@link UploadDAO}.

* + *

Design Pattern

+ *

Follows the same batch-save pattern as {@link org.apache.fesod.sheet.examples.read.listeners.DemoDataListener}: + * caches up to {@value #BATCH_COUNT} rows, then flushes to the database.

+ * + *

Spring Integration

+ *

This listener is NOT a Spring bean. It accepts a Spring-managed {@link UploadDAO} + * via constructor injection. Create a new instance per upload request:

+ *
{@code
+ * // In WebExampleController
+ * FesodSheet.read(file.getInputStream(), UploadData.class, new UploadDataListener(uploadDAO))
+ *     .sheet().doRead();
+ * }
+ * + * @see org.apache.fesod.sheet.examples.web.WebExampleController#upload(MultipartFile) + * @see UploadDAO */ -// 有个很重要的点 DemoDataListener 不能被spring管理,要每次读取excel都要new,然后里面用到spring可以构造方法传进去 @Slf4j public class UploadDataListener implements ReadListener { - /** - * 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收 - */ - private static final int BATCH_COUNT = 5; + private static final int BATCH_COUNT = 100; private List cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); - /** - * 假设这个是一个DAO,当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。 - */ private UploadDAO uploadDAO; - public UploadDataListener() { - // 这里是demo,所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数 - uploadDAO = new UploadDAO(); - } - - /** - * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来 - * - * @param uploadDAO - */ public UploadDataListener(UploadDAO uploadDAO) { this.uploadDAO = uploadDAO; } - /** - * 这个每一条数据解析都会来调用 - * - * @param data one row value. It is same as {@link AnalysisContext#readRowHolder()} - * @param context - */ @Override public void invoke(UploadData data, AnalysisContext context) { - log.info("解析到一条数据:{}", JSON.toJSONString(data)); + log.info("Parsed a data row: {}", JSON.toJSONString(data)); cachedDataList.add(data); - // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM if (cachedDataList.size() >= BATCH_COUNT) { saveData(); - // 存储完成清理 list cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); } } - /** - * 所有数据解析完成了 都会来调用 - * - * @param context - */ @Override public void doAfterAllAnalysed(AnalysisContext context) { - // 这里也要保存数据,确保最后遗留的数据也存储到数据库 saveData(); - log.info("所有数据解析完成!"); + log.info("All data parsing completed!"); } - /** - * 加上存储数据库 - */ private void saveData() { - log.info("{}条数据,开始存储数据库!", cachedDataList.size()); + log.info("{} records saved to database!", cachedDataList.size()); uploadDAO.save(cachedDataList); - log.info("存储数据库成功!"); } } diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/WebExampleController.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/WebExampleController.java new file mode 100644 index 000000000..e9aa4a39b --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/web/WebExampleController.java @@ -0,0 +1,153 @@ +/* + * 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 org.apache.fesod.sheet.examples.web; + +import java.io.IOException; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import javax.servlet.http.HttpServletResponse; +import org.apache.fesod.sheet.FesodSheet; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +/** + * Spring MVC controller demonstrating Excel download and upload in a web application. + * + *

Scenario

+ *

A typical enterprise application where users can: + *

    + *
  • Download — Export data as an Excel file via HTTP GET (browser download).
  • + *
  • Upload — Import data from an uploaded Excel file via HTTP POST (multipart form).
  • + *
+ * + *

Download Flow ({@code GET /download})

+ *
+ * Browser GET /download
+ *     │
+ *     ├─ Set Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
+ *     ├─ Set Content-Disposition: attachment;filename=test.xlsx
+ *     └─ FesodSheet.write(response.getOutputStream(), ...).sheet().doWrite(data)
+ *         └─ Excel bytes streamed directly to HTTP response (no temp file)
+ * 
+ * + *

Upload Flow ({@code POST /upload})

+ *
+ * Browser POST /upload (multipart/form-data)
+ *     │
+ *     └─ FesodSheet.read(file.getInputStream(), UploadData.class, listener).sheet().doRead()
+ *         └─ UploadDataListener processes rows in batches → saves to database
+ * 
+ * + *

Key Implementation Details

+ *
    + *
  • Streaming download: Writes directly to {@code response.getOutputStream()}, + * avoiding temporary files and enabling large exports.
  • + *
  • Filename encoding: Uses {@code URLEncoder} with UTF-8 for Chinese/special + * characters in the filename.
  • + *
  • Upload listener: Creates a new {@link UploadDataListener} per request with + * the injected {@link UploadDAO} (Spring-managed). The listener itself is NOT a bean.
  • + *
+ * + *

curl Test Commands

+ *
{@code
+ * # Download
+ * curl -o test.xlsx http://localhost:8080/download
+ *
+ * # Upload
+ * curl -F "file=@test.xlsx" http://localhost:8080/upload
+ * }
+ * + *

Related Examples

+ *
    + *
  • {@link org.apache.fesod.sheet.examples.write.BasicWriteExample} — Write to file.
  • + *
  • {@link org.apache.fesod.sheet.examples.read.BasicReadExample} — Read from file.
  • + *
+ * + * @see UploadDataListener + * @see DownloadData + */ +@Controller +public class WebExampleController { + + @Autowired + private UploadDAO uploadDAO; + + /** + * Downloads an Excel file as an HTTP response. + * + *

Writes directly to the response output stream — no temporary file is created. + * The response headers are configured for browser download with a UTF-8 encoded filename.

+ * + *

Important: Set {@code Content-Type} and {@code Content-Disposition} headers + * BEFORE writing to the output stream. Once bytes are written, headers cannot be modified.

+ * + * @param response the HTTP servlet response + * @throws IOException if writing to the output stream fails + */ + @GetMapping("download") + public void download(HttpServletResponse response) throws IOException { + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setCharacterEncoding("utf-8"); + String fileName = URLEncoder.encode("test", "UTF-8").replaceAll("\\+", "%20"); + response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); + + FesodSheet.write(response.getOutputStream(), DownloadData.class) + .sheet("Template") + .doWrite(data()); + } + + /** + * Uploads and parses an Excel file from a multipart form submission. + * + *

Uses {@code file.getInputStream()} to read the uploaded file directly from + * the multipart data, avoiding extra disk I/O. The {@link UploadDataListener} + * processes rows in batches and persists via the injected {@link UploadDAO}.

+ * + * @param file the uploaded multipart file + * @return "success" on completion + * @throws IOException if reading the input stream fails + */ + @PostMapping("upload") + @ResponseBody + public String upload(MultipartFile file) throws IOException { + FesodSheet.read(file.getInputStream(), UploadData.class, new UploadDataListener(uploadDAO)) + .sheet() + .doRead(); + return "success"; + } + + private List data() { + List list = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + DownloadData data = new DownloadData(); + data.setString("String" + i); + data.setDate(new Date()); + data.setDoubleData(0.56); + list.add(data); + } + return list; + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/BasicWriteExample.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/BasicWriteExample.java new file mode 100644 index 000000000..1f068a88b --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/BasicWriteExample.java @@ -0,0 +1,102 @@ +/* + * 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 org.apache.fesod.sheet.examples.write; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.examples.util.ExampleFileUtil; +import org.apache.fesod.sheet.examples.write.data.DemoData; + +/** + * Demonstrates the standard pattern for writing data to an Excel file. + * + *

Scenario

+ *

You have a list of Java objects (e.g., query results from a database) and want to + * export them to an Excel file with proper column headers. This is the most common + * write use case.

+ * + *

Key Concepts

+ *
    + *
  • {@link FesodSheet#write(String, Class)} — Creates a write builder. The class parameter + * defines the column headers (from {@code @ExcelProperty} annotations) and data types.
  • + *
  • {@code .sheet("Template")} — Creates a worksheet with the given tab name.
  • + *
  • {@code .doWrite(data)} — Terminal operation: writes all rows and closes the file. + * Handles header generation, type conversion, and resource cleanup automatically.
  • + *
+ * + *

Expected Output

+ *

An Excel file with one sheet named "Template" containing:

+ *
+ * | String Title | Date Title          | Number Title |
+ * |--------------|---------------------|--------------|
+ * | String0      | 2025-01-01 00:00:00 | 0.56         |
+ * | String1      | 2025-01-01 00:00:00 | 0.56         |
+ * | ...          | ...                 | ...          |
+ * | String9      | 2025-01-01 00:00:00 | 0.56         |
+ * 
+ * + *

Related Examples

+ *
    + *
  • {@link StyleWriteExample} — Add custom header/content styles (colors, fonts).
  • + *
  • {@link MergeWriteExample} — Merge cells during write.
  • + *
  • {@link ImageWriteExample} — Export images to Excel cells.
  • + *
  • {@link org.apache.fesod.sheet.examples.advanced.LargeFileWriteExample} + * — Write 100K+ rows with memory optimization.
  • + *
+ * + * @see FesodSheet#write(String, Class) + * @see DemoData + */ +@Slf4j +public class BasicWriteExample { + + public static void main(String[] args) { + basicWrite(); + } + + /** + * Writes 10 rows of demo data to an Excel file. + * + *

The output file is created in the system temp directory. + * Check the log output for the exact file path.

+ */ + public static void basicWrite() { + String fileName = ExampleFileUtil.getTempPath("basicWrite" + System.currentTimeMillis() + ".xlsx"); + + // Specify the class to write, then write to the first sheet. + FesodSheet.write(fileName, DemoData.class).sheet("Template").doWrite(data()); + log.info("Successfully wrote file: {}", fileName); + } + + private static List data() { + List list = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + DemoData data = new DemoData(); + data.setString("String" + i); + data.setDate(new Date()); + data.setDoubleData(0.56); + list.add(data); + } + return list; + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/ImageWriteExample.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/ImageWriteExample.java new file mode 100644 index 000000000..ba83155e2 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/ImageWriteExample.java @@ -0,0 +1,185 @@ +/* + * 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 org.apache.fesod.sheet.examples.write; + +import java.io.File; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.enums.CellDataTypeEnum; +import org.apache.fesod.sheet.examples.util.ExampleFileUtil; +import org.apache.fesod.sheet.examples.write.data.ImageDemoData; +import org.apache.fesod.sheet.metadata.data.ImageData; +import org.apache.fesod.sheet.metadata.data.WriteCellData; +import org.apache.fesod.sheet.util.FileUtils; + +/** + * Demonstrates exporting images to Excel cells using five different source types. + * + *

Scenario

+ *

You need to generate an Excel report containing images — for example, product photos + * in a catalog, user avatars in a report, or QR codes in an inventory sheet.

+ * + *

Five Image Source Types

+ *
+ * Type          | Field Type          | Use Case
+ * ──────────────|─────────────────────|──────────────────────────────────────────
+ * File          | File                | Local file on disk
+ * InputStream   | InputStream         | Classpath resource, servlet upload, etc.
+ * String path   | String              | File path (requires StringImageConverter)
+ * byte[]        | byte[]              | Pre-loaded binary data, generated images
+ * URL           | URL                 | Remote image (downloaded at write time)
+ * 
+ * + *

Advanced: Multiple Images per Cell ({@link WriteCellData})

+ *

Using {@code WriteCellData} you can:

+ *
    + *
  • Add multiple images to a single cell
  • + *
  • Combine text with images in the same cell
  • + *
  • Control image positioning with margins (top, right, bottom, left)
  • + *
  • Span images across adjacent cells using {@code relativeLastColumnIndex}
  • + *
+ * + *

Memory Considerations

+ *

Warning: All images are loaded into memory during write. For large volumes:

+ *
    + *
  • Upload images to cloud storage (e.g., AWS S3) and reference by URL.
  • + *
  • Compress images before embedding.
  • + *
  • Consider writing fewer images per batch.
  • + *
+ * + *

Expected Output

+ *

An Excel file with one row containing 6 columns, each showing the same image + * loaded from a different source. The last column contains two images with text, + * spanning into the adjacent cell.

+ * + *

Related Examples

+ *
    + *
  • {@link BasicWriteExample} — Simple data write.
  • + *
  • {@link StyleWriteExample} — Style customization.
  • + *
+ * + * @see ImageDemoData + * @see WriteCellData + * @see ImageData + */ +@Slf4j +public class ImageWriteExample { + + public static void main(String[] args) throws Exception { + imageWrite(); + } + + /** + * Writes images to Excel using all five source types plus advanced multi-image positioning. + * + *

The method demonstrates: + *

    + *
  1. Setting up five different image sources (File, InputStream, String, byte[], URL).
  2. + *
  3. Creating a {@link WriteCellData} with text + two images at custom positions.
  4. + *
  5. Using {@code relativeLastColumnIndex} to span an image across cells.
  6. + *
+ * + *

Troubleshooting: If image resources are inaccessible, XLSX format may error with + * "SXSSFWorkbook - Failed to dispose sheet". In that case, try XLS format instead.

+ * + * @throws Exception if file operations fail + */ + public static void imageWrite() throws Exception { + String fileName = ExampleFileUtil.getTempPath("imageWrite" + System.currentTimeMillis() + ".xlsx"); + + // Note: All images will be loaded into memory. For large volumes, consider: + // 1. Upload images to cloud storage (e.g., https://www.aliyun.com/product/oss) and use URLs + // 2. Use image compression tools like: https://github.com/coobird/thumbnailator + + String imagePath = ExampleFileUtil.getPath() + "example/sample-data" + File.separator + "img.jpg"; + try (InputStream inputStream = FileUtils.openInputStream(new File(imagePath))) { + List list = new ArrayList<>(); + ImageDemoData imageDemoData = new ImageDemoData(); + list.add(imageDemoData); + + // Five types of image export - in practice, choose only one method + imageDemoData.setByteArray(FileUtils.readFileToByteArray(new File(imagePath))); + imageDemoData.setFile(new File(imagePath)); + imageDemoData.setString(imagePath); + imageDemoData.setInputStream(inputStream); + imageDemoData.setUrl(new URL("https://poi.apache.org/images/project-header.png")); + + // Advanced example demonstrating: + // - Adding text to the cell in addition to images + // - Adding 2 images to the same cell + // - First image aligned to the left + // - Second image aligned to the right and spanning into adjacent cells + WriteCellData writeCellData = new WriteCellData<>(); + imageDemoData.setWriteCellDataFile(writeCellData); + // Can be set to EMPTY if no additional data is needed + writeCellData.setType(CellDataTypeEnum.STRING); + writeCellData.setStringValue("Additional text content"); + + // Can add multiple images to a single cell + List imageDataList = new ArrayList<>(); + ImageData imageData = new ImageData(); + imageDataList.add(imageData); + writeCellData.setImageDataList(imageDataList); + // Set image as binary data + imageData.setImage(FileUtils.readFileToByteArray(new File(imagePath))); + // Set image type + imageData.setImageType(ImageData.ImageType.PICTURE_TYPE_PNG); + // Top, Right, Bottom, Left margins + // Similar to CSS margin + // Note: Setting values too large (exceeding cell size) may cause repair prompts when opening. + // No perfect solution found yet. + imageData.setTop(5); + imageData.setRight(40); + imageData.setBottom(5); + imageData.setLeft(5); + + // Add second image + imageData = new ImageData(); + imageDataList.add(imageData); + writeCellData.setImageDataList(imageDataList); + imageData.setImage(FileUtils.readFileToByteArray(new File(imagePath))); + imageData.setImageType(ImageData.ImageType.PICTURE_TYPE_PNG); + imageData.setTop(5); + imageData.setRight(5); + imageData.setBottom(5); + imageData.setLeft(50); + // Position the image to span from current cell to the cell on its right + // Starting point is relative to current cell (0 - can be omitted) + imageData.setRelativeFirstRowIndex(0); + imageData.setRelativeFirstColumnIndex(0); + imageData.setRelativeLastRowIndex(0); + // The first 3 can be omitted. This one must be set - the ending position + // needs to move one column to the right relative to the current cell + // This means the image will cover the current cell and the next cell to its right + imageData.setRelativeLastColumnIndex(1); + + // Write data + FesodSheet.write(fileName, ImageDemoData.class).sheet().doWrite(list); + log.info("Successfully wrote image file: {}", fileName); + // If image resources are inaccessible, XLSX format may error: SXSSFWorkbook - Failed to dispose sheet + // Consider declaring as XLS format in such cases: + // FesodSheet.write(fileName, ImageDemoData.class).excelType(ExcelTypeEnum.XLS).sheet().doWrite(list); + } + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/MergeWriteExample.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/MergeWriteExample.java new file mode 100644 index 000000000..425d01eca --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/MergeWriteExample.java @@ -0,0 +1,129 @@ +/* + * 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 org.apache.fesod.sheet.examples.write; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.examples.util.ExampleFileUtil; +import org.apache.fesod.sheet.examples.write.data.DemoMergeData; +import org.apache.fesod.sheet.write.merge.LoopMergeStrategy; + +/** + * Demonstrates cell merging strategies when writing Excel files. + * + *

Scenario

+ *

You need to create an Excel report where certain cells are merged — for example, + * merging repeated category names in the first column, or creating summary rows. + * Fesod supports two approaches: annotation-based and strategy-based merging.

+ * + *

Approach 1: Annotation-Based ({@code @ContentLoopMerge})

+ *

Annotate a field in the data class with {@code @ContentLoopMerge(eachRow = N)} + * to automatically merge every N rows in that column. See {@link DemoMergeData}.

+ *
+ * Result (eachRow = 2):
+ * | String Title | Date Title          | Number Title |
+ * |--------------|---------------------|--------------|
+ * | String0      | 2025-01-01 00:00:00 | 0.56         |
+ * | (merged)     | 2025-01-01 00:00:00 | 0.56         |
+ * | String1      | 2025-01-01 00:00:00 | 0.56         |
+ * | (merged)     | 2025-01-01 00:00:00 | 0.56         |
+ * 
+ * + *

Approach 2: Strategy-Based ({@link LoopMergeStrategy})

+ *

Register a {@code LoopMergeStrategy(eachRow, columnIndex)} as a write handler. + * More flexible — can be configured at runtime and applied to any column.

+ *
{@code
+ * // Merge every 2 rows in column 0
+ * LoopMergeStrategy strategy = new LoopMergeStrategy(2, 0);
+ * FesodSheet.write(fileName, DemoMergeData.class)
+ *     .registerWriteHandler(strategy)
+ *     .sheet().doWrite(data);
+ * }
+ * + *

When to Use Which

+ *
    + *
  • Annotation — Simple, fixed merge patterns baked into the data class.
  • + *
  • Strategy — Dynamic merging, multiple merge rules, or merging based on data content.
  • + *
+ * + *

Related Examples

+ *
    + *
  • {@link StyleWriteExample} — Style customization.
  • + *
  • {@link BasicWriteExample} — Simple write without merging.
  • + *
+ * + * @see org.apache.fesod.sheet.annotation.write.style.ContentLoopMerge + * @see LoopMergeStrategy + * @see DemoMergeData + */ +@Slf4j +public class MergeWriteExample { + + public static void main(String[] args) { + mergeWrite(); + } + + /** + * Demonstrates both annotation-based and strategy-based cell merging. + * + *

Writes two separate files: + *

    + *
  1. Annotation merge — Uses {@code @ContentLoopMerge(eachRow = 2)} on the + * {@code string} field of {@link DemoMergeData}.
  2. + *
  3. Strategy merge — Registers a {@link LoopMergeStrategy} to merge every + * 2 rows in column 0.
  4. + *
+ * Both produce the same visual result but via different mechanisms.

+ */ + public static void mergeWrite() { + String fileName = ExampleFileUtil.getTempPath("mergeWrite" + System.currentTimeMillis() + ".xlsx"); + + // Method 1: Use annotations (see DemoMergeData) + FesodSheet.write(fileName, DemoMergeData.class) + .sheet("Annotation Merge") + .doWrite(data()); + log.info("Successfully wrote file: {}", fileName); + + // Method 2: Use a merge strategy + fileName = ExampleFileUtil.getTempPath("mergeWriteStrategy" + System.currentTimeMillis() + ".xlsx"); + // Merge every 2 rows in the 0th column. + LoopMergeStrategy loopMergeStrategy = new LoopMergeStrategy(2, 0); + FesodSheet.write(fileName, DemoMergeData.class) + .registerWriteHandler(loopMergeStrategy) + .sheet("Strategy Merge") + .doWrite(data()); + log.info("Successfully wrote file: {}", fileName); + } + + private static List data() { + List list = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + DemoMergeData data = new DemoMergeData(); + data.setString("String" + (i / 2)); // Same string for merged rows + data.setDate(new Date()); + data.setDoubleData(0.56); + list.add(data); + } + return list; + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/StyleWriteExample.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/StyleWriteExample.java new file mode 100644 index 000000000..6b36c2703 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/StyleWriteExample.java @@ -0,0 +1,117 @@ +/* + * 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 org.apache.fesod.sheet.examples.write; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.examples.util.ExampleFileUtil; +import org.apache.fesod.sheet.examples.write.data.DemoStyleData; + +/** + * Demonstrates how to customize header and content styles in Excel output. + * + *

Scenario

+ *

You're generating an Excel report that needs branded colors, custom font sizes, + * or specific cell formatting to match corporate style guides.

+ * + *

Key Concepts

+ *
    + *
  • Class-level annotations — Apply default styles to all columns: + *
      + *
    • {@code @HeadStyle} / {@code @HeadFontStyle} — Header row background color and font.
    • + *
    • {@code @ContentStyle} / {@code @ContentFontStyle} — Data row background color and font.
    • + *
    + *
  • + *
  • Field-level annotations — Override class-level styles for specific columns. + * In the example, the "String Title" column has distinct colors and a larger font + * than the other columns.
  • + *
  • Color values — Use Excel's indexed color system (0-63). Common values: + * 10 = dark green, 14 = dark teal, 17 = light yellow, 40 = light blue. + * See {@link org.apache.poi.ss.usermodel.IndexedColors} for the full palette.
  • + *
+ * + *

Style Hierarchy

+ *
+ * Field-level @HeadStyle / @ContentStyle
+ *     │ (if present, overrides class-level)
+ *     ↓
+ * Class-level @HeadStyle / @ContentStyle
+ *     │ (if present, overrides Fesod default)
+ *     ↓
+ * Fesod default styles
+ * 
+ * + *

Expected Output

+ *

An Excel file where: + *

    + *
  • Header row: dark green background (color 10), 20pt font for all columns, + * except "String Title" which has dark teal (14) and 30pt font.
  • + *
  • Content rows: light yellow background (color 17), 20pt font for all columns, + * except "String Title" which has light blue (40) and 30pt font.
  • + *
+ * + *

Related Examples

+ *
    + *
  • {@link BasicWriteExample} — Write with default styles.
  • + *
  • {@link MergeWriteExample} — Combine merging with styles.
  • + *
  • {@link org.apache.fesod.sheet.examples.write.handlers.CustomCellWriteHandler} + * — Programmatic style customization via handlers.
  • + *
+ * + * @see DemoStyleData + * @see org.apache.fesod.sheet.annotation.write.style.HeadStyle + * @see org.apache.fesod.sheet.annotation.write.style.ContentStyle + */ +@Slf4j +public class StyleWriteExample { + + public static void main(String[] args) { + styleWrite(); + } + + /** + * Writes an Excel file with custom header and content styles. + * + *

Styles are defined entirely through annotations on {@link DemoStyleData}. + * No programmatic style code is needed — Fesod reads the annotations and applies + * them automatically during write.

+ */ + public static void styleWrite() { + String fileName = ExampleFileUtil.getTempPath("styleWrite" + System.currentTimeMillis() + ".xlsx"); + + FesodSheet.write(fileName, DemoStyleData.class).sheet("Template").doWrite(data()); + log.info("Successfully wrote file: {}", fileName); + } + + private static List data() { + List list = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + DemoStyleData data = new DemoStyleData(); + data.setString("String" + i); + data.setDate(new Date()); + data.setDoubleData(0.56); + list.add(data); + } + return list; + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/DemoData.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/data/DemoData.java similarity index 67% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/DemoData.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/data/DemoData.java index bc0c31868..c191ab781 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/DemoData.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/data/DemoData.java @@ -17,23 +17,30 @@ * under the License. */ -package org.apache.fesod.sheet.demo.write; +package org.apache.fesod.sheet.examples.write.data; import java.util.Date; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; +import lombok.Data; import org.apache.fesod.sheet.annotation.ExcelIgnore; import org.apache.fesod.sheet.annotation.ExcelProperty; /** - * Basic data class + * Data model for the write examples, mapping Java fields to Excel columns. * + *

Identical structure to the read examples' DemoData, but uses Lombok's + * {@code @Data} for brevity (generates getters, setters, equals, hashCode, toString). + * The {@link ExcelProperty} annotations define column headers in the output file, + * while {@link ExcelIgnore} excludes the {@code ignore} field from the Excel output.

* - **/ -@Getter -@Setter -@EqualsAndHashCode + *

Generated Excel Headers

+ *
+ * | String Title | Date Title | Number Title |
+ * 
+ * + * @see ExcelProperty + * @see ExcelIgnore + */ +@Data public class DemoData { /** * String Title diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/DemoMergeData.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/data/DemoMergeData.java similarity index 57% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/DemoMergeData.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/data/DemoMergeData.java index 0e33c2071..afc8d2efc 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/DemoMergeData.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/data/DemoMergeData.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.demo.write; +package org.apache.fesod.sheet.examples.write.data; import java.util.Date; import lombok.EqualsAndHashCode; @@ -27,17 +27,33 @@ import org.apache.fesod.sheet.annotation.write.style.ContentLoopMerge; /** - * Style data class + * Data model demonstrating annotation-based cell merging. * + *

The {@code @ContentLoopMerge(eachRow = 2)} annotation on the {@code string} field + * tells Fesod to merge every 2 consecutive rows in that column. This is useful for + * category grouping in reports.

* - **/ + *

Merge Effect

+ *
+ * Row 1: | String0 | 2025-01-01 | 0.56 |  ← merged with row 2
+ * Row 2: | (merged)| 2025-01-01 | 0.56 |
+ * Row 3: | String1 | 2025-01-01 | 0.56 |  ← merged with row 4
+ * Row 4: | (merged)| 2025-01-01 | 0.56 |
+ * 
+ * + *

For runtime-configurable merging, use {@link org.apache.fesod.sheet.write.merge.LoopMergeStrategy} + * instead (see {@link org.apache.fesod.sheet.examples.write.MergeWriteExample}).

+ * + * @see ContentLoopMerge + * @see org.apache.fesod.sheet.write.merge.LoopMergeStrategy + */ @Getter @Setter @EqualsAndHashCode -// Merge columns 2-3 of rows 6-7 into one cell -// @OnceAbsoluteMerge(firstRowIndex = 5, lastRowIndex = 6, firstColumnIndex = 1, lastColumnIndex = 2) public class DemoMergeData { - // Merge this column every 2 rows + /** + * Merge cells every 2 rows in this column. + */ @ContentLoopMerge(eachRow = 2) @ExcelProperty("String Title") private String string; @@ -45,6 +61,6 @@ public class DemoMergeData { @ExcelProperty("Date Title") private Date date; - @ExcelProperty("Double Title") + @ExcelProperty("Number Title") private Double doubleData; } diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/DemoStyleData.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/data/DemoStyleData.java similarity index 61% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/DemoStyleData.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/data/DemoStyleData.java index 3b21486f3..1a4685648 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/DemoStyleData.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/data/DemoStyleData.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.demo.write; +package org.apache.fesod.sheet.examples.write.data; import java.util.Date; import lombok.EqualsAndHashCode; @@ -31,29 +31,47 @@ import org.apache.fesod.sheet.enums.poi.FillPatternTypeEnum; /** - * Style data class + * Data model demonstrating annotation-based style customization. * + *

Class-Level Styles (Default for All Columns)

+ *
    + *
  • Header: Solid fill, color 10 (dark green), font size 20pt
  • + *
  • Content: Solid fill, color 17 (light yellow), font size 20pt
  • + *
* - **/ + *

Field-Level Overrides ("String Title" Column Only)

+ *
    + *
  • Header: Solid fill, color 14 (dark teal), font size 30pt
  • + *
  • Content: Solid fill, color 40 (light blue), font size 30pt
  • + *
+ * + *

Style Annotations Reference

+ *
    + *
  • {@link HeadStyle} / {@link ContentStyle} — Cell background fill pattern and color. + * Use {@code fillPatternType = SOLID_FOREGROUND} with {@code fillForegroundColor} for + * solid background colors.
  • + *
  • {@link HeadFontStyle} / {@link ContentFontStyle} — Font properties like size, + * bold, italic, color, and font name.
  • + *
  • Field-level annotations override class-level annotations for that specific column.
  • + *
+ * + * @see HeadStyle + * @see HeadFontStyle + * @see ContentStyle + * @see ContentFontStyle + * @see org.apache.fesod.sheet.examples.write.StyleWriteExample + */ @Getter @Setter @EqualsAndHashCode -// Head background red @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 10) -// Head font size 20 @HeadFontStyle(fontHeightInPoints = 20) -// Content background green @ContentStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 17) -// Content font size 20 @ContentFontStyle(fontHeightInPoints = 20) public class DemoStyleData { - // String head background pink @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 14) - // String head font size 30 @HeadFontStyle(fontHeightInPoints = 30) - // String content background sky blue @ContentStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 40) - // String content font size 30 @ContentFontStyle(fontHeightInPoints = 30) @ExcelProperty("String Title") private String string; @@ -61,6 +79,6 @@ public class DemoStyleData { @ExcelProperty("Date Title") private Date date; - @ExcelProperty("Double Title") + @ExcelProperty("Number Title") private Double doubleData; } diff --git a/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/data/ImageDemoData.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/data/ImageDemoData.java new file mode 100644 index 000000000..562131247 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/data/ImageDemoData.java @@ -0,0 +1,91 @@ +/* + * 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 org.apache.fesod.sheet.examples.write.data; + +import java.io.File; +import java.io.InputStream; +import java.net.URL; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import org.apache.fesod.sheet.annotation.ExcelProperty; +import org.apache.fesod.sheet.annotation.write.style.ColumnWidth; +import org.apache.fesod.sheet.annotation.write.style.ContentRowHeight; +import org.apache.fesod.sheet.converters.string.StringImageConverter; +import org.apache.fesod.sheet.metadata.data.WriteCellData; + +/** + * Data model demonstrating five ways to export images to Excel cells. + * + *

Image Source Types

+ *

Each field represents a different way to provide image data to Fesod:

+ *
+ * Field             | Type                  | Description
+ * ───────────────────|───────────────────────|────────────────────────────────────────
+ * file              | File                  | Local file reference
+ * inputStream       | InputStream           | Stream from any source
+ * string            | String                | File path (requires StringImageConverter)
+ * byteArray         | byte[]                | Raw image bytes
+ * url               | URL                   | Remote image URL
+ * writeCellDataFile | WriteCellData<Void>   | Advanced: multiple images + text in one cell
+ * 
+ * + *

Layout Annotations

+ *
    + *
  • {@code @ContentRowHeight(100)} — Sets row height to 100 points for image visibility.
  • + *
  • {@code @ColumnWidth(100 / 8)} — Sets column width (in characters, ~12.5) for image cells.
  • + *
+ * + *

Memory Warning

+ *

All images are loaded into memory. For large volumes, consider: + *

    + *
  • Uploading to cloud storage and using URL references.
  • + *
  • Compressing images before export.
  • + *
+ * + * @see org.apache.fesod.sheet.examples.write.ImageWriteExample + * @see StringImageConverter + * @see WriteCellData + */ +@Getter +@Setter +@EqualsAndHashCode +@ContentRowHeight(100) +@ColumnWidth(100 / 8) +public class ImageDemoData { + private File file; + private InputStream inputStream; + /** + * If string type, a converter must be specified. + */ + @ExcelProperty(converter = StringImageConverter.class) + private String string; + + private byte[] byteArray; + /** + * Export by URL. + */ + private URL url; + + /** + * Export by file and set the export position. + */ + private WriteCellData writeCellDataFile; +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/CommentWriteHandler.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/handlers/CommentWriteHandler.java similarity index 55% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/CommentWriteHandler.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/handlers/CommentWriteHandler.java index af2063c31..75668c030 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/CommentWriteHandler.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/handlers/CommentWriteHandler.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.demo.write; +package org.apache.fesod.sheet.examples.write.handlers; import lombok.extern.slf4j.Slf4j; import org.apache.fesod.common.util.BooleanUtils; @@ -30,9 +30,37 @@ import org.apache.poi.xssf.usermodel.XSSFRichTextString; /** - * Custom handler. Add comment to the header of the first row. + * Custom {@link RowWriteHandler} that adds an Excel comment (note) to a header cell. * + *

Scenario

+ *

You want to add hover-able comments/notes to specific cells — for example, adding + * instructions or descriptions to column headers so end-users understand each column.

* + *

How It Works

+ *
    + *
  1. Implements {@link RowWriteHandler#afterRowDispose(RowWriteHandlerContext)}, + * which is called after each row is written.
  2. + *
  3. Checks if the row is a header row via {@code context.getHead()}.
  4. + *
  5. Creates a drawing patriarch on the sheet and adds a comment anchored + * to cell B1 (row 0, column 1).
  6. + *
+ * + *

Result

+ *

The second column header cell will show a small red triangle indicator. + * Hovering over it displays "Created a comment!".

+ * + *

Registration

+ *
{@code
+ * FesodSheet.write(fileName, DemoData.class)
+ *     .registerWriteHandler(new CommentWriteHandler())
+ *     .sheet().doWrite(data);
+ * }
+ * + *

Note: This handler uses Apache POI's XSSF-specific classes ({@code XSSFClientAnchor}, + * {@code XSSFRichTextString}), so it only works with {@code .xlsx} format.

+ * + * @see RowWriteHandler + * @see org.apache.poi.ss.usermodel.Comment */ @Slf4j public class CommentWriteHandler implements RowWriteHandler { @@ -42,12 +70,10 @@ public void afterRowDispose(RowWriteHandlerContext context) { if (BooleanUtils.isTrue(context.getHead())) { Sheet sheet = context.getWriteSheetHolder().getSheet(); Drawing drawingPatriarch = sheet.createDrawingPatriarch(); - // Create a comment in the first row, second column + // Create a comment in the first row, second column. Comment comment = drawingPatriarch.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) 1, 0, (short) 2, 1)); - // Input comment information - comment.setString(new XSSFRichTextString("Create comment!")); - // Add comment to cell object + comment.setString(new XSSFRichTextString("Created a comment!")); sheet.getRow(0).getCell(1).setCellComment(comment); } } diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/CustomCellWriteHandler.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/handlers/CustomCellWriteHandler.java similarity index 53% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/CustomCellWriteHandler.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/handlers/CustomCellWriteHandler.java index 01dfc4a33..0d26f53ae 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/CustomCellWriteHandler.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/handlers/CustomCellWriteHandler.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.demo.write; +package org.apache.fesod.sheet.examples.write.handlers; import lombok.extern.slf4j.Slf4j; import org.apache.fesod.common.util.BooleanUtils; @@ -29,9 +29,40 @@ import org.apache.poi.ss.usermodel.Hyperlink; /** - * Custom handler + * Custom {@link CellWriteHandler} that adds a hyperlink to the first header cell. * + *

Scenario

+ *

You want to customize individual cells after they are written — for example, + * adding hyperlinks, conditional formatting, or cell validation. The {@code CellWriteHandler} + * gives you access to the Apache POI {@link Cell} object for low-level customization.

* + *

How It Works

+ *
    + *
  1. Implements {@link CellWriteHandler#afterCellDispose(CellWriteHandlerContext)}, + * which is called after each cell (both header and content cells).
  2. + *
  3. Checks if the cell is a header cell ({@code context.getHead()}) in the first + * column ({@code cell.getColumnIndex() == 0}).
  4. + *
  5. Creates a URL hyperlink pointing to the Fesod GitHub repository and attaches + * it to the cell.
  6. + *
+ * + *

Result

+ *

The first column header cell becomes a clickable hyperlink to + * {@code https://github.com/apache/fesod}.

+ * + *

Registration

+ *
{@code
+ * FesodSheet.write(fileName, DemoData.class)
+ *     .registerWriteHandler(new CustomCellWriteHandler())
+ *     .sheet().doWrite(data);
+ * }
+ * + *

Handler Execution Order

+ *

Fesod calls write handlers in registration order. If multiple handlers modify + * the same cell, later handlers can override earlier ones.

+ * + * @see CellWriteHandler + * @see org.apache.poi.ss.usermodel.Hyperlink */ @Slf4j public class CustomCellWriteHandler implements CellWriteHandler { @@ -39,13 +70,12 @@ public class CustomCellWriteHandler implements CellWriteHandler { @Override public void afterCellDispose(CellWriteHandlerContext context) { Cell cell = context.getCell(); - // Can perform any operation on the cell here - log.info("Finished writing row {}, column {}", cell.getRowIndex(), cell.getColumnIndex()); + log.info("Row {}, Column {} write completed.", cell.getRowIndex(), cell.getColumnIndex()); if (BooleanUtils.isTrue(context.getHead()) && cell.getColumnIndex() == 0) { CreationHelper createHelper = context.getWriteSheetHolder().getSheet().getWorkbook().getCreationHelper(); Hyperlink hyperlink = createHelper.createHyperlink(HyperlinkType.URL); - hyperlink.setAddress("https://github.com/fast-excel/fastexcel"); + hyperlink.setAddress("https://github.com/apache/fesod"); cell.setHyperlink(hyperlink); } } diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/CustomSheetWriteHandler.java b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/handlers/CustomSheetWriteHandler.java similarity index 53% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/CustomSheetWriteHandler.java rename to fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/handlers/CustomSheetWriteHandler.java index 02c28ec25..6f14e3cbf 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/CustomSheetWriteHandler.java +++ b/fesod-examples/fesod-sheet-examples/src/main/java/org/apache/fesod/sheet/examples/write/handlers/CustomSheetWriteHandler.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.fesod.sheet.demo.write; +package org.apache.fesod.sheet.examples.write.handlers; import lombok.extern.slf4j.Slf4j; import org.apache.fesod.sheet.write.handler.SheetWriteHandler; @@ -28,19 +28,52 @@ import org.apache.poi.ss.util.CellRangeAddressList; /** - * Custom handler. Add dropdown to first column of first and second data rows, displaying "Test1", "Test2" + * Custom {@link SheetWriteHandler} that adds a dropdown validation list to a sheet. * + *

Scenario

+ *

You want to add data validation, conditional formatting, or other sheet-level + * customizations when a worksheet is first created. The {@code SheetWriteHandler} + * provides a hook into the sheet creation lifecycle.

* + *

How It Works

+ *
    + *
  1. Implements {@link SheetWriteHandler#afterSheetCreate(SheetWriteHandlerContext)}, + * called immediately after a new sheet is created.
  2. + *
  3. Creates a data validation constraint with explicit list values + * ({@code "Test1", "Test2"}).
  4. + *
  5. Applies the constraint to cells A2:A3 (rows 1-2, column 0).
  6. + *
+ * + *

Result

+ *

Cells A2 and A3 will show a dropdown arrow. Clicking it reveals the options + * "Test1" and "Test2". Entering other values triggers a validation error.

+ * + *

Registration

+ *
{@code
+ * FesodSheet.write(fileName, DemoData.class)
+ *     .registerWriteHandler(new CustomSheetWriteHandler())
+ *     .sheet().doWrite(data);
+ * }
+ * + *

Other Use Cases for SheetWriteHandler

+ *
    + *
  • Setting print areas or page breaks
  • + *
  • Freezing panes (freeze rows/columns)
  • + *
  • Adding auto-filters
  • + *
  • Setting sheet protection
  • + *
+ * + * @see SheetWriteHandler + * @see org.apache.poi.ss.usermodel.DataValidation */ @Slf4j public class CustomSheetWriteHandler implements SheetWriteHandler { @Override public void afterSheetCreate(SheetWriteHandlerContext context) { - log.info("Sheet {} write success.", context.getWriteSheetHolder().getSheetNo()); + log.info("Sheet {} write successful.", context.getWriteSheetHolder().getSheetNo()); - // Set range for first column, first and second data rows. Since the first row is head, the data is actually in - // the 2nd and 3rd rows. + // Add a dropdown list to the first column of the second and third rows. CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(1, 2, 0, 0); DataValidationHelper helper = context.getWriteSheetHolder().getSheet().getDataValidationHelper(); DataValidationConstraint constraint = helper.createExplicitListConstraint(new String[] {"Test1", "Test2"}); diff --git a/fesod-examples/fesod-sheet-examples/src/main/resources/application.properties b/fesod-examples/fesod-sheet-examples/src/main/resources/application.properties new file mode 100644 index 000000000..9afc34590 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/main/resources/application.properties @@ -0,0 +1,20 @@ +# +# 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. +# + +server.port=8080 diff --git a/fesod-examples/fesod-sheet-examples/src/main/resources/example/demo.xlsx b/fesod-examples/fesod-sheet-examples/src/main/resources/example/demo.xlsx new file mode 100644 index 000000000..89e43a71d Binary files /dev/null and b/fesod-examples/fesod-sheet-examples/src/main/resources/example/demo.xlsx differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/converter/img.jpg b/fesod-examples/fesod-sheet-examples/src/main/resources/example/sample-data/img.jpg similarity index 100% rename from fesod-examples/fesod-sheet-examples/src/test/resources/converter/img.jpg rename to fesod-examples/fesod-sheet-examples/src/main/resources/example/sample-data/img.jpg diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/list.xlsx b/fesod-examples/fesod-sheet-examples/src/main/resources/example/templates/list.xlsx similarity index 100% rename from fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/list.xlsx rename to fesod-examples/fesod-sheet-examples/src/main/resources/example/templates/list.xlsx diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/simple.xlsx b/fesod-examples/fesod-sheet-examples/src/main/resources/example/templates/simple.xlsx similarity index 100% rename from fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/simple.xlsx rename to fesod-examples/fesod-sheet-examples/src/main/resources/example/templates/simple.xlsx diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/logback.xml b/fesod-examples/fesod-sheet-examples/src/main/resources/logback.xml similarity index 84% rename from fesod-examples/fesod-sheet-examples/src/test/resources/logback.xml rename to fesod-examples/fesod-sheet-examples/src/main/resources/logback.xml index 6ef9578b8..b18f5687b 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/resources/logback.xml +++ b/fesod-examples/fesod-sheet-examples/src/main/resources/logback.xml @@ -20,16 +20,17 @@ --> - - - ${CONSOLE_LOG_PATTERN} + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n utf8 - + + + + diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/fill/FillTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/fill/FillTest.java deleted file mode 100644 index 1d65a91cf..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/fill/FillTest.java +++ /dev/null @@ -1,302 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.fill; - -import java.io.File; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.fesod.common.util.ListUtils; -import org.apache.fesod.common.util.MapUtils; -import org.apache.fesod.sheet.ExcelWriter; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.enums.WriteDirectionEnum; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.handler.SheetWriteHandler; -import org.apache.fesod.sheet.write.handler.context.SheetWriteHandlerContext; -import org.apache.fesod.sheet.write.metadata.WriteSheet; -import org.apache.fesod.sheet.write.metadata.fill.FillConfig; -import org.apache.fesod.sheet.write.metadata.fill.FillWrapper; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.util.CellRangeAddress; -import org.junit.jupiter.api.Test; - -/** - * Example of writing and filling data into Excel - */ -public class FillTest { - /** - * Simplest example of filling data - */ - @Test - public void simpleFill() { - // Template note: Use {} to indicate variables. If there are existing "{", "}" characters, use "\{", "\}" - // instead. - String templateFileName = - TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "simple.xlsx"; - - // Option 1: Fill based on an object - String fileName = TestFileUtil.getPath() + "simpleFill" + System.currentTimeMillis() + ".xlsx"; - // This will fill the first sheet, and the file stream will be automatically closed. - FillData fillData = new FillData(); - fillData.setName("Zhang San"); - fillData.setNumber(5.2); - FesodSheet.write(fileName).withTemplate(templateFileName).sheet().doFill(fillData); - - // Option 2: Fill based on a Map - fileName = TestFileUtil.getPath() + "simpleFill" + System.currentTimeMillis() + ".xlsx"; - // This will fill the first sheet, and the file stream will be automatically closed. - Map map = MapUtils.newHashMap(); - map.put("name", "Zhang San"); - map.put("number", 5.2); - FesodSheet.write(fileName).withTemplate(templateFileName).sheet().doFill(map); - } - - /** - * Example of filling a list - */ - @Test - public void listFill() { - // Template note: Use {} to indicate variables. If there are existing "{", "}" characters, use "\{", "\}" - // instead. - // When filling a list, note that {.} in the template indicates a list. - // If the object filling the list is a Map, it must contain all keys of the list, even if the data is null. Use - // map.put(key, null). - String templateFileName = - TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "list.xlsx"; - - // Option 1: Load all data into memory at once and fill - String fileName = TestFileUtil.getPath() + "listFill" + System.currentTimeMillis() + ".xlsx"; - // This will fill the first sheet, and the file stream will be automatically closed. - FesodSheet.write(fileName).withTemplate(templateFileName).sheet().doFill(data()); - - // Option 2: Fill in multiple passes, using file caching (saves memory) - fileName = TestFileUtil.getPath() + "listFill" + System.currentTimeMillis() + ".xlsx"; - try (ExcelWriter excelWriter = - FesodSheet.write(fileName).withTemplate(templateFileName).build()) { - WriteSheet writeSheet = FesodSheet.writerSheet().build(); - excelWriter.fill(data(), writeSheet); - excelWriter.fill(data(), writeSheet); - } - } - - /** - * Example of complex filling - */ - @Test - public void complexFill() { - // Template note: Use {} to indicate variables. If there are existing "{", "}" characters, use "\{", "\}" - // instead. - // {} represents a normal variable, {.} represents a list variable. - String templateFileName = - TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "complex.xlsx"; - - String fileName = TestFileUtil.getPath() + "complexFill" + System.currentTimeMillis() + ".xlsx"; - // Option 1 - try (ExcelWriter excelWriter = - FesodSheet.write(fileName).withTemplate(templateFileName).build()) { - WriteSheet writeSheet = FesodSheet.writerSheet().build(); - // Note: The forceNewRow parameter is used here. When writing a list, it will always create a new row, and - // the data below will be shifted down. Default is false, which will use the next row if available, - // otherwise create a new one. - // forceNewRow: If set to true, it will load all data into memory, so use it with caution. - // In short, if your template has a list and the list is not the last row, and there is data below that - // needs to be filled, you must set forceNewRow=true. However, this will consume a lot of memory. - // For large datasets where the list is not the last row, refer to the next example. - FillConfig fillConfig = - FillConfig.builder().forceNewRow(Boolean.TRUE).build(); - excelWriter.fill(data(), fillConfig, writeSheet); - excelWriter.fill(data(), fillConfig, writeSheet); - Map map = MapUtils.newHashMap(); - map.put("date", "2019-10-09 13:28:28"); - map.put("total", 1000); - excelWriter.fill(map, writeSheet); - } - } - - /** - * Example of complex filling with large datasets - *

- * The solution here is to ensure that the list in the template is the last row, and then append a table. For Excel 2003, there is no solution other than increasing memory. - */ - @Test - public void complexFillWithTable() { - // Template note: Use {} to indicate variables. If there are existing "{", "}" characters, use "\{", "\}" - // instead. - // {} represents a normal variable, {.} represents a list variable. - // Here, the template deletes the data after the list, i.e., the summary row. - String templateFileName = TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator - + "complexFillWithTable.xlsx"; - - String fileName = TestFileUtil.getPath() + "complexFillWithTable" + System.currentTimeMillis() + ".xlsx"; - - // Option 1 - try (ExcelWriter excelWriter = - FesodSheet.write(fileName).withTemplate(templateFileName).build()) { - WriteSheet writeSheet = FesodSheet.writerSheet().build(); - // Directly write data - excelWriter.fill(data(), writeSheet); - excelWriter.fill(data(), writeSheet); - - // Write data before the list - Map map = new HashMap(); - map.put("date", "2019-10-09 13:28:28"); - excelWriter.fill(map, writeSheet); - - // There is a summary after the list, which needs to be written manually. - // Here, we use a list for simplicity. You can also use an object. - List> totalListList = ListUtils.newArrayList(); - List totalList = ListUtils.newArrayList(); - totalListList.add(totalList); - totalList.add(null); - totalList.add(null); - totalList.add(null); - // Fourth column - totalList.add("Total:1000"); - // Note: Use write here, not fill. - excelWriter.write(totalListList, writeSheet); - // Overall, the writing is complex, but there is no better solution. Asynchronous writing to Excel does not - // support row deletion or movement, nor does it support writing comments, so this approach is used. - // The idea is to create a new sheet and copy data bit by bit. However, when adding rows to the list, the - // data in the columns below cannot be shifted. A better solution will be explored in the future. - } - } - - /** - * Example of horizontal filling - */ - @Test - public void horizontalFill() { - // Template note: Use {} to indicate variables. If there are existing "{", "}" characters, use "\{", "\}" - // instead. - // {} represents a normal variable, {.} represents a list variable. - String templateFileName = - TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "horizontal.xlsx"; - - String fileName = TestFileUtil.getPath() + "horizontalFill" + System.currentTimeMillis() + ".xlsx"; - // Option 1 - try (ExcelWriter excelWriter = - FesodSheet.write(fileName).withTemplate(templateFileName).build()) { - WriteSheet writeSheet = FesodSheet.writerSheet().build(); - FillConfig fillConfig = FillConfig.builder() - .direction(WriteDirectionEnum.HORIZONTAL) - .build(); - excelWriter.fill(data(), fillConfig, writeSheet); - excelWriter.fill(data(), fillConfig, writeSheet); - - Map map = new HashMap<>(); - map.put("date", "2019-10-09 13:28:28"); - excelWriter.fill(map, writeSheet); - } - } - - /** - * Example of composite filling with multiple lists - */ - @Test - public void compositeFill() { - // Template note: Use {} to indicate variables. If there are existing "{", "}" characters, use "\{", "\}" - // instead. - // {} represents a normal variable, {.} represents a list variable, {prefix.} prefix can distinguish different - // lists. - String templateFileName = - TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "composite.xlsx"; - - String fileName = TestFileUtil.getPath() + "compositeFill" + System.currentTimeMillis() + ".xlsx"; - - // Option 1 - try (ExcelWriter excelWriter = - FesodSheet.write(fileName).withTemplate(templateFileName).build()) { - WriteSheet writeSheet = FesodSheet.writerSheet().build(); - FillConfig fillConfig = FillConfig.builder() - .direction(WriteDirectionEnum.HORIZONTAL) - .build(); - // If there are multiple lists, the template must have {prefix.}. Here, the prefix is data1, and multiple - // lists must be wrapped with FillWrapper. - excelWriter.fill(new FillWrapper("data1", data()), fillConfig, writeSheet); - excelWriter.fill(new FillWrapper("data1", data()), fillConfig, writeSheet); - excelWriter.fill(new FillWrapper("data2", data()), writeSheet); - excelWriter.fill(new FillWrapper("data2", data()), writeSheet); - excelWriter.fill(new FillWrapper("data3", data()), writeSheet); - excelWriter.fill(new FillWrapper("data3", data()), writeSheet); - - Map map = new HashMap(); - map.put("date", new Date()); - - excelWriter.fill(map, writeSheet); - } - } - - /** - * Example of filling an Excel template with date formatting. - *

- * This method demonstrates how to fill an Excel template where date fields - * are already formatted in the template. The written data will automatically - * follow the predefined date format in the template. - */ - @Test - public void dateFormatFill() { - // Define the path to the template file. - // The template should have predefined date formatting. - String templateFileName = - TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "dateFormat.xlsx"; - - // Generate a new output file name with a timestamp to avoid overwriting. - String fileName = TestFileUtil.getPath() + "dateFormatFill" + System.currentTimeMillis() + ".xlsx"; - - // Fill the template with data. - // The dates in the data will be formatted according to the template's settings. - FesodSheet.write(fileName).withTemplate(templateFileName).sheet().doFill(data()); - } - - @Test - public void testFillSheetDispose() { - String templateFileName = - TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "simple.xlsx"; - String fileName = TestFileUtil.getPath() + "simpleFill" + System.currentTimeMillis() + ".xlsx"; - FillData fillData = new FillData(); - fillData.setName("Zhang San"); - fillData.setNumber(5.2); - FesodSheet.write(fileName) - .withTemplate(templateFileName) - .sheet() - .registerWriteHandler(new SheetWriteHandler() { - @Override - public void afterSheetDispose(SheetWriteHandlerContext context) { - Sheet sheet = context.getWriteSheetHolder().getSheet(); - sheet.addMergedRegionUnsafe(new CellRangeAddress(1, 2, 0, 1)); - } - }) - .doFill(fillData); - } - - private List data() { - List list = ListUtils.newArrayList(); - for (int i = 0; i < 10; i++) { - FillData fillData = new FillData(); - list.add(fillData); - fillData.setName("Zhang San"); - fillData.setNumber(5.2); - fillData.setDate(new Date()); - } - return list; - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/rare/WriteTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/rare/WriteTest.java deleted file mode 100644 index f47697e91..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/rare/WriteTest.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.rare; - -import java.io.File; -import java.util.Date; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.common.util.ListUtils; -import org.apache.fesod.sheet.ExcelWriter; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.demo.read.DemoData; -import org.apache.fesod.sheet.util.FileUtils; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.handler.RowWriteHandler; -import org.apache.fesod.sheet.write.handler.WorkbookWriteHandler; -import org.apache.fesod.sheet.write.handler.context.RowWriteHandlerContext; -import org.apache.fesod.sheet.write.handler.context.WorkbookWriteHandlerContext; -import org.apache.fesod.sheet.write.metadata.WriteSheet; -import org.apache.poi.ss.usermodel.Cell; -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.junit.jupiter.api.Test; - -/** - * Record some uncommon cases - * - * - */ -@Slf4j -public class WriteTest { - - /** - * Compress temporary files - * When exporting an Excel file in xlsx format, a temporary XML file will be generated, which can be quite large. - * If disk space is limited, you can compress these files. - * Note that compression consumes performance. - */ - @Test - public void compressedTemporaryFile() { - log.info("Temporary XML files are stored at: {}", FileUtils.getPoiFilesPath()); - File file = TestFileUtil.createNewFile("rare/compressedTemporaryFile" + System.currentTimeMillis() + ".xlsx"); - - // Specify which class to use for writing here - try (ExcelWriter excelWriter = FesodSheet.write(file, DemoData.class) - .registerWriteHandler(new WorkbookWriteHandler() { - - /** - * Intercept the Workbook creation completion event - * @param context - */ - @Override - public void afterWorkbookCreate(WorkbookWriteHandlerContext context) { - // Get the Workbook object - Workbook workbook = context.getWriteWorkbookHolder().getWorkbook(); - // Temporary files are only generated in SXSSFWorkbook mode - if (workbook instanceof SXSSFWorkbook) { - SXSSFWorkbook sxssfWorkbook = (SXSSFWorkbook) workbook; - // Enable temporary file compression. Note that this will consume CPU performance, but the - // temporary files will be smaller - sxssfWorkbook.setCompressTempFiles(true); - } - } - }) - .build()) { - // Note that the same sheet should only be created once - WriteSheet writeSheet = FesodSheet.writerSheet("Template").build(); - // 100,000 data entries to ensure sufficient space - for (int i = 0; i < 10000; i++) { - // Query data from the database page by page. Here you can query data for each page from the database - List data = data(); - excelWriter.write(data, writeSheet); - } - log.info("Writing completed, preparing to migrate and compress files."); - } - } - - /** - * Write data to a specified cell - */ - @Test - public void specifiedCellWrite() { - File file = TestFileUtil.createNewFile("rare/specifiedCellWrite" + System.currentTimeMillis() + ".xlsx"); - - // It is necessary to distinguish whether it is before or after the last row - // The reason for the distinction is: Excel can only move forward, and only 100 rows are stored in memory. The - // afterRowDispose event is called after each row is written, so modifying a row requires intercepting this - // event - // If it is after the last row, since there will be no more data afterwards, just intercept the - // afterWorkbookDispose event and write the data when the Excel file is almost done - FesodSheet.write(file, DemoData.class) - // Writing value before the last row - .registerWriteHandler(new RowWriteHandler() { - @Override - public void afterRowDispose(RowWriteHandlerContext context) { - if (context.getRow().getRowNum() == 2) { - Cell cell = context.getRow().getCell(2); - if (cell == null) { - cell = context.getRow().createCell(2); - } - cell.setCellValue("Test data for the second row"); - } - } - }) - // Writing value after the last row - .registerWriteHandler(new WorkbookWriteHandler() { - @Override - public void afterWorkbookDispose(WorkbookWriteHandlerContext context) { - Workbook workbook = context.getWriteWorkbookHolder().getWorkbook(); - Sheet sheet = workbook.getSheetAt(0); - Row row = sheet.getRow(99); - if (row == null) { - row = sheet.createRow(99); - } - Cell cell = row.getCell(2); - if (cell == null) { - cell = row.createCell(2); - } - cell.setCellValue("Test data for row 99"); - } - }) - .sheet("Template") - .doWrite(data()); - - log.info("Writing to file completed:{}", file); - } - - private List data() { - List list = ListUtils.newArrayList(); - for (int i = 0; i < 10; i++) { - DemoData data = new DemoData(); - data.setString("String" + i); - data.setDate(new Date()); - data.setDoubleData(0.56); - list.add(data); - } - return list; - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/CellDataDemoHeadDataListener.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/CellDataDemoHeadDataListener.java deleted file mode 100644 index f648a25a4..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/CellDataDemoHeadDataListener.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.read; - -import com.alibaba.fastjson2.JSON; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.common.util.ListUtils; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.read.listener.ReadListener; - -/** - * Read header - * - * - */ -@Slf4j -public class CellDataDemoHeadDataListener implements ReadListener { - /** - * Store data to database every 5 records. In actual use, it can be 100 records, then clear the list to facilitate memory recycling - */ - private static final int BATCH_COUNT = 100; - - private List cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); - - @Override - public void invoke(CellDataReadDemoData data, AnalysisContext context) { - log.info("Parsed one record: {}", JSON.toJSONString(data)); - if (cachedDataList.size() >= BATCH_COUNT) { - saveData(); - cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); - } - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - saveData(); - log.info("All data parsing completed!"); - } - - /** - * Save data to database - */ - private void saveData() { - log.info("{} records, starting to save to database!", cachedDataList.size()); - log.info("Successfully saved to database!"); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/CellDataReadDemoData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/CellDataReadDemoData.java deleted file mode 100644 index 432d069a2..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/CellDataReadDemoData.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.read; - -import java.util.Date; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.metadata.data.CellData; - -/** - * Basic data class. The order here is consistent with the order in Excel - * - * - **/ -@Getter -@Setter -@EqualsAndHashCode -public class CellDataReadDemoData { - private CellData string; - // Note that although this is a date, the type stored is number because excel stores it as number - private CellData date; - private CellData doubleData; - // This may not be perfectly retrieved. Some formulas are dependent and may not be read. This issue will be fixed - // later - private CellData formulaValue; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/ConverterData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/ConverterData.java deleted file mode 100644 index e8d67e74d..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/ConverterData.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.read; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; -import org.apache.fesod.sheet.annotation.format.DateTimeFormat; -import org.apache.fesod.sheet.annotation.format.NumberFormat; - -/** - * Basic data class. The order here is consistent with the order in the Excel file. - * - * - **/ -@Getter -@Setter -@EqualsAndHashCode -public class ConverterData { - - /** - * I use a custom converter. No matter what is passed from the database, I prepend "Custom:". - */ - @ExcelProperty(converter = CustomStringStringConverter.class) - private String string; - - /** - * I use a string to receive the date so that it can be formatted. I want to receive the date in the format of yyyy-MM-dd HH:mm:ss. - */ - @DateTimeFormat("yyyy-MM-dd HH:mm:ss") - private String date; - - /** - * I want to receive a number in percentage format. - */ - @NumberFormat("#.##%") - private String doubleData; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/ConverterDataListener.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/ConverterDataListener.java deleted file mode 100644 index 127574947..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/ConverterDataListener.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.read; - -import com.alibaba.fastjson2.JSON; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.common.util.ListUtils; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.read.listener.ReadListener; - -/** - * Template data reading class - * - * - */ -@Slf4j -public class ConverterDataListener implements ReadListener { - - /** - * Save to the database every 5 records. In actual use, you might use 100 records, - * then clear the list to facilitate memory recycling. - */ - private static final int BATCH_COUNT = 5; - - private List cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); - - @Override - public void invoke(ConverterData data, AnalysisContext context) { - log.info("Parsed a piece of data: {}", JSON.toJSONString(data)); - cachedDataList.add(data); - if (cachedDataList.size() >= BATCH_COUNT) { - saveData(); - cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); - } - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - saveData(); - log.info("All data has been parsed and processed!"); - } - - /** - * Simulate saving data to the database - */ - private void saveData() { - log.info("Saving {} records to the database!", cachedDataList.size()); - log.info("Data saved to the database successfully!"); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoChainAccessorsData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoChainAccessorsData.java deleted file mode 100644 index 24e45ed20..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoChainAccessorsData.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.read; - -import java.util.Date; -import lombok.Data; -import lombok.experimental.Accessors; - -/** - * 基础数据类.这里的排序和excel里面的排序一致 - * - * - **/ -@Data -@Accessors(chain = true) -public class DemoChainAccessorsData { - private String string; - private Date date; - private Double doubleData; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoCompatibleHeaderDataListener.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoCompatibleHeaderDataListener.java deleted file mode 100644 index 064d4b3b4..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoCompatibleHeaderDataListener.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.read; - -import com.alibaba.fastjson2.JSON; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.common.util.ListUtils; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.apache.fesod.sheet.metadata.data.ReadCellData; - -/** - * Listener to read headers with compatibility for both Chinese and English. - */ -@Slf4j -public class DemoCompatibleHeaderDataListener extends AnalysisEventListener { - - /** - * Store data in batches of 100. In practice, you can adjust this number based on your needs. - * After storing, clear the list to facilitate memory recovery. - */ - private static final int BATCH_COUNT = 100; - - /** - * Map various header names to their corresponding annotation header information. - */ - private final Map headerMapping = new HashMap<>(8); - - /** - * Cache data in a list. - */ - private List cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); - - { - // Initialize the header mapping with examples. - headerMapping.put("字符串标题", "String"); - headerMapping.put("日期标题", "Date"); - headerMapping.put("数字标题", "DoubleData"); - } - - /** - * This method will be called for each row of headers. - * - * @param headMap A map containing the header information. - * @param context The analysis context. - */ - @Override - public void invokeHead(Map> headMap, AnalysisContext context) { - log.info("Parsed one header row:{}", JSON.toJSONString(headMap)); - headMap.forEach((key, value) -> { - // Here, a header mapping relationship is established. You can customize this logic as needed, - // such as case conversion, suffix removal, space deletion, etc. - String stringValue = value.getStringValue(); - value.setStringValue(headerMapping.getOrDefault(stringValue, stringValue)); - }); - } - - /** - * This method is called for each parsed data row. - * - * @param data One row of data. It is the same as {@link AnalysisContext#readRowHolder()}. - * @param context The analysis context. - */ - @Override - public void invoke(DemoCompatibleHeaderData data, AnalysisContext context) { - log.info("Parsed one data row:{}", JSON.toJSONString(data)); - cachedDataList.add(data); - // When the cached data reaches BATCH_COUNT, store it to prevent OOM issues with large datasets. - if (cachedDataList.size() >= BATCH_COUNT) { - saveData(); - // Clear the list after storage. - cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); - } - } - - /** - * Called when all data has been analyzed. - * - * @param context The analysis context. - */ - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - saveData(); - log.info("All data parsing completed!"); - } - - /** - * Simulates saving data to a database. - */ - private void saveData() { - log.info("{} rows of data, starting to save to the database!", cachedDataList.size()); - log.info("Data saved successfully to the database!"); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoData.java deleted file mode 100644 index ce90bf84b..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoData.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.read; - -import java.util.Date; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; - -/** - * 基础数据类.这里的排序和excel里面的排序一致 - * - * - **/ -@Getter -@Setter -@EqualsAndHashCode -public class DemoData { - private String string; - private Date date; - private Double doubleData; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoDataAnother.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoDataAnother.java deleted file mode 100644 index ec9b41fc0..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoDataAnother.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.read; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; - -@Getter -@Setter -@EqualsAndHashCode -@ToString -public class DemoDataAnother { - private String strA; - private String strB; - private String strC; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoDataListener.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoDataListener.java deleted file mode 100644 index d1574de19..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoDataListener.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.read; - -import com.alibaba.fastjson2.JSON; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.common.util.ListUtils; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.read.listener.ReadListener; - -/** - * Template reading class - * - * - */ -// An important point is that DemoDataListener should not be managed by Spring. -// It needs to be newly created each time an Excel file is read. -// If Spring is used inside, it can be passed through the constructor. -@Slf4j -public class DemoDataListener implements ReadListener { - - /** - * Store data in the database every 5 records. In actual use, it can be 100 records, - * and then clear the list to facilitate memory recycling. - */ - private static final int BATCH_COUNT = 100; - /** - * Cached data - */ - private List cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); - /** - * Assume this is a DAO. Of course, if there is business logic, this can also be a service. - * If the data does not need to be stored, this object is useless. - */ - private DemoDAO demoDAO; - - public DemoDataListener() { - // This is a demo, so a new instance is created here. In actual use with Spring, - // please use the constructor with parameters below. - demoDAO = new DemoDAO(); - } - - /** - * If Spring is used, please use this constructor. When creating a Listener, the class managed by Spring needs to be passed in. - * - * @param demoDAO - */ - public DemoDataListener(DemoDAO demoDAO) { - this.demoDAO = demoDAO; - } - - /** - * This method will be called for each data parsed. - * - * @param data one row value. It is same as {@link AnalysisContext#readRowHolder()} - * @param context - */ - @Override - public void invoke(DemoData data, AnalysisContext context) { - log.info("Parsed one row of data: {}", JSON.toJSONString(data)); - cachedDataList.add(data); - // When the number of records reaches BATCH_COUNT, the data needs to be stored in the database to prevent tens - // of - // thousands of records from being held in memory, which can easily cause OutOfMemoryError (OOM). - if (cachedDataList.size() >= BATCH_COUNT) { - saveData(); - // Clear the list after storage - cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); - } - } - - /** - * This method will be called after all data has been parsed. - * - * @param context - */ - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - // Data needs to be saved here to ensure that any remaining data is stored in the database. - saveData(); - log.info("All data has been parsed!"); - } - - /** - * Store data in the database - */ - private void saveData() { - log.info("{} records are being stored in the database!", cachedDataList.size()); - demoDAO.save(cachedDataList); - log.info("Data has been successfully stored in the database!"); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoExtraListener.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoExtraListener.java deleted file mode 100644 index cade0789d..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoExtraListener.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.read; - -import com.alibaba.fastjson2.JSON; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.metadata.CellExtra; -import org.apache.fesod.sheet.read.listener.ReadListener; -import org.junit.jupiter.api.Assertions; - -/** - * Listener to read cell comments, hyperlinks, and merged cells. - * - * - **/ -@Slf4j -public class DemoExtraListener implements ReadListener { - - @Override - public void invoke(DemoExtraData data, AnalysisContext context) {} - - @Override - public void doAfterAllAnalysed(AnalysisContext context) {} - - @Override - public void extra(CellExtra extra, AnalysisContext context) { - log.info("Read an extra piece of information: {}", JSON.toJSONString(extra)); - switch (extra.getType()) { - case COMMENT: - log.info( - "The extra information is a comment, at rowIndex:{}, columnIndex:{}, content:{}", - extra.getRowIndex(), - extra.getColumnIndex(), - extra.getText()); - break; - case HYPERLINK: - if ("Sheet1!A1".equals(extra.getText())) { - log.info( - "The extra information is a hyperlink, at rowIndex:{}, columnIndex:{}, content:{}", - extra.getRowIndex(), - extra.getColumnIndex(), - extra.getText()); - } else if ("Sheet2!A1".equals(extra.getText())) { - log.info( - "The extra information is a hyperlink, covering a range, firstRowIndex:{}, firstColumnIndex:{}, " - + "lastRowIndex:{}, lastColumnIndex:{}, content:{}", - extra.getFirstRowIndex(), - extra.getFirstColumnIndex(), - extra.getLastRowIndex(), - extra.getLastColumnIndex(), - extra.getText()); - } else { - Assertions.fail("Unknown hyperlink!"); - } - break; - case MERGE: - log.info( - "The extra information is a merged cell, covering a range, firstRowIndex:{}, firstColumnIndex:{}, " - + "lastRowIndex:{}, lastColumnIndex:{}", - extra.getFirstRowIndex(), - extra.getFirstColumnIndex(), - extra.getLastRowIndex(), - extra.getLastColumnIndex()); - break; - default: - } - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoHeadDataListener.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoHeadDataListener.java deleted file mode 100644 index e06b90d58..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoHeadDataListener.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.read; - -import com.alibaba.fastjson2.JSON; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.common.util.ListUtils; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.exception.ExcelDataConvertException; -import org.apache.fesod.sheet.metadata.data.ReadCellData; -import org.apache.fesod.sheet.read.listener.ReadListener; - -/** - * Reading headers - * - * - */ -@Slf4j -public class DemoHeadDataListener implements ReadListener { - - /** - * Save to the database every 5 records. In actual use, you might use 100 records, - * then clear the list to facilitate memory recycling. - */ - private static final int BATCH_COUNT = 5; - - private List cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); - - /** - * This method is called when a conversion exception or other exceptions occur. - * Throwing an exception will stop the reading process. If no exception is thrown here, - * the reading will continue to the next row. - * - * @param exception The exception that occurred. - * @param context The analysis context. - * @throws Exception If an exception is thrown to stop reading. - */ - @Override - public void onException(Exception exception, AnalysisContext context) { - log.error("Parsing failed, but continue parsing the next row: {}", exception.getMessage()); - if (exception instanceof ExcelDataConvertException) { - ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception; - log.error( - "Row {}, Column {} parsing exception, data is: {}", - excelDataConvertException.getRowIndex(), - excelDataConvertException.getColumnIndex(), - excelDataConvertException.getCellData()); - } - } - - /** - * This method is called for each header row. - * - * @param headMap The header data as a map. - * @param context The analysis context. - */ - @Override - public void invokeHead(Map> headMap, AnalysisContext context) { - log.info("Parsed a header row: {}", JSON.toJSONString(headMap)); - // If you want to convert it to a Map: - // Solution 1: Do not implement ReadListener, but extend AnalysisEventListener. - // Solution 2: Call ConverterUtils.convertToStringMap(headMap, context) to convert automatically. - } - - @Override - public void invoke(DemoData data, AnalysisContext context) { - log.info("Parsed a piece of data: {}", JSON.toJSONString(data)); - if (cachedDataList.size() >= BATCH_COUNT) { - saveData(); - cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); - } - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - saveData(); - log.info("All data has been parsed and processed!"); - } - - /** - * Simulate saving data to the database. - */ - private void saveData() { - log.info("Saving {} records to the database!", cachedDataList.size()); - log.info("Data saved to the database successfully!"); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/GenericHeaderTypeDataListener.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/GenericHeaderTypeDataListener.java deleted file mode 100644 index 6dd9b9a02..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/GenericHeaderTypeDataListener.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.read; - -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.read.listener.ReadListener; - -/** - * A data listener example that specifies the header type through generics. - * - * @param - */ -@Slf4j -public class GenericHeaderTypeDataListener implements ReadListener { - - private final Class headerClass; - - private GenericHeaderTypeDataListener(Class headerClass) { - this.headerClass = headerClass; - } - - @Override - public void invoke(T data, AnalysisContext context) { - log.info("data:{}", data); - // Execute business logic - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - // Perform cleanup tasks - } - - public static GenericHeaderTypeDataListener build(Class excelHeaderClass) { - return new GenericHeaderTypeDataListener<>(excelHeaderClass); - } - - public Class getHeaderClass() { - return headerClass; - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/IndexOrNameDataListener.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/IndexOrNameDataListener.java deleted file mode 100644 index 0335c0456..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/IndexOrNameDataListener.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.read; - -import com.alibaba.fastjson2.JSON; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.common.util.ListUtils; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; - -/** - * Template reading class - * - * - */ -@Slf4j -public class IndexOrNameDataListener extends AnalysisEventListener { - - /** - * Store data in the database every 5 records. In actual use, it can be 100 records, - * and then clear the list to facilitate memory recycling. - */ - private static final int BATCH_COUNT = 5; - - private List cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); - - @Override - public void invoke(IndexOrNameData data, AnalysisContext context) { - log.info("Parsed one row of data: {}", JSON.toJSONString(data)); - cachedDataList.add(data); - if (cachedDataList.size() >= BATCH_COUNT) { - saveData(); - cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); - } - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - saveData(); - log.info("All data has been parsed!"); - } - - /** - * Store data in the database - */ - private void saveData() { - log.info("{} records are being stored in the database!", cachedDataList.size()); - log.info("Data has been successfully stored in the database!"); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/ReadTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/ReadTest.java deleted file mode 100644 index aba7545e8..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/ReadTest.java +++ /dev/null @@ -1,454 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.read; - -import com.alibaba.fastjson2.JSON; -import java.io.File; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.common.util.ListUtils; -import org.apache.fesod.sheet.ExcelReader; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.annotation.ExcelProperty; -import org.apache.fesod.sheet.annotation.format.DateTimeFormat; -import org.apache.fesod.sheet.annotation.format.NumberFormat; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.converters.DefaultConverterLoader; -import org.apache.fesod.sheet.enums.CellExtraTypeEnum; -import org.apache.fesod.sheet.read.listener.PageReadListener; -import org.apache.fesod.sheet.read.listener.ReadListener; -import org.apache.fesod.sheet.read.metadata.ReadSheet; -import org.apache.fesod.sheet.read.metadata.holder.csv.CsvReadWorkbookHolder; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; - -/** - * Common approaches for reading Excel files - * - * - */ -@Slf4j -public class ReadTest { - - /** - * Simplest way to read - *

- * 1. Create an entity class corresponding to the Excel data structure. Refer to {@link DemoData}. - *

- * 2. Since Fesod reads Excel files row by row, you need to create a callback listener for each row. Refer to {@link DemoDataListener}. - *

- * 3. Directly read the file. - */ - @Test - public void simpleRead() { - // Approach 1: JDK8+, no need to create a separate DemoDataListener - // since: 3.0.0-beta1 - String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx"; - // Specify the class to read the data, then read the first sheet. The file stream will be automatically closed. - // By default, it reads 100 rows at a time. You can process the data directly. - // The number of rows to read can be set in the constructor of `PageReadListener`. - FesodSheet.read(fileName, DemoData.class, new PageReadListener(dataList -> { - for (DemoData demoData : dataList) { - log.info("Reading a row of data: {}", JSON.toJSONString(demoData)); - } - })) - .numRows(2) - .sheet() - .doRead(); - - // Approach 2: - // Anonymous inner class, no need to create a separate DemoDataListener - fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx"; - // Specify the class to read the data, then read the first sheet. The file stream will be automatically closed. - FesodSheet.read(fileName, DemoData.class, new ReadListener() { - /** - * Batch size for caching data - */ - public static final int BATCH_COUNT = 100; - /** - * Temporary storage - */ - private List cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); - - @Override - public void invoke(DemoData data, AnalysisContext context) { - cachedDataList.add(data); - if (cachedDataList.size() >= BATCH_COUNT) { - saveData(); - // Clear the list after saving - cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); - } - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - saveData(); - } - - /** - * Simulate saving data to the database - */ - private void saveData() { - log.info("Saving {} rows of data to the database!", cachedDataList.size()); - log.info("Data saved successfully!"); - } - }) - .sheet() - .doRead(); - - // Important note: DemoDataListener should not be managed by Spring. It needs to be instantiated every time you - // read an Excel file. - // Approach 3: - fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx"; - // Specify the class to read the data, then read the first sheet. The file stream will be automatically closed. - FesodSheet.read(fileName, DemoData.class, new DemoDataListener()) - .sheet() - .doRead(); - - // Approach 4 - fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx"; - // One reader per file - try (ExcelReader excelReader = FesodSheet.read(fileName, DemoData.class, new DemoDataListener()) - .build()) { - // Build a sheet. You can specify the name or index. - ReadSheet readSheet = FesodSheet.readSheet(0).build(); - readSheet.setNumRows(2); - // Read a single sheet - excelReader.read(readSheet); - } - } - - @Test - public void genericHeaderTypeRead() { - String fileName = TestFileUtil.getPath() + "demo" + File.separator + "generic-demo.xlsx"; - // Simulate obtaining the Excel header's Class object through any possible means - Class excelHeaderClass = DemoDataAnother.class; - FesodSheet.read(fileName, excelHeaderClass, GenericHeaderTypeDataListener.build(excelHeaderClass)) - .sheet() - .doRead(); - } - - /** - * Specify column indexes or names - *

- * 1. Create an entity class corresponding to the Excel data structure and use the {@link ExcelProperty} annotation. Refer to {@link IndexOrNameData}. - *

- * 2. Since Fesod reads Excel files row by row, you need to create a callback listener for each row. Refer to {@link IndexOrNameDataListener}. - *

- * 3. Directly read the file. - */ - @Test - public void indexOrNameRead() { - String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx"; - // By default, read the first sheet - FesodSheet.read(fileName, IndexOrNameData.class, new IndexOrNameDataListener()) - .numRows(1) - .sheet() - .doRead(); - } - - /** - * Read multiple or all sheets. Note that a sheet cannot be read multiple times; multiple reads require re-reading the file. - *

- * 1. Create an entity class corresponding to the Excel data structure. Refer to {@link DemoData}. - *

- * 2. Since Fesod reads Excel files row by row, you need to create a callback listener for each row. Refer to {@link DemoDataListener}. - *

- * 3. Directly read the file. - */ - @Test - public void repeatedRead() { - String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx"; - // Read all sheets - // Note: The `doAfterAllAnalysed` method of DemoDataListener will be called once after each sheet is read. - // All sheets will write to the same DemoDataListener. - FesodSheet.read(fileName, DemoData.class, new DemoDataListener()).doReadAll(); - - // Read some sheets - fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx"; - - // Method 1 - try (ExcelReader excelReader = FesodSheet.read(fileName).build()) { - // For simplicity, the same head and Listener are registered here. - // In actual use, different Listeners must be used. - ReadSheet readSheet1 = FesodSheet.readSheet(0) - .head(DemoData.class) - .registerReadListener(new DemoDataListener()) - .build(); - ReadSheet readSheet2 = FesodSheet.readSheet(1) - .head(DemoData.class) - .registerReadListener(new DemoDataListener()) - .build(); - // Note: All sheets (sheet1 and sheet2) must be passed together. - // Otherwise, for Excel 2003 files, the same sheet may be read multiple times, wasting performance. - excelReader.read(readSheet1, readSheet2); - } - } - - /** - * Date, number, or custom format conversion - *

- * Default converter: {@link DefaultConverterLoader#loadDefaultReadConverter()} - *

- * 1. Create an entity class corresponding to the Excel data structure. Refer to {@link ConverterData}. - * Annotations such as {@link DateTimeFormat}, {@link NumberFormat}, or custom annotations can be used. - *

- * 2. Since Fesod reads Excel files row by row, you need to create a callback listener for each row. Refer to {@link ConverterDataListener}. - *

- * 3. Directly read the file. - */ - @Test - public void converterRead() { - String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx"; - // Specify the class to read, then read the first sheet - FesodSheet.read(fileName, ConverterData.class, new ConverterDataListener()) - // Note: We can also register a custom converter using `registerConverter`. - // However, this converter will be global, and all fields with Java type `String` and Excel type - // `String` will use this converter. - // If you want to use it for a single field, specify the converter using `@ExcelProperty`. - // .registerConverter(new CustomStringStringConverter()) - // Read the sheet - .sheet() - .doRead(); - } - - /** - * Multi-row header - * - *

- * 1. Create an entity class corresponding to the Excel data structure. Refer to {@link DemoData}. - *

- * 2. Since Fesod reads Excel files row by row, you need to create a callback listener for each row. Refer to {@link DemoDataListener}. - *

- * 3. Set the `headRowNumber` parameter, then read. Note that if `headRowNumber` is not specified, - * the number of rows will be determined by the number of headers in the `@ExcelProperty#value()` of the class you provide. - * If no class is provided, the default is 1. Of course, if you specify `headRowNumber`, it will be used regardless of whether a class is provided. - */ - @Test - public void complexHeaderRead() { - String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx"; - // Specify the class to read, then read the first sheet - FesodSheet.read(fileName, DemoData.class, new DemoDataListener()) - .sheet() - // Set to 1 here because the header is one row. For multi-row headers, set to other values. - // You can also omit this, as the default behavior will parse based on DemoData, which does not specify - // a header, meaning the default is 1 row. - .headRowNumber(1) - .doRead(); - } - - /** - * Method to read Excel files with headers that support compatibility, such as case sensitivity or simultaneous - * support for Chinese and English headers. - * - *

- * 1. Create an entity object corresponding to the Excel data structure. Refer to {@link DemoCompatibleHeaderData} - * for implementation details. - *

- * - *

- * 2. Since Fesod reads the Excel file row by row by default, you need to create a listener that handles each - * row's data accordingly. Refer to {@link DemoCompatibleHeaderDataListener} for implementation details. In this - * listener, you should override the `invokeHead` method to transform the uploaded headers as needed. - *

- * - *

- * 3. Simply proceed to read the file. - *

- */ - @Test - public void compatibleHeaderRead() { - String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx"; - // Specify the class used for reading and choose to read the first sheet. - FesodSheet.read(fileName, DemoCompatibleHeaderData.class, new DemoCompatibleHeaderDataListener()) - .sheet() - .doRead(); - } - - /** - * Read header data - * - *

- * 1. Create an entity object corresponding to the Excel data structure. Refer to {@link DemoData}. - *

- * 2. Since Fesod reads Excel files row by row, you need to create a callback listener for each row. Refer to {@link DemoHeadDataListener}. - *

- * 3. Directly read the file. - */ - @Test - public void headerRead() { - String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx"; - // Specify the class to read, then read the first sheet - FesodSheet.read(fileName, DemoData.class, new DemoHeadDataListener()) - .sheet() - .doRead(); - } - - /** - * Additional information (comments, hyperlinks, merged cell information) - *

- * Since it is stream-based reading, it is not possible to directly read additional information when reading cell data. - * Therefore, only notifications of which cells contain additional information can be provided at the end. - * - *

- * 1. Create an entity object corresponding to the Excel data structure. Refer to {@link DemoExtraData}. - *

- * 2. Since Fesod reads Excel files row by row by default, you need to create a callback listener for each row. Refer to {@link DemoExtraListener}. - *

- * 3. Directly read the file. - */ - @Test - public void extraRead() { - String fileName = TestFileUtil.getPath() + "demo" + File.separator + "extra.xlsx"; - // Specify the class to read, then read the first sheet - FesodSheet.read(fileName, DemoExtraData.class, new DemoExtraListener()) - // Read comments (default is not to read) - .extraRead(CellExtraTypeEnum.COMMENT) - // Read hyperlinks (default is not to read) - .extraRead(CellExtraTypeEnum.HYPERLINK) - // Read merged cell information (default is not to read) - .extraRead(CellExtraTypeEnum.MERGE) - .sheet() - .doRead(); - } - - /** - * Read formulas and cell types - * - *

- * 1. Create an entity object corresponding to the Excel data structure. Refer to {@link CellDataReadDemoData}. - *

- * 2. Since Fesod reads Excel files row by row by default, you need to create a callback listener for each row. Refer to {@link CellDataDemoHeadDataListener}. - *

- * 3. Directly read the file. - */ - @Test - public void cellDataRead() { - String fileName = TestFileUtil.getPath() + "demo" + File.separator + "cellDataDemo.xlsx"; - // Specify the class to read, then read the first sheet - FesodSheet.read(fileName, CellDataReadDemoData.class, new CellDataDemoHeadDataListener()) - .sheet() - .doRead(); - } - - /** - * Exception handling for data conversion, etc. - * - *

- * 1. Create an entity object corresponding to the Excel data structure. Refer to {@link ExceptionDemoData}. - *

- * 2. Since Fesod reads Excel files row by row by default, you need to create a callback listener for each row. Refer to {@link DemoExceptionListener}. - *

- * 3. Directly read the file. - */ - @Test - public void exceptionRead() { - String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx"; - // Specify the class to read, then read the first sheet - FesodSheet.read(fileName, ExceptionDemoData.class, new DemoExceptionListener()) - .sheet() - .doRead(); - } - - /** - * Synchronous return is not recommended, as it will store data in memory if the data volume is large. - */ - @Test - public void synchronousRead() { - String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx"; - // Specify the class to read, then read the first sheet. Synchronous reading will automatically finish. - List list = - FesodSheet.read(fileName).head(DemoData.class).sheet().doReadSync(); - for (DemoData data : list) { - log.info("Read data:{}", JSON.toJSONString(data)); - } - - // Alternatively, you can read without specifying a class, returning a list, then read the first sheet. - // Synchronous reading will automatically finish. - List> listMap = FesodSheet.read(fileName).sheet().doReadSync(); - for (Map data : listMap) { - // Return key-value pairs for each data item, representing the column index and its value. - log.info("Read data:{}", JSON.toJSONString(data)); - } - } - - /** - * Reading without creating objects - */ - @Test - public void noModelRead() { - String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx"; - // Simply read the first sheet. Synchronous reading will automatically finish. - FesodSheet.read(fileName, new NoModelDataListener()).sheet().doRead(); - } - - /** - * Custom modification of CSV configuration - */ - @Nested - class ReadCsvFormat { - - @Test - void asNormalJavaBean() { - String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.csv"; - try (ExcelReader excelReader = FesodSheet.read(fileName, DemoData.class, new DemoDataListener()) - .build()) { - // Check if it is a CSV file - if (excelReader.analysisContext().readWorkbookHolder() instanceof CsvReadWorkbookHolder) { - CsvReadWorkbookHolder csvReadWorkbookHolder = (CsvReadWorkbookHolder) - excelReader.analysisContext().readWorkbookHolder(); - // Set to comma-separated (default is also comma-separated) - // Note: `withDelimiter` will regenerate the format, so it needs to be set back. - csvReadWorkbookHolder.setCsvFormat( - csvReadWorkbookHolder.getCsvFormat().withDelimiter(',')); - } - - // Get all sheets - List readSheetList = excelReader.excelExecutor().sheetList(); - // If you only want to read the first sheet, you can pass the parameter accordingly. - // ReadSheet readSheet = FesodSheet.readSheet(0).build(); - excelReader.read(readSheetList); - } - } - - @Test - void asChainedAccessorsJavaBean() { - String fileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.csv"; - try (ExcelReader excelReader = FesodSheet.read( - fileName, DemoChainAccessorsData.class, new ReadListener() { - @Override - public void invoke(DemoChainAccessorsData data, AnalysisContext context) { - Assertions.assertNotNull(data.getString()); - Assertions.assertNotNull(data.getDate()); - Assertions.assertNotNull(data.getDoubleData()); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) {} - }) - .build()) { - excelReader.readAll(); - } - } - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/Sample.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/Sample.java deleted file mode 100644 index c76f40396..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/Sample.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.read; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -@Getter -@Setter -@EqualsAndHashCode -@NoArgsConstructor -public class Sample { - - private String header; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/WebTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/WebTest.java deleted file mode 100644 index f63490edc..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/WebTest.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.web; - -import com.alibaba.fastjson2.JSON; -import java.io.IOException; -import java.net.URLEncoder; -import java.util.Date; -import java.util.List; -import java.util.Map; -import javax.servlet.http.HttpServletResponse; -import org.apache.fesod.common.util.ListUtils; -import org.apache.fesod.common.util.MapUtils; -import org.apache.fesod.sheet.FesodSheet; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.multipart.MultipartFile; - -/** - * Web read and write examples - * - * - **/ -@Controller -public class WebTest { - - @Autowired - private UploadDAO uploadDAO; - - /** - * File download (returns an Excel with partial data if failed) - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link DownloadData} - *

- * 2. Set the return parameters - *

- * 3. Write directly. Note that the OutputStream will be automatically closed when finish is called. It's fine to close the stream outside as well - */ - @GetMapping("download") - public void download(HttpServletResponse response) throws IOException { - // Note: Some students reported that using Swagger causes various issues, please use browser directly or use - // Postman - response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); - response.setCharacterEncoding("utf-8"); - // Here URLEncoder.encode can prevent Chinese character encoding issues, which is unrelated to Fesod - String fileName = URLEncoder.encode("test", "UTF-8").replaceAll("\\+", "%20"); - response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); - - FesodSheet.write(response.getOutputStream(), DownloadData.class) - .sheet("Template") - .doWrite(data()); - } - - /** - * File download that returns JSON when failed (by default, returns an Excel with partial data when failed) - */ - @GetMapping("downloadFailedUsingJson") - public void downloadFailedUsingJson(HttpServletResponse response) throws IOException { - // Note: Some students reported that using Swagger causes various issues, please use browser directly or use - // Postman - try { - response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); - response.setCharacterEncoding("utf-8"); - // Here URLEncoder.encode can prevent Chinese character encoding issues, which is unrelated to Fesod - String fileName = URLEncoder.encode("test", "UTF-8").replaceAll("\\+", "%20"); - response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx"); - // Here we need to set not to close the stream - FesodSheet.write(response.getOutputStream(), DownloadData.class) - .autoCloseStream(Boolean.FALSE) - .sheet("Template") - .doWrite(data()); - } catch (Exception e) { - // Reset response - response.reset(); - response.setContentType("application/json"); - response.setCharacterEncoding("utf-8"); - Map map = MapUtils.newHashMap(); - map.put("status", "failure"); - map.put("message", "Failed to download file: " + e.getMessage()); - response.getWriter().println(JSON.toJSONString(map)); - } - } - - /** - * File upload - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link UploadData} - *

- * 2. Since Excel is read row by row by default, you need to create a row-by-row callback listener for Excel. Refer to {@link UploadDataListener} - *

- * 3. Read directly - */ - @PostMapping("upload") - @ResponseBody - public String upload(MultipartFile file) throws IOException { - FesodSheet.read(file.getInputStream(), UploadData.class, new UploadDataListener(uploadDAO)) - .sheet() - .doRead(); - return "success"; - } - - private List data() { - List list = ListUtils.newArrayList(); - for (int i = 0; i < 10; i++) { - DownloadData data = new DownloadData(); - data.setString("String" + 0); - data.setDate(new Date()); - data.setDoubleData(0.56); - list.add(data); - } - return list; - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/ColorDemoData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/ColorDemoData.java deleted file mode 100644 index 0f80e71de..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/ColorDemoData.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.write; - -import lombok.AllArgsConstructor; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; -import org.apache.fesod.sheet.annotation.write.style.HeadFontStyle; -import org.apache.poi.ss.usermodel.Font; - -/** - * Basic data class for test color - * - **/ -@Getter -@Setter -@EqualsAndHashCode -@AllArgsConstructor -@NoArgsConstructor -public class ColorDemoData { - - @ExcelProperty("Name") - private String name; - - @ExcelProperty("Age") - @HeadFontStyle(color = Font.COLOR_RED) - private Integer age; - - @ExcelProperty("Sex") - private String sex; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/ComplexHeadData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/ComplexHeadData.java deleted file mode 100644 index 4ed4c4ddf..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/ComplexHeadData.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.write; - -import java.util.Date; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -/** - * Complex header data. The final effect is a main title on the first row, and categories on the second row. - * - * - **/ -@Getter -@Setter -@EqualsAndHashCode -public class ComplexHeadData { - @ExcelProperty({"Main Title", "String Title"}) - private String string; - - @ExcelProperty({"Main Title", "Date Title"}) - private Date date; - - @ExcelProperty({"Main Title", "Double Title"}) - private Double doubleData; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/ConverterData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/ConverterData.java deleted file mode 100644 index 9448d3b1d..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/ConverterData.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.write; - -import java.util.Date; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; -import org.apache.fesod.sheet.annotation.format.DateTimeFormat; -import org.apache.fesod.sheet.annotation.format.NumberFormat; - -/** - * Basic data class. The sorting here is consistent with the sorting in Excel. - * - * - **/ -@Getter -@Setter -@EqualsAndHashCode -public class ConverterData { - /** - * I want to add "Custom:" to the beginning of all strings. - */ - @ExcelProperty(value = "String Title", converter = CustomStringStringConverter.class) - private String string; - /** - * I want to write to Excel using the format "yyyy-MM-dd HH:mm:ss" - */ - @DateTimeFormat("yyyy-MM-dd HH:mm:ss") - @ExcelProperty("Date Title") - private Date date; - /** - * I want to write to Excel using percentage format. - */ - @NumberFormat("#.##%") - @ExcelProperty(value = "Double Title") - private Double doubleData; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/CustomStringStringConverter.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/CustomStringStringConverter.java deleted file mode 100644 index bce1f630c..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/CustomStringStringConverter.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.write; - -import org.apache.fesod.sheet.converters.Converter; -import org.apache.fesod.sheet.converters.ReadConverterContext; -import org.apache.fesod.sheet.converters.WriteConverterContext; -import org.apache.fesod.sheet.enums.CellDataTypeEnum; -import org.apache.fesod.sheet.metadata.data.WriteCellData; - -/** - * String and string converter - * - * - */ -public class CustomStringStringConverter implements Converter { - @Override - public Class supportJavaTypeKey() { - return String.class; - } - - @Override - public CellDataTypeEnum supportExcelTypeKey() { - return CellDataTypeEnum.STRING; - } - - /** - * 这里是读的时候会调用 不用管 - * - * @return - */ - @Override - public String convertToJavaData(ReadConverterContext context) { - return context.getReadCellData().getStringValue(); - } - - /** - * 这里是写的时候会调用 不用管 - * - * @return - */ - @Override - public WriteCellData convertToExcelData(WriteConverterContext context) { - return new WriteCellData<>("自定义:" + context.getValue()); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/EscapeHexCellWriteHandlerTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/EscapeHexCellWriteHandlerTest.java deleted file mode 100644 index 0d5d266e5..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/EscapeHexCellWriteHandlerTest.java +++ /dev/null @@ -1,303 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.write; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.support.ExcelTypeEnum; -import org.apache.fesod.sheet.write.handler.EscapeHexCellWriteHandler; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -public class EscapeHexCellWriteHandlerTest { - - @TempDir - Path tempDir; - - private DemoData createDemoData(String str) { - DemoData data = new DemoData(); - data.setString(str); - data.setDate(new Date()); - data.setDoubleData(123.45); - data.setIgnore("ignoreMe"); - return data; - } - - @Test - public void testEscapeHex_xlsx_singleHex() throws Exception { - List list = new ArrayList<>(); - list.add(createDemoData("_xB9f0_")); - - File file = tempDir.resolve("testEscapeHex.xlsx").toFile(); - FesodSheet.write(file, DemoData.class) - .registerWriteHandler(new EscapeHexCellWriteHandler()) - .sheet("TestSheet") - .doWrite(list); - - // Verify the result - try (Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(file)) { - Sheet sheet = workbook.getSheetAt(0); - Row row = sheet.getRow(1); // Data row (header is row 0) - Cell cell = row.getCell(0); // String column - String actualValue = cell.getStringCellValue(); - System.out.println("XLSX result: " + actualValue); - Assertions.assertNotEquals("_x005F_xB9f0_", actualValue, "xlsx should not escape _xB9f0_ to _x005F_xB9f0_"); - } - } - - @Test - public void testEscapeHex_xls_singleHex() throws Exception { - List list = new ArrayList<>(); - list.add(createDemoData("_xB9f0_")); - - File file = tempDir.resolve("testEscapeHex.xls").toFile(); - FesodSheet.write(file, DemoData.class) - .excelType(ExcelTypeEnum.XLS) - .registerWriteHandler(new EscapeHexCellWriteHandler()) - .sheet("TestSheet") - .doWrite(list); - - // Verify the result - try (Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(file)) { - Sheet sheet = workbook.getSheetAt(0); - Row row = sheet.getRow(1); - Cell cell = row.getCell(0); - Assertions.assertNotEquals( - "_x005F_xB9f0_", cell.getStringCellValue(), "xls should not escape _xB9f0_ to _x005F_xB9f0_"); - } - } - - @Test - public void testEscapeHex_csv_singleHex() throws Exception { - List list = new ArrayList<>(); - list.add(createDemoData("_xB9f0_")); - - File file = tempDir.resolve("testEscapeHex.csv").toFile(); - FesodSheet.write(file, DemoData.class) - .excelType(ExcelTypeEnum.CSV) - .registerWriteHandler(new EscapeHexCellWriteHandler()) - .sheet("TestSheet") - .doWrite(list); - - // Verify the result - try (BufferedReader reader = new BufferedReader(new FileReader(file))) { - reader.readLine(); // Skip header - String dataLine = reader.readLine(); - Assertions.assertNotNull(dataLine); - Assertions.assertFalse( - dataLine.contains("_x005F_xB9f0_"), - "csv should not contain escaped _x005F_xB9f0_, but was: " + dataLine); - } - } - - @Test - public void testEscapeHex_multipleHexInOneString() throws Exception { - List list = new ArrayList<>(); - list.add(createDemoData("_xB9f0_ and _x1234_ and _xABCD_")); - - File file = tempDir.resolve("testMultipleHex.xlsx").toFile(); - FesodSheet.write(file, DemoData.class) - .registerWriteHandler(new EscapeHexCellWriteHandler()) - .sheet("TestSheet") - .doWrite(list); - - try (Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(file)) { - Sheet sheet = workbook.getSheetAt(0); - Row row = sheet.getRow(1); - Cell cell = row.getCell(0); - String expected = "_xB9f0_ and _x1234_ and _xABCD_"; - Assertions.assertEquals(expected, cell.getStringCellValue(), "Multiple hex patterns should all be escaped"); - } - } - - @Test - public void testEscapeHex_noHexPattern() throws Exception { - List list = new ArrayList<>(); - list.add(createDemoData("normalString")); - - File file = tempDir.resolve("testNoHex.xlsx").toFile(); - FesodSheet.write(file, DemoData.class) - .registerWriteHandler(new EscapeHexCellWriteHandler()) - .sheet("TestSheet") - .doWrite(list); - - try (Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(file)) { - Sheet sheet = workbook.getSheetAt(0); - Row row = sheet.getRow(1); - Cell cell = row.getCell(0); - Assertions.assertEquals("normalString", cell.getStringCellValue(), "Normal strings should not be modified"); - } - } - - @Test - public void testEscapeHex_partialHexPattern() throws Exception { - List list = new ArrayList<>(); - list.add(createDemoData("_x123_ _xABC_ _x12345_")); // Invalid patterns - - File file = tempDir.resolve("testPartialHex.xlsx").toFile(); - FesodSheet.write(file, DemoData.class) - .registerWriteHandler(new EscapeHexCellWriteHandler()) - .sheet("TestSheet") - .doWrite(list); - - try (Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(file)) { - Sheet sheet = workbook.getSheetAt(0); - Row row = sheet.getRow(1); - Cell cell = row.getCell(0); - Assertions.assertEquals( - "_x123_ _xABC_ _x12345_", cell.getStringCellValue(), "Invalid hex patterns should not be modified"); - } - } - - @Test - public void testEscapeHex_mixedValidAndInvalidPatterns() throws Exception { - List list = new ArrayList<>(); - list.add(createDemoData("_x1234_ _x123_ _xABCD_ _xGHIJ_")); - - File file = tempDir.resolve("testMixedHex.xlsx").toFile(); - FesodSheet.write(file, DemoData.class) - .registerWriteHandler(new EscapeHexCellWriteHandler()) - .sheet("TestSheet") - .doWrite(list); - - try (Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(file)) { - Sheet sheet = workbook.getSheetAt(0); - Row row = sheet.getRow(1); - Cell cell = row.getCell(0); - String expected = "_x1234_ _x123_ _xABCD_ _xGHIJ_"; - Assertions.assertEquals(expected, cell.getStringCellValue(), "Only valid hex patterns should be escaped"); - } - } - - @Test - public void testEscapeHex_emptyAndNullStrings() throws Exception { - List list = new ArrayList<>(); - DemoData data1 = createDemoData(""); - DemoData data2 = createDemoData(null); - list.add(data1); - list.add(data2); - - File file = tempDir.resolve("testEmptyNull.xlsx").toFile(); - FesodSheet.write(file, DemoData.class) - .registerWriteHandler(new EscapeHexCellWriteHandler()) - .sheet("TestSheet") - .doWrite(list); - - try (Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(file)) { - Sheet sheet = workbook.getSheetAt(0); - - // Check empty string - Row row1 = sheet.getRow(1); - Cell cell1 = row1.getCell(0); - Assertions.assertEquals("", cell1.getStringCellValue(), "Empty string should remain empty"); - - // Check null string - Row row2 = sheet.getRow(2); - Cell cell2 = row2.getCell(0); - if (cell2 != null) { - Assertions.assertEquals("", cell2.getStringCellValue(), "Null string should be handled gracefully"); - } - } - } - - @Test - public void testEscapeHex_caseInsensitiveHex() throws Exception { - List list = new ArrayList<>(); - list.add(createDemoData("_x1a2B_ _XC3d4_ _x9F8e_")); - - File file = tempDir.resolve("testCaseInsensitive.xlsx").toFile(); - FesodSheet.write(file, DemoData.class) - .registerWriteHandler(new EscapeHexCellWriteHandler()) - .sheet("TestSheet") - .doWrite(list); - - try (Workbook workbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(file)) { - Sheet sheet = workbook.getSheetAt(0); - Row row = sheet.getRow(1); - Cell cell = row.getCell(0); - String expected = "_x1a2B_ _XC3d4_ _x9F8e_"; - Assertions.assertEquals( - expected, cell.getStringCellValue(), "Case-sensitive hex patterns should be handled correctly"); - } - } - - @Test - public void testEscapeHex_multipleDifferentFormats() throws Exception { - List list = new ArrayList<>(); - list.add(createDemoData("_xB9f0_")); - - // Test xlsx - File xlsxFile = tempDir.resolve("testFormats.xlsx").toFile(); - FesodSheet.write(xlsxFile, DemoData.class) - .registerWriteHandler(new EscapeHexCellWriteHandler()) - .sheet("TestSheet") - .doWrite(list); - - // Test xls - File xlsFile = tempDir.resolve("testFormats.xls").toFile(); - FesodSheet.write(xlsFile, DemoData.class) - .excelType(ExcelTypeEnum.XLS) - .registerWriteHandler(new EscapeHexCellWriteHandler()) - .sheet("TestSheet") - .doWrite(list); - - // Test csv - File csvFile = tempDir.resolve("testFormats.csv").toFile(); - FesodSheet.write(csvFile, DemoData.class) - .excelType(ExcelTypeEnum.CSV) - .registerWriteHandler(new EscapeHexCellWriteHandler()) - .sheet("TestSheet") - .doWrite(list); - - // Verify all formats produce the same escaped result - try (Workbook xlsxWorkbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(xlsxFile); - Workbook xlsWorkbook = org.apache.poi.ss.usermodel.WorkbookFactory.create(xlsFile); - BufferedReader csvReader = new BufferedReader(new FileReader(csvFile))) { - - // Check xlsx - String xlsxValue = xlsxWorkbook.getSheetAt(0).getRow(1).getCell(0).getStringCellValue(); - Assertions.assertEquals("_xB9f0_", xlsxValue); - - // Check xls - String xlsValue = xlsWorkbook.getSheetAt(0).getRow(1).getCell(0).getStringCellValue(); - Assertions.assertEquals("_xB9f0_", xlsValue); - - // Check csv - csvReader.readLine(); // Skip header - String csvLine = csvReader.readLine(); - Assertions.assertTrue(csvLine.contains("_xB9f0_")); - Assertions.assertFalse(csvLine.contains("_x005F_xB9f0_")); - - // All formats should produce the same result - Assertions.assertEquals(xlsxValue, xlsValue, "xlsx, csv and xls should produce the same escaped result"); - } - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/ImageDataWithAnnotation.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/ImageDataWithAnnotation.java deleted file mode 100644 index 59d7b4ace..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/ImageDataWithAnnotation.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.write; - -import java.io.File; -import java.io.InputStream; -import java.net.URL; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; -import org.apache.fesod.sheet.annotation.write.style.ColumnWidth; -import org.apache.fesod.sheet.annotation.write.style.ContentRowHeight; -import org.apache.fesod.sheet.converters.string.StringImageConverter; - -/** - * 图片导出类 - */ -@Getter -@Setter -@EqualsAndHashCode -@ContentRowHeight(100) -@ColumnWidth(100 / 8) -public class ImageDataWithAnnotation { - private File file; - private InputStream inputStream; - /** - * 如果string类型 必须指定转换器,string默认转换成string - */ - @ExcelProperty(converter = StringImageConverter.class) - private String string; - - private byte[] byteArray; - /** - * 根据url导出 - */ - private URL url; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/ImageDemoData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/ImageDemoData.java deleted file mode 100644 index 722d3ee50..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/ImageDemoData.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.write; - -import java.io.File; -import java.io.InputStream; -import java.net.URL; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; -import org.apache.fesod.sheet.annotation.write.style.ColumnWidth; -import org.apache.fesod.sheet.annotation.write.style.ContentRowHeight; -import org.apache.fesod.sheet.converters.string.StringImageConverter; -import org.apache.fesod.sheet.metadata.data.WriteCellData; - -/** - * Image export class - */ -@Getter -@Setter -@EqualsAndHashCode -@ContentRowHeight(100) -@ColumnWidth(100 / 8) -public class ImageDemoData { - private File file; - private InputStream inputStream; - /** - * If it is a String type, a converter must be specified; String is converted to String by default. - */ - @ExcelProperty(converter = StringImageConverter.class) - private String string; - - private byte[] byteArray; - /** - * Export by URL - * - * @since 2.1.1 - */ - private URL url; - - /** - * Export by file and set the export location. - * - * @since 3.0.0-beta1 - */ - private WriteCellData writeCellDataFile; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/IndexData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/IndexData.java deleted file mode 100644 index f4e6129d2..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/IndexData.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.write; - -import java.util.Date; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -/** - * Basic data class - * - * - **/ -@Getter -@Setter -@EqualsAndHashCode -public class IndexData { - @ExcelProperty(value = "String Title", index = 0) - private String string; - - @ExcelProperty(value = "Date Title", index = 1) - private Date date; - /** - * Setting index to 3 will result in the second column being empty. - */ - @ExcelProperty(value = "Double Title", index = 3) - private Double doubleData; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/LongestMatchColumnWidthData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/LongestMatchColumnWidthData.java deleted file mode 100644 index b3ae2ea28..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/LongestMatchColumnWidthData.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.write; - -import java.util.Date; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -/** - * Basic data class - * - * - **/ -@Getter -@Setter -@EqualsAndHashCode -public class LongestMatchColumnWidthData { - @ExcelProperty("String Title") - private String string; - - @ExcelProperty("Date Title is very long Date Title is very long") - private Date date; - - @ExcelProperty("Double") - private Double doubleData; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/WidthAndHeightData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/WidthAndHeightData.java deleted file mode 100644 index 6b7fe8c5c..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/WidthAndHeightData.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.write; - -import java.util.Date; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; -import org.apache.fesod.sheet.annotation.write.style.ColumnWidth; -import org.apache.fesod.sheet.annotation.write.style.ContentRowHeight; -import org.apache.fesod.sheet.annotation.write.style.HeadRowHeight; - -/** - * Basic data class - * - * - **/ -@Getter -@Setter -@EqualsAndHashCode -@ContentRowHeight(10) -@HeadRowHeight(20) -@ColumnWidth(25) -public class WidthAndHeightData { - @ExcelProperty("String Title") - private String string; - - @ExcelProperty("Date Title") - private Date date; - /** - * Width is 50 - */ - @ColumnWidth(50) - @ExcelProperty("Double Title") - private Double doubleData; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/WriteCellDemoData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/WriteCellDemoData.java deleted file mode 100644 index 02704925a..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/WriteCellDemoData.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.write; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.metadata.data.WriteCellData; - -/** - * Write via WriteCellData - * - * - */ -@Getter -@Setter -@EqualsAndHashCode -public class WriteCellDemoData { - /** - * Hyperlink - * - * @since 3.0.0-beta1 - */ - private WriteCellData hyperlink; - - /** - * Comment - * - * @since 3.0.0-beta1 - */ - private WriteCellData commentData; - - /** - * Formula - * - * @since 3.0.0-beta1 - */ - private WriteCellData formulaData; - - /** - * Specify cell style. Annotations can also be used. - * - * @since 3.0.0-beta1 - */ - private WriteCellData writeCellStyle; - - /** - * Specify multiple styles for a single cell - * - * @since 3.0.0-beta1 - */ - private WriteCellData richText; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/WriteTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/WriteTest.java deleted file mode 100644 index 0c8c6a061..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/write/WriteTest.java +++ /dev/null @@ -1,899 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.demo.write; - -import java.io.File; -import java.io.InputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import org.apache.fesod.common.util.BooleanUtils; -import org.apache.fesod.common.util.ListUtils; -import org.apache.fesod.sheet.ExcelWriter; -import org.apache.fesod.sheet.FesodSheet; -import org.apache.fesod.sheet.annotation.ExcelProperty; -import org.apache.fesod.sheet.annotation.format.DateTimeFormat; -import org.apache.fesod.sheet.annotation.format.NumberFormat; -import org.apache.fesod.sheet.annotation.write.style.ColumnWidth; -import org.apache.fesod.sheet.annotation.write.style.ContentRowHeight; -import org.apache.fesod.sheet.annotation.write.style.HeadRowHeight; -import org.apache.fesod.sheet.enums.CellDataTypeEnum; -import org.apache.fesod.sheet.metadata.data.CommentData; -import org.apache.fesod.sheet.metadata.data.FormulaData; -import org.apache.fesod.sheet.metadata.data.HyperlinkData; -import org.apache.fesod.sheet.metadata.data.ImageData; -import org.apache.fesod.sheet.metadata.data.RichTextStringData; -import org.apache.fesod.sheet.metadata.data.WriteCellData; -import org.apache.fesod.sheet.util.FileUtils; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.handler.CellWriteHandler; -import org.apache.fesod.sheet.write.handler.EscapeHexCellWriteHandler; -import org.apache.fesod.sheet.write.handler.SheetWriteHandler; -import org.apache.fesod.sheet.write.handler.context.CellWriteHandlerContext; -import org.apache.fesod.sheet.write.handler.context.SheetWriteHandlerContext; -import org.apache.fesod.sheet.write.merge.LoopMergeStrategy; -import org.apache.fesod.sheet.write.metadata.WriteSheet; -import org.apache.fesod.sheet.write.metadata.WriteTable; -import org.apache.fesod.sheet.write.metadata.style.WriteCellStyle; -import org.apache.fesod.sheet.write.metadata.style.WriteFont; -import org.apache.fesod.sheet.write.style.HorizontalCellStyleStrategy; -import org.apache.fesod.sheet.write.style.column.LongestMatchColumnWidthStyleStrategy; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.junit.jupiter.api.Test; - -/** - * Common writing examples - * - * - */ -public class WriteTest { - - /** - * Simple write - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link DemoData} - *

- * 2. Write directly - */ - @Test - public void simpleWrite() { - // Note: simpleWrite can be used when the data volume is not large (within 5000, depending on the actual - // situation). For large data volumes, refer to repeated writes. - - // Method 1 JDK8+ - // since: 3.0.0-beta1 - String fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx"; - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - // If you want to use Excel 03, pass the excelType parameter. - FesodSheet.write(fileName, DemoData.class).sheet("Template").doWrite(() -> { - // Paging query data - return data(); - }); - - // Method 2 - fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx"; - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - // If you want to use Excel 03, pass the excelType parameter. - FesodSheet.write(fileName, DemoData.class).sheet("Template").doWrite(data()); - - // Method 3 - fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx"; - // Specify the class to use for writing - try (ExcelWriter excelWriter = - FesodSheet.write(fileName, DemoData.class).build()) { - WriteSheet writeSheet = FesodSheet.writerSheet("Template").build(); - excelWriter.write(data(), writeSheet); - } - } - - @Test - public void testEscapeHex() { - String fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx"; - FesodSheet.write(fileName, DemoData.class) - .sheet("Template") - .registerWriteHandler(new EscapeHexCellWriteHandler()) - .doWrite(() -> { - return dataHex(); - }); - } - - /** - * Export only specified columns based on parameters - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link DemoData} - *

- * 2. Include or exclude columns as needed - *

- * 3. Write directly - */ - @Test - public void excludeOrIncludeWrite() { - String fileName = TestFileUtil.getPath() + "excludeOrIncludeWrite" + System.currentTimeMillis() + ".xlsx"; - // Note: When using the ExcelProperty annotation, if you want to avoid empty columns, you need to use the - // 'order' field instead of 'index'. 'order' will ignore empty columns and continue sequentially, while 'index' - // will not ignore empty columns (it stays in the specified column). - - // Based on user input fields, assuming we want to ignore 'date' - Set excludeColumnFieldNames = new HashSet<>(); - excludeColumnFieldNames.add("date"); - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - FesodSheet.write(fileName, DemoData.class) - .excludeColumnFieldNames(excludeColumnFieldNames) - .sheet("Template") - .doWrite(data()); - - fileName = TestFileUtil.getPath() + "excludeOrIncludeWrite" + System.currentTimeMillis() + ".xlsx"; - // Based on user input fields, assuming we only want to export 'date' - Set includeColumnFieldNames = new HashSet<>(); - includeColumnFieldNames.add("date"); - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - FesodSheet.write(fileName, DemoData.class) - .includeColumnFieldNames(includeColumnFieldNames) - .sheet("Template") - .doWrite(data()); - } - - /** - * Specify columns to write - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link IndexData} - *

- * 2. Use {@link ExcelProperty} annotation to specify columns to write - *

- * 3. Write directly - */ - @Test - public void indexWrite() { - String fileName = TestFileUtil.getPath() + "indexWrite" + System.currentTimeMillis() + ".xlsx"; - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - FesodSheet.write(fileName, IndexData.class).sheet("Template").doWrite(data()); - } - - /** - * Complex header writing - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link ComplexHeadData} - *

- * 2. Use {@link ExcelProperty} annotation to specify complex headers - *

- * 3. Write directly - */ - @Test - public void complexHeadWrite() { - String fileName = TestFileUtil.getPath() + "complexHeadWrite" + System.currentTimeMillis() + ".xlsx"; - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - FesodSheet.write(fileName, ComplexHeadData.class).sheet("Template").doWrite(data()); - } - - /** - * Repeated writes - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link ComplexHeadData} - *

- * 2. Use {@link ExcelProperty} annotation to specify complex headers - *

- * 3. Call write multiple times - */ - @Test - public void repeatedWrite() { - // Method 1: Writing to the same sheet - String fileName = TestFileUtil.getPath() + "repeatedWrite" + System.currentTimeMillis() + ".xlsx"; - // Specify the class to use for writing - try (ExcelWriter excelWriter = - FesodSheet.write(fileName, DemoData.class).build()) { - // Note: Create the writeSheet only once if writing to the same sheet - WriteSheet writeSheet = FesodSheet.writerSheet("Template").build(); - // Call write. Here I called it five times. In actual use, loop based on the total number of pages in the - // database query. - for (int i = 0; i < 5; i++) { - // Paging query data from the database. Here you can query the data for each page. - List data = data(); - excelWriter.write(data, writeSheet); - } - } - - // Method 2: Writing to different sheets with the same object - fileName = TestFileUtil.getPath() + "repeatedWrite" + System.currentTimeMillis() + ".xlsx"; - // Specify file - try (ExcelWriter excelWriter = - FesodSheet.write(fileName, DemoData.class).build()) { - // Call write. Here I called it five times. In actual use, loop based on the total number of pages in the - // database query. Eventually it will be written to 5 sheets. - for (int i = 0; i < 5; i++) { - // Create writeSheet every time. Note that sheetNo must be specified and sheetName must be different. - WriteSheet writeSheet = - FesodSheet.writerSheet(i, "Template" + i).build(); - // Paging query data from the database. Here you can query the data for each page. - List data = data(); - excelWriter.write(data, writeSheet); - } - } - - // Method 3: Writing to different sheets with different objects - fileName = TestFileUtil.getPath() + "repeatedWrite" + System.currentTimeMillis() + ".xlsx"; - // Specify file - try (ExcelWriter excelWriter = FesodSheet.write(fileName).build()) { - // Call write. Here I called it five times. In actual use, loop based on the total number of pages in the - // database query. Eventually it will be written to 5 sheets. - for (int i = 0; i < 5; i++) { - // Create writeSheet every time. Note that sheetNo must be specified and sheetName must be different. - // Note that DemoData.class can change each time; I used the same class here for convenience. - // In reality, it can change every time. - WriteSheet writeSheet = FesodSheet.writerSheet(i, "Template" + i) - .head(DemoData.class) - .build(); - // Paging query data from the database. Here you can query the data for each page. - List data = data(); - excelWriter.write(data, writeSheet); - } - } - } - - /** - * Date, number, or custom format conversion - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link ConverterData} - *

- * 2. Use {@link ExcelProperty} with annotations {@link DateTimeFormat}, {@link NumberFormat}, or custom annotations - *

- * 3. Write directly - */ - @Test - public void converterWrite() { - String fileName = TestFileUtil.getPath() + "converterWrite" + System.currentTimeMillis() + ".xlsx"; - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - FesodSheet.write(fileName, ConverterData.class).sheet("Template").doWrite(data()); - } - - /** - * Image export - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link ImageDemoData} - *

- * 2. Write directly - */ - @Test - public void imageWrite() throws Exception { - String fileName = TestFileUtil.getPath() + "imageWrite" + System.currentTimeMillis() + ".xlsx"; - - // Note: All images will be loaded into memory. There is no good solution for now. For large numbers of images, - // it is recommended to: - // 1. Upload images to OSS or other storage sites: https://www.aliyun.com/product/oss, then verify the link - // directly - // 2. Use: https://github.com/coobird/thumbnailator or other tools to compress images - - String imagePath = TestFileUtil.getPath() + "converter" + File.separator + "img.jpg"; - try (InputStream inputStream = FileUtils.openInputStream(new File(imagePath))) { - List list = ListUtils.newArrayList(); - ImageDemoData imageDemoData = new ImageDemoData(); - list.add(imageDemoData); - // Put five types of images. In actual use, just choose one. - imageDemoData.setByteArray(FileUtils.readFileToByteArray(new File(imagePath))); - imageDemoData.setFile(new File(imagePath)); - imageDemoData.setString(imagePath); - imageDemoData.setInputStream(inputStream); - imageDemoData.setUrl(new URL("https://poi.apache.org/images/project-header.png")); - - // Demonstration - // Need to add extra text - // And need to add 2 images - // The first image is on the left - // The second is on the right and occupies the cell behind it - WriteCellData writeCellData = new WriteCellData<>(); - imageDemoData.setWriteCellDataFile(writeCellData); - // Set to EMPTY to indicate no other data is needed - writeCellData.setType(CellDataTypeEnum.STRING); - writeCellData.setStringValue("Extra text"); - - // Can put multiple images - List imageDataList = new ArrayList<>(); - ImageData imageData = new ImageData(); - imageDataList.add(imageData); - writeCellData.setImageDataList(imageDataList); - // Put binary image - imageData.setImage(FileUtils.readFileToByteArray(new File(imagePath))); - // Image type - imageData.setImageType(ImageData.ImageType.PICTURE_TYPE_PNG); - // Top, Right, Bottom, Left need padding - // Similar to CSS margin - // Tested: cannot set too large. If it exceeds the original cell size, opening it will prompt repair. No - // good solution found yet. - imageData.setTop(5); - imageData.setRight(40); - imageData.setBottom(5); - imageData.setLeft(5); - - // Put second image - imageData = new ImageData(); - imageDataList.add(imageData); - writeCellData.setImageDataList(imageDataList); - imageData.setImage(FileUtils.readFileToByteArray(new File(imagePath))); - imageData.setImageType(ImageData.ImageType.PICTURE_TYPE_PNG); - imageData.setTop(5); - imageData.setRight(5); - imageData.setBottom(5); - imageData.setLeft(50); - // Set image position. Assume the target is to cover the current cell and the cell to the right. - // Start point relative to current cell is 0. Can be omitted. - imageData.setRelativeFirstRowIndex(0); - imageData.setRelativeFirstColumnIndex(0); - imageData.setRelativeLastRowIndex(0); - // First 3 can be omitted. The following one needs to be written, meaning the end needs to move one cell to - // the right relative to the current cell. - // This image will cover the current cell and the next one. - imageData.setRelativeLastColumnIndex(1); - - // Write data - FesodSheet.write(fileName, ImageDemoData.class).sheet().doWrite(list); - // If image resource is inaccessible, XLSX format will error: SXSSFWorkbook - Failed to dispose sheet - // Can consider declaring as XLS format - // FesodSheet.write(fileName, ImageDemoData.class).excelType(ExcelTypeEnum.XLS).sheet().doWrite(list); - } - } - - /** - * Hyperlinks, comments, formulas, single cell styling, multiple styles in a single cell - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link WriteCellDemoData} - *

- * 2. Write directly - */ - @Test - public void writeCellDataWrite() { - String fileName = TestFileUtil.getPath() + "writeCellDataWrite" + System.currentTimeMillis() + ".xlsx"; - WriteCellDemoData writeCellDemoData = new WriteCellDemoData(); - - // Set hyperlink - WriteCellData hyperlink = new WriteCellData<>("Official Website"); - writeCellDemoData.setHyperlink(hyperlink); - HyperlinkData hyperlinkData = new HyperlinkData(); - hyperlink.setHyperlinkData(hyperlinkData); - hyperlinkData.setAddress("https://github.com/fast-excel/fastexcel"); - hyperlinkData.setHyperlinkType(HyperlinkData.HyperlinkType.URL); - - // Set comment - WriteCellData comment = new WriteCellData<>("Comment cell info"); - writeCellDemoData.setCommentData(comment); - CommentData commentData = new CommentData(); - comment.setCommentData(commentData); - commentData.setAuthor("Jiaju Zhuang"); - commentData.setRichTextStringData(new RichTextStringData("This is a comment")); - // The default size of the comment is the size of the cell. Here we want to adjust it to the size of 4 cells, so - // we occupy one extra cell to the right and one extra cell down. - commentData.setRelativeLastColumnIndex(1); - commentData.setRelativeLastRowIndex(1); - - // Set formula - WriteCellData formula = new WriteCellData<>(); - writeCellDemoData.setFormulaData(formula); - FormulaData formulaData = new FormulaData(); - formula.setFormulaData(formulaData); - // Replace the first digit in 123456789 with 2 - // This is just an example. If it involves formulas, try to calculate them in memory if possible. Avoid using - // formulas if possible. - formulaData.setFormulaValue("REPLACE(123456789,1,1,2)"); - - // Set style for a single cell. If there are many styles, you can use annotations. - WriteCellData writeCellStyle = new WriteCellData<>("Cell Style"); - writeCellStyle.setType(CellDataTypeEnum.STRING); - writeCellDemoData.setWriteCellStyle(writeCellStyle); - WriteCellStyle writeCellStyleData = new WriteCellStyle(); - writeCellStyle.setWriteCellStyle(writeCellStyleData); - // Need to specify FillPatternType as FillPatternType.SOLID_FOREGROUND, otherwise background color will not be - // displayed. - writeCellStyleData.setFillPatternType(FillPatternType.SOLID_FOREGROUND); - // Green background - writeCellStyleData.setFillForegroundColor(IndexedColors.GREEN.getIndex()); - - // Set multiple styles in a single cell - // Need to set inMemory=true, otherwise multiple styles in a single cell cannot be displayed. Use with caution. - WriteCellData richTest = new WriteCellData<>(); - richTest.setType(CellDataTypeEnum.RICH_TEXT_STRING); - writeCellDemoData.setRichText(richTest); - RichTextStringData richTextStringData = new RichTextStringData(); - richTest.setRichTextStringDataValue(richTextStringData); - richTextStringData.setTextString("Red Green Default"); - // First 3 characters are red - WriteFont writeFont = new WriteFont(); - writeFont.setColor(IndexedColors.RED.getIndex()); - richTextStringData.applyFont(0, 3, writeFont); - // Next 5 characters are green - writeFont = new WriteFont(); - writeFont.setColor(IndexedColors.GREEN.getIndex()); - richTextStringData.applyFont(4, 9, writeFont); - - List data = new ArrayList<>(); - data.add(writeCellDemoData); - FesodSheet.write(fileName, WriteCellDemoData.class) - .inMemory(true) - .sheet("Template") - .doWrite(data); - } - - /** - * Write according to template - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link IndexData} - *

- * 2. Use {@link ExcelProperty} annotation to specify columns to write - *

- * 3. Use withTemplate to read template - *

- * 4. Write directly - */ - @Test - public void templateWrite() { - String templateFileName = TestFileUtil.getPath() + "demo" + File.separator + "demo.xlsx"; - String fileName = TestFileUtil.getPath() + "templateWrite" + System.currentTimeMillis() + ".xlsx"; - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - // Note: withTemplate will store the entire template file in memory, so try not to use it for appending files. - // If the template file is too large, it will cause OOM. - // If you want to append to a file (cannot be processed in one thread, refer to the repeated writing demo - // recommended for one thread), it is recommended to store temporarily in the database or disk cache (ehcache) - // and then write all at once. - FesodSheet.write(fileName, DemoData.class) - .withTemplate(templateFileName) - .sheet() - .doWrite(data()); - } - - /** - * Column width and row height - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link WidthAndHeightData } - *

- * 2. Use annotations {@link ColumnWidth}, {@link HeadRowHeight}, {@link ContentRowHeight} to specify width or height - *

- * 3. Write directly - */ - @Test - public void widthAndHeightWrite() { - String fileName = TestFileUtil.getPath() + "widthAndHeightWrite" + System.currentTimeMillis() + ".xlsx"; - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - FesodSheet.write(fileName, WidthAndHeightData.class).sheet("Template").doWrite(data()); - } - - /** - * Custom style via annotations - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link DemoStyleData} - *

- * 3. Write directly - */ - @Test - public void annotationStyleWrite() { - String fileName = TestFileUtil.getPath() + "annotationStyleWrite" + System.currentTimeMillis() + ".xlsx"; - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - FesodSheet.write(fileName, DemoStyleData.class).sheet("Template").doWrite(data()); - } - - /** - * Custom style via handlers - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link DemoData} - *

- * 2. Create a style strategy and register it - *

- * 3. Write directly - */ - @Test - public void handlerStyleWrite() { - // Method 1: Use existing strategies (Recommended) - // HorizontalCellStyleStrategy: styles are the same for each row or alternating rows - // AbstractVerticalCellStyleStrategy: styles are the same for each column. Need to subclass and implement. - String fileName = TestFileUtil.getPath() + "handlerStyleWrite" + System.currentTimeMillis() + ".xlsx"; - // Head strategy - WriteCellStyle headWriteCellStyle = new WriteCellStyle(); - // Background red - headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); - WriteFont headWriteFont = new WriteFont(); - headWriteFont.setFontHeightInPoints((short) 20); - headWriteCellStyle.setWriteFont(headWriteFont); - // Content strategy - WriteCellStyle contentWriteCellStyle = new WriteCellStyle(); - // Need to specify FillPatternType as SOLID_FOREGROUND. The head defaults to FillPatternType so it can be - // omitted. - contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND); - // Background green - contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex()); - WriteFont contentWriteFont = new WriteFont(); - // Font size - contentWriteFont.setFontHeightInPoints((short) 20); - contentWriteCellStyle.setWriteFont(contentWriteFont); - // This strategy separates head style and content style. You can implement other strategies yourself. - HorizontalCellStyleStrategy horizontalCellStyleStrategy = - new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle); - - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - FesodSheet.write(fileName, DemoData.class) - .registerWriteHandler(horizontalCellStyleStrategy) - .sheet("Template") - .doWrite(data()); - - // Method 2: Write your own handler using Fesod API. Not recommended. Try to use existing strategies. - fileName = TestFileUtil.getPath() + "handlerStyleWrite" + System.currentTimeMillis() + ".xlsx"; - FesodSheet.write(fileName, DemoData.class) - .registerWriteHandler(new CellWriteHandler() { - @Override - public void afterCellDispose(CellWriteHandlerContext context) { - // This event is called after data is set into the POI cell - // Check if it's not a head. If it's fill, this will be null, so use not true. - if (BooleanUtils.isNotTrue(context.getHead())) { - // First cell - // As long as it's not a head, there will be data. Of course in fill scenarios, use - // context.getCellDataList(). Depending on the template, a cell may have multiple - // WriteCellData. - WriteCellData cellData = context.getFirstCellData(); - // Need to get style from cellData - // A very important reason is that WriteCellStyle is bound to dataFormatData. For example, - // if you add DateTimeFormat, - // the dataFormatData in writeCellStyle has been changed. If you new a WriteCellStyle - // yourself, the annotation style may be lost. - // getOrCreateStyle returns a style, creating one if it's null. - WriteCellStyle writeCellStyle = cellData.getOrCreateStyle(); - writeCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); - // Need to specify FillPatternType as SOLID_FOREGROUND - writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND); - - // The style is set. There is a FillStyleCellWriteHandler later that will default set - // WriteCellStyle to the cell, so you don't need to worry about it. - } - } - }) - .sheet("Template") - .doWrite(data()); - - // Method 3: Use POI styles directly. Not recommended. - // Pitfall 1: Style contains dataformat for formatting data, so setting it yourself may cause formatting - // annotations to fail. - // Pitfall 2: Don't keep creating styles. Remember to cache them. Creating more than 60,000 will crash. - fileName = TestFileUtil.getPath() + "handlerStyleWrite" + System.currentTimeMillis() + ".xlsx"; - FesodSheet.write(fileName, DemoData.class) - .registerWriteHandler(new CellWriteHandler() { - @Override - public void afterCellDispose(CellWriteHandlerContext context) { - // This event is called after data is set into the POI cell - // Check if it's not a head. If it's fill, this will be null, so use not true. - if (BooleanUtils.isNotTrue(context.getHead())) { - Cell cell = context.getCell(); - // Get POI workbook - Workbook workbook = context.getWriteWorkbookHolder().getWorkbook(); - // Remember to cache reusable parts. A table can have at most 60,000 styles. - // Try to pass the same cellStyle for different cells - CellStyle cellStyle = workbook.createCellStyle(); - cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); - // Need to specify FillPatternType as SOLID_FOREGROUND - cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - cell.setCellStyle(cellStyle); - - // Since dataformat is not specified here, the displayed data format may be incorrect. - - // Clear the style of WriteCellData. Otherwise, FillStyleCellWriteHandler will override your - // settings. - context.getFirstCellData().setWriteCellStyle(null); - } - } - }) - .sheet("Template") - .doWrite(data()); - } - - /** - * Merge cells - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link DemoData} {@link DemoMergeData} - *

- * 2. Create a merge strategy and register it - *

- * 3. Write directly - */ - @Test - public void mergeWrite() { - // Method 1: Annotation - String fileName = TestFileUtil.getPath() + "mergeWrite" + System.currentTimeMillis() + ".xlsx"; - // Add ContentLoopMerge annotation in DemoStyleData - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - FesodSheet.write(fileName, DemoMergeData.class).sheet("Template").doWrite(data()); - - // Method 2: Custom merge strategy - fileName = TestFileUtil.getPath() + "mergeWrite" + System.currentTimeMillis() + ".xlsx"; - // Merge every 2 rows. Set eachColumn to 3 (length of our data), so only the first column will merge. Other - // merge strategies can be implemented. - LoopMergeStrategy loopMergeStrategy = new LoopMergeStrategy(2, 0); - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - FesodSheet.write(fileName, DemoData.class) - .registerWriteHandler(loopMergeStrategy) - .sheet("Template") - .doWrite(data()); - } - - /** - * Write using table - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link DemoData} - *

- * 2. Then write to the table - */ - @Test - public void tableWrite() { - String fileName = TestFileUtil.getPath() + "tableWrite" + System.currentTimeMillis() + ".xlsx"; - // Method 1: Writing multiple tables here. If there is only one, it can be done in one line. - // Specify the class to use for writing - try (ExcelWriter excelWriter = - FesodSheet.write(fileName, DemoData.class).build()) { - // Set sheet to not need head, otherwise it will output sheet head, looking like the first table has 2 - // heads. - WriteSheet writeSheet = - FesodSheet.writerSheet("Template").needHead(Boolean.FALSE).build(); - // Must specify need head here. Table inherits sheet configuration. If sheet is configured not to need it, - // table defaults to not needing it. - WriteTable writeTable0 = - FesodSheet.writerTable(0).needHead(Boolean.TRUE).build(); - WriteTable writeTable1 = - FesodSheet.writerTable(1).needHead(Boolean.TRUE).build(); - // First write will create head - excelWriter.write(data(), writeSheet, writeTable0); - // Second write will also create head, writing data after the first one. - excelWriter.write(data(), writeSheet, writeTable1); - } - } - - /** - * Dynamic header writing - *

- * The idea is to first create a sheet with List head format, writing only the head, then write data via table without writing head. - * - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link DemoData} - *

- * 2. Then write to the table - */ - @Test - public void dynamicHeadWrite() { - String fileName = TestFileUtil.getPath() + "dynamicHeadWrite" + System.currentTimeMillis() + ".xlsx"; - FesodSheet.write(fileName) - // Put dynamic head here - .head(head()) - .sheet("Template") - // Of course data can also be passed as List> - .doWrite(data()); - } - - /** - * Auto column width (not very precise) - *

- * This is not very easy to use currently. For example, numbers will cause line breaks. And the length is not exactly consistent with actual length. Use with caution if precise column width is needed. You can also re-implement referencing {@link LongestMatchColumnWidthStyleStrategy}. - *

- * POI's built-in {@link SXSSFSheet#autoSizeColumn(int)} also doesn't support Chinese very well. No good algorithm found yet. - * - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link LongestMatchColumnWidthData} - *

- * 2. Register strategy {@link LongestMatchColumnWidthStyleStrategy} - *

- * 3. Write directly - */ - @Test - public void longestMatchColumnWidthWrite() { - String fileName = - TestFileUtil.getPath() + "longestMatchColumnWidthWrite" + System.currentTimeMillis() + ".xlsx"; - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - FesodSheet.write(fileName, LongestMatchColumnWidthData.class) - .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) - .sheet("Template") - .doWrite(dataLong()); - } - - /** - * Custom handlers for dropdowns, hyperlinks, etc. (Refer to this for operations that don't fit above points but need to manipulate cells) - *

- * Demo implements 2 points: 1. Hyperlink the head of the first row and first column to URL. 2. Add dropdown box for data in the first column, first and second rows, displaying "Test1", "Test2". - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link DemoData} - *

- * 2. Register handlers {@link CustomCellWriteHandler} {@link CustomSheetWriteHandler} - *

- * 2. Write directly - */ - @Test - public void customHandlerWrite() { - String fileName = TestFileUtil.getPath() + "customHandlerWrite" + System.currentTimeMillis() + ".xlsx"; - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - FesodSheet.write(fileName, DemoData.class) - .registerWriteHandler(new CustomSheetWriteHandler()) - .registerWriteHandler(new CustomCellWriteHandler()) - .sheet("Template") - .doWrite(data()); - } - - /** - * Insert comment - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link DemoData} - *

- * 2. Register handler {@link CommentWriteHandler} - *

- * 2. Write directly - */ - @Test - public void commentWrite() { - String fileName = TestFileUtil.getPath() + "commentWrite" + System.currentTimeMillis() + ".xlsx"; - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - // Note that inMemory must be set to true to support comments. Currently there is no good way to handle comments - // without being in memory. - FesodSheet.write(fileName, DemoData.class) - .inMemory(Boolean.TRUE) - .registerWriteHandler(new CommentWriteHandler()) - .sheet("Template") - .doWrite(data()); - } - - /** - * Variable title handling (including title internationalization, etc.) - *

- * Simply put, use List> for titles but still support annotations - *

- * 1. Create the entity object corresponding to Excel. Refer to {@link ConverterData} - *

- * 2. Write directly - */ - @Test - public void variableTitleWrite() { - // Method 1 - String fileName = TestFileUtil.getPath() + "variableTitleWrite" + System.currentTimeMillis() + ".xlsx"; - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - FesodSheet.write(fileName, ConverterData.class) - .head(variableTitleHead()) - .sheet("Template") - .doWrite(data()); - } - - /** - * Write without creating objects - */ - @Test - public void noModelWrite() { - // Method 1 - String fileName = TestFileUtil.getPath() + "noModelWrite" + System.currentTimeMillis() + ".xlsx"; - // Specify the class to use for writing, then write to the first sheet with the name "Template". The file stream - // will be automatically closed. - FesodSheet.write(fileName).head(head()).sheet("Template").doWrite(dataList()); - } - - @Test - public void sheetDisposeTest() { - String fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx"; - FesodSheet.write(fileName, DemoData.class) - .sheet("Template") - .registerWriteHandler(new SheetWriteHandler() { - @Override - public void afterSheetDispose(SheetWriteHandlerContext context) { - Sheet sheet = context.getWriteSheetHolder().getSheet(); - // Merge region cells - sheet.addMergedRegionUnsafe(new CellRangeAddress(1, 10, 2, 2)); - } - }) - .doWrite(this::data); - System.out.println(fileName); - } - - private List dataLong() { - List list = ListUtils.newArrayList(); - for (int i = 0; i < 10; i++) { - LongestMatchColumnWidthData data = new LongestMatchColumnWidthData(); - data.setString("Testing very long string Testing very long string Testing very long string" + i); - data.setDate(new Date()); - data.setDoubleData(1000000000000.0); - list.add(data); - } - return list; - } - - private List> variableTitleHead() { - List> list = ListUtils.newArrayList(); - List head0 = ListUtils.newArrayList(); - head0.add("string" + System.currentTimeMillis()); - List head1 = ListUtils.newArrayList(); - head1.add("number" + System.currentTimeMillis()); - List head2 = ListUtils.newArrayList(); - head2.add("date" + System.currentTimeMillis()); - list.add(head0); - list.add(head1); - list.add(head2); - return list; - } - - private List> head() { - List> list = ListUtils.newArrayList(); - List head0 = ListUtils.newArrayList(); - head0.add("String" + System.currentTimeMillis()); - List head1 = ListUtils.newArrayList(); - head1.add("Double" + System.currentTimeMillis()); - List head2 = ListUtils.newArrayList(); - head2.add("Date" + System.currentTimeMillis()); - list.add(head0); - list.add(head1); - list.add(head2); - return list; - } - - private List> dataList() { - List> list = ListUtils.newArrayList(); - for (int i = 0; i < 10; i++) { - List data = ListUtils.newArrayList(); - data.add("String" + i); - data.add(0.56); - data.add(new Date()); - list.add(data); - } - return list; - } - - private List data() { - List list = ListUtils.newArrayList(); - for (int i = 0; i < 10; i++) { - DemoData data = new DemoData(); - data.setString("STRING" + i); - data.setDate(new Date()); - data.setDoubleData(0.56); - list.add(data); - } - return list; - } - - private List dataHex() { - List list = ListUtils.newArrayList(); - for (int i = 0; i < 10; i++) { - DemoData data = new DemoData(); - data.setString("_xB9f0_"); - data.setDate(new Date()); - data.setDoubleData(0.56); - list.add(data); - } - return list; - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/ExampleTestBase.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/ExampleTestBase.java new file mode 100644 index 000000000..479ebe7e2 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/ExampleTestBase.java @@ -0,0 +1,100 @@ +/* + * 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 org.apache.fesod.sheet.examples; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.file.Path; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.usermodel.WorkbookFactory; + +/** + * Base class for Fesod example integration tests. + * + *

Provides common utilities for verifying Excel file output, following the patterns established + * by Apache Flink's {@code ExampleOutputTestBase} and {@code AbstractTestBase}. + * + *

Key utilities: + *

    + *
  • {@link #assertValidExcelFile(File)} — verifies a file is a readable Excel workbook
  • + *
  • {@link #assertValidExcelFile(File, int)} — additionally verifies minimum row count
  • + *
  • {@link #getTempOutputPath(Path, String)} — generates a temp file path within a directory
  • + *
+ */ +public abstract class ExampleTestBase { + + /** + * Assert that the given file exists, is non-empty, and is a valid Excel workbook that + * Apache POI can open. + * + * @param file the Excel file to validate + */ + protected static void assertValidExcelFile(File file) { + assertNotNull(file, "File reference must not be null"); + assertTrue(file.exists(), "File should exist: " + file.getAbsolutePath()); + assertTrue(file.length() > 0, "File should not be empty: " + file.getAbsolutePath()); + + try (FileInputStream fis = new FileInputStream(file); + Workbook workbook = WorkbookFactory.create(fis)) { + assertNotNull(workbook, "Workbook should be readable"); + assertTrue(workbook.getNumberOfSheets() > 0, "Workbook should have at least one sheet"); + } catch (IOException e) { + fail("File should be a valid Excel workbook: " + file.getAbsolutePath() + ", error: " + e.getMessage()); + } + } + + /** + * Assert that the given file is a valid Excel workbook with at least the specified number of + * data rows (excluding header). + * + * @param file the Excel file to validate + * @param minDataRows the minimum number of data rows expected (excluding header row) + */ + protected static void assertValidExcelFile(File file, int minDataRows) { + assertValidExcelFile(file); + + try (FileInputStream fis = new FileInputStream(file); + Workbook workbook = WorkbookFactory.create(fis)) { + int totalRows = workbook.getSheetAt(0).getPhysicalNumberOfRows(); + // totalRows includes header row, so data rows = totalRows - 1 + assertTrue( + totalRows > minDataRows, + "Expected at least " + minDataRows + " data rows (plus header), but found " + totalRows + + " total rows in: " + file.getAbsolutePath()); + } catch (IOException e) { + fail("Failed to read workbook for row count verification: " + e.getMessage()); + } + } + + /** + * Generate a temp output file path within the given directory. + * + * @param tempDir the temporary directory (typically from {@code @TempDir}) + * @param fileName the desired filename + * @return the absolute path as a String + */ + protected static String getTempOutputPath(Path tempDir, String fileName) { + return tempDir.resolve(fileName).toAbsolutePath().toString(); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/advanced/CustomConverterExampleITCase.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/advanced/CustomConverterExampleITCase.java new file mode 100644 index 000000000..1d4304699 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/advanced/CustomConverterExampleITCase.java @@ -0,0 +1,39 @@ +/* + * 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 org.apache.fesod.sheet.examples.advanced; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.apache.fesod.sheet.examples.ExampleTestBase; +import org.junit.jupiter.api.Test; + +/** + * Test for {@link CustomConverterExample}. + * + *

Verifies the custom-converter round-trip: writes an Excel file with a + * {@code CustomStringStringConverter} that transforms string values, then reads them back + * using the same converter. + */ +class CustomConverterExampleITCase extends ExampleTestBase { + + @Test + void testCustomConverterRoundTrip() { + assertDoesNotThrow(() -> CustomConverterExample.main(new String[] {})); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/advanced/LargeFileWriteExampleITCase.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/advanced/LargeFileWriteExampleITCase.java new file mode 100644 index 000000000..bc2e74376 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/advanced/LargeFileWriteExampleITCase.java @@ -0,0 +1,40 @@ +/* + * 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 org.apache.fesod.sheet.examples.advanced; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.apache.fesod.sheet.examples.ExampleTestBase; +import org.junit.jupiter.api.Test; + +/** + * Test for {@link LargeFileWriteExample}. + * + *

Verifies the large-file write example which writes 100,000 rows in batches using + * {@code SXSSFWorkbook} with compressed temporary files to reduce disk usage. + * + *

Note: This test may take several seconds due to the volume of data. + */ +class LargeFileWriteExampleITCase extends ExampleTestBase { + + @Test + void testCompressedTemporaryFile() { + assertDoesNotThrow(LargeFileWriteExample::compressedTemporaryFile); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/advanced/PasswordProtectionExampleITCase.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/advanced/PasswordProtectionExampleITCase.java new file mode 100644 index 000000000..1f02c52eb --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/advanced/PasswordProtectionExampleITCase.java @@ -0,0 +1,75 @@ +/* + * 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 org.apache.fesod.sheet.examples.advanced; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.examples.ExampleTestBase; +import org.apache.fesod.sheet.examples.write.data.DemoData; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Test for {@link PasswordProtectionExample}. + * + *

Verifies the full password-protection round-trip: writes a password-protected Excel file, + * then reads it back with the same password. Also validates the protected file is a readable + * workbook via a controlled write to {@code @TempDir}. + */ +class PasswordProtectionExampleITCase extends ExampleTestBase { + + @Test + void testPasswordRoundTrip() { + assertDoesNotThrow(() -> PasswordProtectionExample.main(new String[] {})); + } + + @Test + void testPasswordProtectedFileIsValid(@TempDir Path tempDir) { + String fileName = getTempOutputPath(tempDir, "password.xlsx"); + String password = "test123"; + + List data = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + DemoData d = new DemoData(); + d.setString("String" + i); + d.setDate(new Date()); + d.setDoubleData(0.56); + data.add(d); + } + + FesodSheet.write(fileName) + .password(password) + .head(DemoData.class) + .sheet("Test") + .doWrite(data); + + // Password-protected files cannot be opened without the password by POI WorkbookFactory, + // so we only verify the file exists and has a non-trivial size. + File file = new File(fileName); + assertTrue(file.exists(), "Password-protected file should exist"); + assertTrue(file.length() > 0, "Password-protected file should not be empty"); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/fill/FillData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/fill/FillBasicExampleITCase.java similarity index 59% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/fill/FillData.java rename to fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/fill/FillBasicExampleITCase.java index a469793e3..f279d36bb 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/fill/FillData.java +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/fill/FillBasicExampleITCase.java @@ -17,21 +17,22 @@ * under the License. */ -package org.apache.fesod.sheet.demo.fill; +package org.apache.fesod.sheet.examples.fill; -import java.util.Date; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.apache.fesod.sheet.examples.ExampleTestBase; +import org.junit.jupiter.api.Test; /** + * Test for {@link FillBasicExample}. * + *

Verifies the simple-fill example which fills data into an Excel template ({@code simple.xlsx}) + * using both object-based and map-based approaches. */ -@Getter -@Setter -@EqualsAndHashCode -public class FillData { - private String name; - private double number; - private Date date; +class FillBasicExampleITCase extends ExampleTestBase { + + @Test + void testSimpleFill() { + assertDoesNotThrow(FillBasicExample::simpleFill); + } } diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/WriteHandler.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/fill/FillComplexExampleITCase.java similarity index 59% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/WriteHandler.java rename to fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/fill/FillComplexExampleITCase.java index df5f52081..77c965dbd 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/WriteHandler.java +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/fill/FillComplexExampleITCase.java @@ -17,22 +17,22 @@ * under the License. */ -package org.apache.fesod.sheet.temp.simple; +package org.apache.fesod.sheet.examples.fill; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.write.handler.SheetWriteHandler; -import org.apache.fesod.sheet.write.metadata.holder.WriteSheetHolder; -import org.apache.fesod.sheet.write.metadata.holder.WriteWorkbookHolder; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.apache.fesod.sheet.examples.ExampleTestBase; +import org.junit.jupiter.api.Test; /** + * Test for {@link FillComplexExample}. * + *

Verifies the list-fill example which fills a list of {@code FillData} rows into + * a template ({@code list.xlsx}). Tests both single-pass and multi-pass fill methods. */ -@Slf4j -public class WriteHandler implements SheetWriteHandler { +class FillComplexExampleITCase extends ExampleTestBase { - @Override - public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) { - log.info("锁住"); - writeSheetHolder.getSheet().protectSheet("edit"); + @Test + void testListFill() { + assertDoesNotThrow(FillComplexExample::listFill); } } diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/quickstart/SimpleReadExampleITCase.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/quickstart/SimpleReadExampleITCase.java new file mode 100644 index 000000000..61b3dbe17 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/quickstart/SimpleReadExampleITCase.java @@ -0,0 +1,43 @@ +/* + * 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 org.apache.fesod.sheet.examples.quickstart; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.apache.fesod.sheet.examples.ExampleTestBase; +import org.junit.jupiter.api.Test; + +/** + * Test for {@link SimpleReadExample}. + * + *

Verifies that the quickstart read example can successfully read data from the bundled + * {@code demo.xlsx} resource without throwing any exceptions. + */ +class SimpleReadExampleITCase extends ExampleTestBase { + + @Test + void testSimpleRead() { + assertDoesNotThrow(SimpleReadExample::simpleRead); + } + + @Test + void testMain() { + assertDoesNotThrow(() -> SimpleReadExample.main(new String[] {})); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoCompatibleHeaderData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/quickstart/SimpleWriteExampleITCase.java similarity index 55% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoCompatibleHeaderData.java rename to fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/quickstart/SimpleWriteExampleITCase.java index a1a0e3beb..c0f4374c5 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoCompatibleHeaderData.java +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/quickstart/SimpleWriteExampleITCase.java @@ -17,24 +17,27 @@ * under the License. */ -package org.apache.fesod.sheet.demo.read; +package org.apache.fesod.sheet.examples.quickstart; -import java.util.Date; -import lombok.Data; -import org.apache.fesod.sheet.annotation.ExcelProperty; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.apache.fesod.sheet.examples.ExampleTestBase; +import org.junit.jupiter.api.Test; /** - * Compatible header data class. + * Test for {@link SimpleWriteExample}. + * + *

Verifies that the quickstart write example can produce an Excel file. The example writes + * 10 rows of {@code DemoData} to a temp file via {@code ExampleFileUtil.getTempPath()}. */ -@Data -public class DemoCompatibleHeaderData { - - @ExcelProperty("String") - private String string; +class SimpleWriteExampleITCase extends ExampleTestBase { - @ExcelProperty("Date") - private Date date; + @Test + void testSimpleWrite() { + assertDoesNotThrow(SimpleWriteExample::simpleWrite); + } - @ExcelProperty("DoubleData") - private Double doubleData; + @Test + void testMain() { + assertDoesNotThrow(() -> SimpleWriteExample.main(new String[] {})); + } } diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoExtraData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/BasicReadExampleITCase.java similarity index 60% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoExtraData.java rename to fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/BasicReadExampleITCase.java index c5ef63e65..6e09edc08 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoExtraData.java +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/BasicReadExampleITCase.java @@ -17,21 +17,22 @@ * under the License. */ -package org.apache.fesod.sheet.demo.read; +package org.apache.fesod.sheet.examples.read; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.apache.fesod.sheet.examples.ExampleTestBase; +import org.junit.jupiter.api.Test; /** + * Test for {@link BasicReadExample}. * + *

Verifies the basic read example which reads {@code demo.xlsx} using a typed + * {@code DemoDataListener} to process each row. */ -@Getter -@Setter -@EqualsAndHashCode -public class DemoExtraData { +class BasicReadExampleITCase extends ExampleTestBase { - private String row1; - - private String row2; + @Test + void testBasicRead() { + assertDoesNotThrow(BasicReadExample::basicRead); + } } diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/TestListener.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/ConverterReadExampleITCase.java similarity index 59% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/TestListener.java rename to fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/ConverterReadExampleITCase.java index 7d478a232..42fcc9eb7 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/TestListener.java +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/ConverterReadExampleITCase.java @@ -17,27 +17,22 @@ * under the License. */ -package org.apache.fesod.sheet.temp.read; +package org.apache.fesod.sheet.examples.read; -import com.alibaba.fastjson2.JSON; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.apache.fesod.sheet.examples.ExampleTestBase; +import org.junit.jupiter.api.Test; /** - * TODO + * Test for {@link ConverterReadExample}. * - * - * @date 2020/4/9 16:33 - **/ -@Slf4j -public class TestListener extends AnalysisEventListener { + *

Verifies that the converter read example can read {@code demo.xlsx} with a custom + * {@code CustomStringStringConverter} applied during the read process. + */ +class ConverterReadExampleITCase extends ExampleTestBase { - @Override - public void invoke(Object o, AnalysisContext analysisContext) { - log.info("解析一条:{}", JSON.toJSONString(o)); + @Test + void testConverterRead() { + assertDoesNotThrow(ConverterReadExample::converterRead); } - - @Override - public void doAfterAllAnalysed(AnalysisContext analysisContext) {} } diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/ExceptionHandlingExampleITCase.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/ExceptionHandlingExampleITCase.java new file mode 100644 index 000000000..9cdc41b79 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/ExceptionHandlingExampleITCase.java @@ -0,0 +1,38 @@ +/* + * 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 org.apache.fesod.sheet.examples.read; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.apache.fesod.sheet.examples.ExampleTestBase; +import org.junit.jupiter.api.Test; + +/** + * Test for {@link ExceptionHandlingExample}. + * + *

Verifies that the exception handling read example processes all rows from {@code demo.xlsx}, + * demonstrating proper error handling within the listener callback. + */ +class ExceptionHandlingExampleITCase extends ExampleTestBase { + + @Test + void testExceptionRead() { + assertDoesNotThrow(ExceptionHandlingExample::exceptionRead); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/UploadDAO.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/IndexOrNameReadExampleITCase.java similarity index 61% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/UploadDAO.java rename to fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/IndexOrNameReadExampleITCase.java index ad9a21aff..d3bc3e95a 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/web/UploadDAO.java +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/IndexOrNameReadExampleITCase.java @@ -17,20 +17,21 @@ * under the License. */ -package org.apache.fesod.sheet.demo.web; +package org.apache.fesod.sheet.examples.read; -import java.util.List; -import org.springframework.stereotype.Repository; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.apache.fesod.sheet.examples.ExampleTestBase; +import org.junit.jupiter.api.Test; /** - * 假设这个是你的DAO存储。当然还要这个类让spring管理,当然你不用需要存储,也不需要这个类。 + * Test for {@link IndexOrNameReadExample}. * - * - **/ -@Repository -public class UploadDAO { + *

Verifies reading Excel columns by index or name annotation from {@code demo.xlsx}. + */ +class IndexOrNameReadExampleITCase extends ExampleTestBase { - public void save(List list) { - // 如果是mybatis,尽量别直接调用多次insert,自己写一个mapper里面新增一个方法batchInsert,所有数据一次性插入 + @Test + void testIndexOrNameRead() { + assertDoesNotThrow(IndexOrNameReadExample::indexOrNameRead); } } diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/MultiSheetReadExampleITCase.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/MultiSheetReadExampleITCase.java new file mode 100644 index 000000000..bb575204b --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/MultiSheetReadExampleITCase.java @@ -0,0 +1,38 @@ +/* + * 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 org.apache.fesod.sheet.examples.read; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.apache.fesod.sheet.examples.ExampleTestBase; +import org.junit.jupiter.api.Test; + +/** + * Test for {@link MultiSheetReadExample}. + * + *

Verifies that the multi-sheet read example correctly reads the same file multiple times + * using different listeners, demonstrating sheet-level repeated read capability. + */ +class MultiSheetReadExampleITCase extends ExampleTestBase { + + @Test + void testMultiSheetRead() { + assertDoesNotThrow(MultiSheetReadExample::repeatedRead); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/NoModelReadExampleITCase.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/NoModelReadExampleITCase.java new file mode 100644 index 000000000..51d7b04a5 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/read/NoModelReadExampleITCase.java @@ -0,0 +1,38 @@ +/* + * 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 org.apache.fesod.sheet.examples.read; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.apache.fesod.sheet.examples.ExampleTestBase; +import org.junit.jupiter.api.Test; + +/** + * Test for {@link NoModelReadExample}. + * + *

Verifies that the no-model read example can read {@code demo.xlsx} without a pre-defined + * data class, using {@code Map} to receive each row's data. + */ +class NoModelReadExampleITCase extends ExampleTestBase { + + @Test + void testNoModelRead() { + assertDoesNotThrow(NoModelReadExample::noModelRead); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoDAO.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/web/FesodWebApplicationITCase.java similarity index 63% rename from fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoDAO.java rename to fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/web/FesodWebApplicationITCase.java index 92e22ea35..e34e14139 100644 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/demo/read/DemoDAO.java +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/web/FesodWebApplicationITCase.java @@ -17,18 +17,19 @@ * under the License. */ -package org.apache.fesod.sheet.demo.read; +package org.apache.fesod.sheet.examples.web; -import java.util.List; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; /** - * 假设这个是你的DAO存储。当然还要这个类让spring管理,当然你不用需要存储,也不需要这个类。 - * - * - **/ -public class DemoDAO { + * Integration test that verifies FesodWebApplication starts successfully. + */ +@SpringBootTest(classes = FesodWebApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +class FesodWebApplicationITCase { - public void save(List list) { - // 如果是mybatis,尽量别直接调用多次insert,自己写一个mapper里面新增一个方法batchInsert,所有数据一次性插入 + @Test + void contextLoads() { + // If the application context fails to start, this test will fail. } } diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/write/BasicWriteExampleITCase.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/write/BasicWriteExampleITCase.java new file mode 100644 index 000000000..6d2ecdf4e --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/write/BasicWriteExampleITCase.java @@ -0,0 +1,62 @@ +/* + * 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 org.apache.fesod.sheet.examples.write; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import java.io.File; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import org.apache.fesod.sheet.FesodSheet; +import org.apache.fesod.sheet.examples.ExampleTestBase; +import org.apache.fesod.sheet.examples.write.data.DemoData; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Test for {@link BasicWriteExample}. + * + *

Verifies: (1) the example completes without exception, and (2) a separate controlled write + * to a {@code @TempDir} produces a valid Excel workbook with the expected number of data rows. + */ +class BasicWriteExampleITCase extends ExampleTestBase { + + @Test + void testBasicWrite() { + assertDoesNotThrow(BasicWriteExample::basicWrite); + } + + @Test + void testWriteProducesValidExcel(@TempDir Path tempDir) { + String fileName = getTempOutputPath(tempDir, "basicWrite.xlsx"); + List data = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + DemoData d = new DemoData(); + d.setString("String" + i); + d.setDate(new Date()); + d.setDoubleData(0.56); + data.add(d); + } + FesodSheet.write(fileName, DemoData.class).sheet("Template").doWrite(data); + + assertValidExcelFile(new File(fileName), 10); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/write/MergeWriteExampleITCase.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/write/MergeWriteExampleITCase.java new file mode 100644 index 000000000..94103ea75 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/write/MergeWriteExampleITCase.java @@ -0,0 +1,38 @@ +/* + * 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 org.apache.fesod.sheet.examples.write; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.apache.fesod.sheet.examples.ExampleTestBase; +import org.junit.jupiter.api.Test; + +/** + * Test for {@link MergeWriteExample}. + * + *

Verifies both merge strategies: (1) annotation-based merge via {@code @ContentLoopMerge} + * and (2) programmatic merge via {@code LoopMergeStrategy}. Each strategy writes a separate file. + */ +class MergeWriteExampleITCase extends ExampleTestBase { + + @Test + void testMergeWrite() { + assertDoesNotThrow(MergeWriteExample::mergeWrite); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/write/StyleWriteExampleITCase.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/write/StyleWriteExampleITCase.java new file mode 100644 index 000000000..12d97d987 --- /dev/null +++ b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/examples/write/StyleWriteExampleITCase.java @@ -0,0 +1,38 @@ +/* + * 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 org.apache.fesod.sheet.examples.write; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import org.apache.fesod.sheet.examples.ExampleTestBase; +import org.junit.jupiter.api.Test; + +/** + * Test for {@link StyleWriteExample}. + * + *

Verifies that the style-write example can produce an Excel file with annotation-based + * cell styles ({@code @ContentStyle}, {@code @HeadStyle}) applied to a {@code DemoStyleData} model. + */ +class StyleWriteExampleITCase extends ExampleTestBase { + + @Test + void testStyleWrite() { + assertDoesNotThrow(StyleWriteExample::styleWrite); + } +} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/CamlData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/CamlData.java deleted file mode 100644 index a67d55f82..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/CamlData.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; - -/** - * - */ -@Getter -@Setter -@EqualsAndHashCode -public class CamlData { - private String string1; - private String String2; - private String sTring3; - private String STring4; - private String STRING5; - private String STRing6; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/DemoData2.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/DemoData2.java deleted file mode 100644 index 9a56c22b3..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/DemoData2.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp; - -import java.math.BigDecimal; -import java.util.Date; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelIgnore; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -/** - * 基础数据类 - * - * - **/ -@Getter -@Setter -@EqualsAndHashCode -public class DemoData2 { - @ExcelProperty("字符串标题") - private String string; - - @ExcelProperty("日期标题") - private Date date; - - @ExcelProperty("数字标题") - private Double doubleData; - - @ExcelProperty("数字标题2") - private BigDecimal bigDecimal; - /** - * 忽略这个字段 - */ - @ExcelIgnore - private String ignore; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/DemoData3.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/DemoData3.java deleted file mode 100644 index 22209f62f..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/DemoData3.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp; - -import java.time.LocalDateTime; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -/** - * 基础数据类 - * - * - **/ -@Getter -@Setter -@EqualsAndHashCode -public class DemoData3 { - @ExcelProperty("日期时间标题") - private LocalDateTime localDateTime; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/FillTempTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/FillTempTest.java deleted file mode 100644 index 0148e5737..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/FillTempTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.fesod.sheet.ExcelWriter; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.demo.fill.FillData; -import org.apache.fesod.sheet.temp.fill.FillData2; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.merge.OnceAbsoluteMergeStrategy; -import org.apache.fesod.sheet.write.metadata.WriteSheet; -import org.junit.jupiter.api.Test; - -/** - * 写的填充写法 - */ -public class FillTempTest { - - /** - * 复杂的填充 - */ - @Test - public void complexFill() { - // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替 - // {} 代表普通变量 {.} 代表是list的变量 - OnceAbsoluteMergeStrategy onceAbsoluteMergeStrategy = new OnceAbsoluteMergeStrategy(2, 2, 0, 1); - - String fileName = TestFileUtil.getPath() + "complexFill" + System.currentTimeMillis() + ".xlsx"; - ExcelWriter excelWriter = FastExcel.write(fileName) - .registerWriteHandler(onceAbsoluteMergeStrategy) - .withTemplate("src/test/resources/demo/fill/simple.xlsx") - .build(); - WriteSheet writeSheet0 = FastExcel.writerSheet(0).build(); - WriteSheet writeSheet1 = FastExcel.writerSheet(1).build(); - - excelWriter.fill(teamp(), writeSheet0); - excelWriter.fill(teamp(), writeSheet1); - - Map map = new HashMap(); - map.put("date", "2019年10月9日13:28:28"); - map.put("total", 1000); - excelWriter.fill(map, writeSheet0); - - excelWriter.finish(); - } - - /** - * 数据量大的复杂填充 - *

- * 这里的解决方案是 确保模板list为最后一行,然后再拼接table.还有03版没救,只能刚正面加内存。 - */ - @Test - public void complexFillWithTable() { - // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替 - // {} 代表普通变量 {.} 代表是list的变量 - // 这里模板 删除了list以后的数据,也就是统计的这一行 - String templateFileName = "src/test/resources/demo/fill/complexFillWithTable.xlsx"; - - String fileName = TestFileUtil.getPath() + "complexFillWithTable" + System.currentTimeMillis() + ".xlsx"; - ExcelWriter excelWriter = - FastExcel.write(fileName).withTemplate(templateFileName).build(); - WriteSheet writeSheet = FastExcel.writerSheet().build(); - // 直接写入数据 - excelWriter.fill(data(), writeSheet); - excelWriter.fill(data2(), writeSheet); - - // 写入list之前的数据 - Map map = new HashMap(); - map.put("date", "2019年10月9日13:28:28"); - excelWriter.fill(map, writeSheet); - - // list 后面还有个统计 想办法手动写入 - // 这里偷懒直接用list 也可以用对象 - List> totalListList = new ArrayList>(); - List totalList = new ArrayList(); - totalListList.add(totalList); - totalList.add(null); - totalList.add(null); - totalList.add(null); - // 第四列 - totalList.add("统计:1000"); - // 这里是write 别和fill 搞错了 - excelWriter.write(totalListList, writeSheet); - excelWriter.finish(); - // 总体上写法比较复杂 但是也没有想到好的版本 异步的去写入excel 不支持行的删除和移动,也不支持备注这种的写入,所以也排除了可以 - // 新建一个 然后一点点复制过来的方案,最后导致list需要新增行的时候,后面的列的数据没法后移,后续会继续想想解决方案 - } - - private List data2() { - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - FillData2 fillData = new FillData2(); - list.add(fillData); - fillData.setTest("ttttttt" + i); - } - return list; - } - - private List teamp() { - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - TempFillData fillData = new TempFillData(); - list.add(fillData); - fillData.setName("张三"); - fillData.setNumber(5.2); - } - return list; - } - - private List data() { - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - FillData fillData = new FillData(); - list.add(fillData); - fillData.setName("张三"); - fillData.setNumber(5.2); - } - return list; - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/Lock2Test.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/Lock2Test.java deleted file mode 100644 index 20f69f63f..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/Lock2Test.java +++ /dev/null @@ -1,501 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp; - -import com.alibaba.fastjson2.JSON; -import java.io.File; -import java.math.BigDecimal; -import java.math.MathContext; -import java.math.RoundingMode; -import java.nio.file.Path; -import java.text.DecimalFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.fesod.common.util.PositionUtils; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.demo.write.DemoData; -import org.apache.fesod.sheet.metadata.data.ReadCellData; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.metadata.style.WriteCellStyle; -import org.apache.fesod.sheet.write.metadata.style.WriteFont; -import org.apache.fesod.sheet.write.style.HorizontalCellStyleStrategy; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.util.CellReference; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -/** - * 临时测试 - * - * - **/ -@Slf4j -public class Lock2Test { - - @Test - public void test() throws Exception { - List list = FastExcel.read("src/test/resources/converter/converter07.xlsx") - // .useDefaultListener(false) - .sheet(0) - .headRowNumber(0) - .doReadSync(); - log.info("数据:{}", list.size()); - for (Object data : list) { - log.info("返回数据:{}", CollectionUtils.size(data)); - log.info("返回数据:{}", JSON.toJSONString(data)); - } - } - - @Test - public void test33() throws Exception { - File file = new File("src/test/resources/temp/lock_data.xlsx"); - - FastExcel.read(file, LockData.class, new LockDataListener()) - .sheet(0) - .headRowNumber(0) - .doRead(); - } - - @Test - public void write() throws Exception { - String fileName = TestFileUtil.getPath() + "styleWrite" + System.currentTimeMillis() + ".xlsx"; - // 头的策略 - WriteCellStyle headWriteCellStyle = new WriteCellStyle(); - // 背景设置为红色 - headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); - WriteFont headWriteFont = new WriteFont(); - headWriteFont.setFontHeightInPoints((short) 20); - headWriteCellStyle.setWriteFont(headWriteFont); - // 内容的策略 - WriteCellStyle contentWriteCellStyle = new WriteCellStyle(); - // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定 - contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND); - // 背景绿色 - contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex()); - WriteFont contentWriteFont = new WriteFont(); - // 字体大小 - contentWriteFont.setFontHeightInPoints((short) 20); - contentWriteCellStyle.setWriteFont(contentWriteFont); - // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现 - HorizontalCellStyleStrategy horizontalCellStyleStrategy = - new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle); - - // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 - FastExcel.write(fileName, DemoData.class) - .registerWriteHandler(horizontalCellStyleStrategy) - .sheet("模板") - .doWrite(data()); - } - - @Test - public void simpleWrite() { - String fileName = TestFileUtil.getPath() + System.currentTimeMillis() + ".xlsx"; - System.out.println(fileName); - FastExcel.write(fileName).head(head()).sheet("模板").doWrite(dataList()); - } - - private List> head() { - List> list = new ArrayList>(); - List head0 = new ArrayList(); - head0.add("表头"); - - list.add(head0); - return list; - } - - private List> dataList() { - List> list = new ArrayList>(); - List data = new ArrayList(); - data.add("字符串"); - data.add(new Date()); - data.add(0.56); - list.add(data); - return list; - } - - @Test - public void testc() throws Exception { - log.info("reslut:{}", JSON.toJSONString(new CellReference("B3"))); - } - - @Test - public void simpleRead() { - // 写法1: - String fileName = "src/test/resources/temp/lock_data.xlsx"; - // 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭 - FastExcel.read(fileName, LockData.class, new LockDataListener()) - .useDefaultListener(false) - .sheet() - .doRead(); - } - - @Test - public void test2(@TempDir Path tempDir) throws Exception { - File file = tempDir.resolve(System.currentTimeMillis() + ".xlsx").toFile(); - FastExcel.write().file(file).sheet().doWrite(dataList()); - List list = FastExcel.read(file).sheet().headRowNumber(0).doReadSync(); - log.info("数据:{}", list.size()); - for (Object data : list) { - log.info("返回数据:{}", JSON.toJSONString(data)); - } - log.info("文件状态:{}", file.exists()); - file.delete(); - } - - @Test - public void test335() throws Exception { - - log.info("reslut:{}", PositionUtils.getCol("A10", null)); - log.info("reslut:{}", PositionUtils.getRow("A10")); - log.info("reslut:{}", PositionUtils.getCol("AB10", null)); - log.info("reslut:{}", PositionUtils.getRow("AB10")); - - // log.info("reslut:{}", PositionUtils2.getCol("A10",null)); - // log.info("reslut:{}", PositionUtils2.getRow("A10")); - // log.info("reslut:{}", PositionUtils2.getCol("AB10",null)); - // log.info("reslut:{}", PositionUtils2.getRow("AB10")); - } - - @Test - public void numberforamt() throws Exception { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); - - // log.info("date:{}", - // NumberDataFormatterUtils.format(BigDecimal.valueOf(44727.99998842592), (short)200, "yyyy-MM-dd HH:mm:ss", - // null, - // null, null)); - // - // log.info("date:{}", - // NumberDataFormatterUtils.format(BigDecimal.valueOf(44728.99998842592), (short)200, "yyyy-MM-dd HH:mm:ss", - // null, - // null, null)); - // - // log.info("date:{}", - // NumberDataFormatterUtils.format(BigDecimal.valueOf(44729.99998836806), (short)200, "yyyy-MM-dd HH:mm:ss", - // null, - // null, null)); - // - // log.info("date:{}", - // NumberDataFormatterUtils.format(BigDecimal.valueOf(44727.99998842592).setScale(10, RoundingMode - // .HALF_UP), (short)200, "yyyy-MM-dd HH:mm:ss", - // null, - // null, null)); - // - // log.info("date:{}", - // NumberDataFormatterUtils.format(BigDecimal.valueOf(44728.99998842592).setScale(10, RoundingMode - // .HALF_UP), (short)200, "yyyy-MM-dd HH:mm:ss", - // null, - // null, null)); - - // 44729.9999883681 - // 44729.999988368058 - // log.info("date:{}", - // NumberDataFormatterUtils.format(BigDecimal.valueOf(44729.999988368058).setScale(10, RoundingMode - // .HALF_UP), (short)200, "yyyy-MM-dd HH:mm:ss", - // null, - // null, null)); - // log.info("date:{}",BigDecimal.valueOf(44729.999988368058).setScale(10, RoundingMode.HALF_UP).doubleValue - // ()); - - // 2022/6/17 23:59:59 - // 期望 44729.99998842592 - // log.info("data:{}", DateUtil.getJavaDate(44729.9999883681, true)); - log.info( - "data4:{}", - DateUtil.getJavaDate( - BigDecimal.valueOf(44729.999988368058) - .setScale(4, RoundingMode.HALF_UP) - .doubleValue(), - false)); - log.info( - "data5:{}", - DateUtil.getJavaDate( - BigDecimal.valueOf(44729.999988368058) - .setScale(5, RoundingMode.HALF_UP) - .doubleValue(), - false)); - log.info( - "data6:{}", - DateUtil.getJavaDate( - BigDecimal.valueOf(44729.999988368058) - .setScale(6, RoundingMode.HALF_UP) - .doubleValue(), - false)); - log.info( - "data7:{}", - DateUtil.getJavaDate( - BigDecimal.valueOf(44729.999988368058) - .setScale(7, RoundingMode.HALF_UP) - .doubleValue(), - false)); - log.info( - "data8:{}", - DateUtil.getJavaDate( - BigDecimal.valueOf(44729.999988368058) - .setScale(8, RoundingMode.HALF_UP) - .doubleValue(), - false)); - - log.info("data:{}", format.format(DateUtil.getJavaDate(44729.999988368058, false))); - log.info("data:{}", format.format(DateUtil.getJavaDate(44729.9999883681, false))); - - log.info("data:{}", DateUtil.getJavaDate(Double.parseDouble("44729.999988368058"), false)); - log.info("data:{}", DateUtil.getJavaDate(Double.parseDouble("44729.9999883681"), false)); - - // 44729.999976851854 - // 44729.999988368058 - Assertions.assertThrows(ParseException.class, () -> DateUtil.getExcelDate(format.parse("2022-06-17 23:59:58"))); - // 44729.99998842592 - Assertions.assertThrows(ParseException.class, () -> DateUtil.getExcelDate(format.parse("2022-06-17 23:59:59"))); - - log.info( - "data:{}", - DateUtil.getJavaDate( - BigDecimal.valueOf(44729.999976851854) - .setScale(10, RoundingMode.HALF_UP) - .doubleValue(), - false)); - log.info( - "data:{}", - DateUtil.getJavaDate( - BigDecimal.valueOf(44729.99998842592) - .setScale(10, RoundingMode.HALF_UP) - .doubleValue(), - false)); - - log.info( - "data:{}", - DateUtil.getJavaDate( - BigDecimal.valueOf(44729.999976851854) - .setScale(5, RoundingMode.HALF_UP) - .doubleValue(), - false)); - log.info( - "data:{}", - DateUtil.getJavaDate( - BigDecimal.valueOf(44729.99998842592) - .setScale(5, RoundingMode.HALF_UP) - .doubleValue(), - false)); - } - - @Test - public void testDate() throws Exception { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - log.info("TT:{}", format.format(new Date(100L))); - log.info("TT:{}", new Date().getTime()); - } - - @Test - public void testDateAll() throws Exception { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); - - long dateTime = 0L; - while (true) { - Date date = new Date(dateTime); - double excelDate = DateUtil.getExcelDate(date); - // odd assertion comment at 2025-03 - // Assertions.assertEquals("测试基本转换错误" + dateTime, format.format(date), - // format.format(DateUtil.getJavaDate(excelDate, false))); - // Assertions.assertEquals("测试精度5转换错误" + dateTime, format.format(date), - // format.format(DateUtil.getJavaDate(BigDecimal.valueOf(excelDate) - // .setScale(10, RoundingMode.HALF_UP).doubleValue(), false))); - log.info( - "date:{}", - format2.format(DateUtil.getJavaDate(BigDecimal.valueOf(excelDate) - .setScale(10, RoundingMode.HALF_UP) - .doubleValue()))); - dateTime += 100000000000L; - // 30天输出 - if (dateTime % (24 * 60 * 60 * 1000) == 0) { - log.info("{}成功", format.format(date)); - } - if (dateTime > 1673957544750L) { - log.info("结束啦"); - break; - } - } - log.info("结束啦"); - } - - @Test - public void numberforamt3() throws Exception { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); - - List> list = FastExcel.read("src/test/resources/temp/number_format.xlsx") - .useDefaultListener(false) - .sheet(0) - .headRowNumber(0) - .doReadSync(); - log.info("数据:{}", list.size()); - for (Map readCellDataMap : list) { - ReadCellData data = readCellDataMap.get(0); - log.info( - "data:{}", - format.format(DateUtil.getJavaDate( - data.getNumberValue() - .setScale(10, RoundingMode.HALF_UP) - .doubleValue(), - false))); - } - // - // log.info("data:{}", format.format(DateUtil.getJavaDate(44727.999988425923, false))); - // log.info("data:{}", format.format(DateUtil.getJavaDate(44729.999988368058, false))); - - } - - @Test - public void numberforamt4() throws Exception { - String fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx"; - // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 - // 如果这里想使用03 则 传入excelType参数即可 - FastExcel.write(fileName, DemoData.class).sheet("模板").doWrite(() -> { - // 分页查询数据 - return data2(); - }); - } - - @Test - public void numberforamt77() throws Exception { - String fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx"; - // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 - // 如果这里想使用03 则 传入excelType参数即可 - FastExcel.write(fileName, DemoData3.class).sheet("模板").doWrite(() -> { - List list = new ArrayList<>(); - DemoData3 demoData3 = new DemoData3(); - demoData3.setLocalDateTime(LocalDateTime.of(2023, 1, 1, 0, 0, 0, 400000000)); - list.add(demoData3); - demoData3 = new DemoData3(); - demoData3.setLocalDateTime(LocalDateTime.of(2023, 1, 1, 0, 0, 0, 499000000)); - list.add(demoData3); - demoData3 = new DemoData3(); - demoData3.setLocalDateTime(LocalDateTime.of(2023, 1, 1, 0, 0, 0, 500000000)); - list.add(demoData3); - demoData3 = new DemoData3(); - demoData3.setLocalDateTime(LocalDateTime.of(2023, 1, 1, 0, 0, 0, 501000000)); - list.add(demoData3); - demoData3 = new DemoData3(); - demoData3.setLocalDateTime(LocalDateTime.of(2023, 1, 1, 0, 0, 0, 995000000)); - list.add(demoData3); - return list; - }); - } - - @Test - public void numberforamt99() throws Exception { - LocalDateTime localDateTime = LocalDateTime.of(2023, 1, 1, 0, 0, 0, 995000000); - log.info("date:{}", localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))); - } - - @Test - public void numberforamt5() throws Exception { - String fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".xlsx"; - // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 - // 如果这里想使用03 则 传入excelType参数即可 - FastExcel.write(fileName, DemoData.class).sheet("模板").doWrite(() -> { - // 分页查询数据 - return data3(); - }); - } - - @Test - public void numberforamt6() throws Exception { - DecimalFormat decimalFormat = new DecimalFormat("#.#"); - BigDecimal bigDecimal = new BigDecimal(3101011021236149800L); - log.info("b:{}", bigDecimal); - log.info("b:{}", bigDecimal.setScale(-4, RoundingMode.HALF_UP)); - log.info("b:{}", decimalFormat.format(bigDecimal.setScale(-4, RoundingMode.HALF_UP))); - } - - @Test - public void numberforamt7() throws Exception { - DecimalFormat decimalFormat = new DecimalFormat("#.#"); - BigDecimal bigDecimal = new BigDecimal(3.1010110212361498E+18).round(new MathContext(15, RoundingMode.HALF_UP)); - // bigDecimal. - - // bigDecimal - log.info("b:{}", bigDecimal); - log.info("b:{}", bigDecimal.setScale(-4, RoundingMode.HALF_UP)); - log.info("b:{}", decimalFormat.format(bigDecimal.setScale(-4, RoundingMode.HALF_UP))); - log.info("b:{}", decimalFormat.format(bigDecimal)); - } - - private List data3() { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); - - List list = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - DemoData2 data = new DemoData2(); - data.setString("字符串" + i); - data.setDoubleData(0.56); - data.setBigDecimal(BigDecimal.valueOf(3101011021236149800L)); - list.add(data); - } - return list; - } - - private List data() { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); - - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - DemoData data = new DemoData(); - data.setString("字符串" + i); - try { - data.setDate(format.parse("2032-01-18 09:00:01.995")); - } catch (ParseException e) { - throw new RuntimeException(e); - } - data.setDoubleData(0.56); - list.add(data); - } - return list; - } - - private List data2() { - SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss."); - - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - DemoData data = new DemoData(); - data.setString("字符串" + i); - try { - data.setDate(format.parse("2032-01-18 09:00:00.")); - } catch (ParseException e) { - throw new RuntimeException(e); - } - data.setDoubleData(0.56); - list.add(data); - } - return list; - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/LockData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/LockData.java deleted file mode 100644 index 09cd1588d..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/LockData.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.format.NumberFormat; - -/** - * 基础数据类.这里的排序和excel里面的排序一致 - * - * - **/ -@Getter -@Setter -@EqualsAndHashCode -public class LockData { - @NumberFormat("#.##%") - private Double string0; - - private String string1; - private String string2; - private String string3; - private String string4; - private String string5; - private String string6; - private String string7; - private String string8; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/LockDataListener.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/LockDataListener.java deleted file mode 100644 index 4fb9d688f..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/LockDataListener.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp; - -import com.alibaba.fastjson2.JSON; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; - -/** - * 模板的读取类 - * - * - */ -@Slf4j -public class LockDataListener extends AnalysisEventListener { - /** - * 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收 - */ - private static final int BATCH_COUNT = 5; - - List list = new ArrayList(); - - @Override - public void invoke(LockData data, AnalysisContext context) { - log.info("解析到一条数据:{}", JSON.toJSONString(data)); - list.add(data); - if (list.size() >= BATCH_COUNT) { - saveData(); - list.clear(); - } - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - saveData(); - log.info("所有数据解析完成!"); - } - - /** - * 加上存储数据库 - */ - private void saveData() { - log.info("{}条数据,开始存储数据库!", list.size()); - log.info("存储数据库成功!"); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/LockTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/LockTest.java deleted file mode 100644 index 4b451e40f..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/LockTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp; - -import com.alibaba.fastjson2.JSON; -import java.io.FileInputStream; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.FastExcel; -import org.junit.jupiter.api.Test; - -/** - * 临时测试 - * - * - **/ -@Slf4j -public class LockTest { - - @Test - public void test() throws Exception { - List list = FastExcel.read(new FileInputStream("src/test/resources/simple/simple07.xlsx")) - .useDefaultListener(false) - .doReadAllSync(); - for (Object data : list) { - log.info("返回数据:{}", JSON.toJSONString(data)); - } - } - - @Test - public void test2() throws Exception { - List list = FastExcel.read(new FileInputStream("src/test/resources/simple/simple07.xlsx")) - .sheet() - .headRowNumber(0) - .doReadSync(); - for (Object data : list) { - log.info("返回数据:{}", ((Map) data).size()); - log.info("返回数据:{}", JSON.toJSONString(data)); - } - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/StyleData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/StyleData.java deleted file mode 100644 index a3a38d2df..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/StyleData.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp; - -import java.util.List; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; - -/** - * - **/ -@Getter -@Setter -@EqualsAndHashCode -public class StyleData { - private byte[] byteValue; - private Byte[] byteValue2; - private byte byteValue1; - private Byte byteValue4; - private byte byteValue3; - private String[] ss; - private List s1s; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/StyleTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/StyleTest.java deleted file mode 100644 index d2f58321f..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/StyleTest.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp; - -import java.io.InputStream; -import java.lang.reflect.Field; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.Date; -import lombok.extern.slf4j.Slf4j; -import org.apache.poi.ss.usermodel.BuiltinFormats; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.ExcelStyleDateFormatter; -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.ss.usermodel.WorkbookFactory; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -/** - * 临时测试 - * - * - **/ -@Slf4j -public class StyleTest { - - @Test - public void poi07Test() throws Exception { - InputStream is = Files.newInputStream(Paths.get("src/test/resources/style/styleTest.xlsx")); - Workbook workbook = WorkbookFactory.create(is); // 这种方式 Excel 2003/2007/2010 都是可以处理的 - Sheet sheet = workbook.getSheetAt(0); - Row hssfRow = sheet.getRow(0); - Assertions.assertEquals(1.0, hssfRow.getCell(0).getNumericCellValue()); - Assertions.assertEquals(1.0, hssfRow.getCell(1).getNumericCellValue()); - Assertions.assertEquals(1.0, hssfRow.getCell(2).getNumericCellValue()); - Assertions.assertEquals(1.0, hssfRow.getCell(3).getNumericCellValue()); - Assertions.assertEquals(14, hssfRow.getCell(0).getCellStyle().getDataFormat()); - Assertions.assertEquals(0, hssfRow.getCell(1).getCellStyle().getDataFormat()); - Assertions.assertEquals(10, hssfRow.getCell(2).getCellStyle().getDataFormat()); - Assertions.assertEquals(49, hssfRow.getCell(3).getCellStyle().getDataFormat()); - Assertions.assertEquals("m/d/yy", hssfRow.getCell(0).getCellStyle().getDataFormatString()); - Assertions.assertEquals("General", hssfRow.getCell(1).getCellStyle().getDataFormatString()); - Assertions.assertEquals("0.00%", hssfRow.getCell(2).getCellStyle().getDataFormatString()); - Assertions.assertEquals("@", hssfRow.getCell(3).getCellStyle().getDataFormatString()); - Assertions.assertTrue(isDate(hssfRow.getCell(0))); - Assertions.assertFalse(isDate(hssfRow.getCell(1))); - Assertions.assertFalse(isDate(hssfRow.getCell(2))); - Assertions.assertFalse(isDate(hssfRow.getCell(3))); - } - - @Test - public void poi03Test() throws Exception { - InputStream is = Files.newInputStream(Paths.get("src/test/resources/style/styleTest.xls")); - Workbook workbook = WorkbookFactory.create(is); // 这种方式 Excel 2003/2007/2010 都是可以处理的 - Sheet sheet = workbook.getSheetAt(0); - Row hssfRow = sheet.getRow(0); - Assertions.assertEquals(1.0, hssfRow.getCell(0).getNumericCellValue()); - Assertions.assertEquals(1.0, hssfRow.getCell(1).getNumericCellValue()); - Assertions.assertEquals(1.0, hssfRow.getCell(2).getNumericCellValue()); - Assertions.assertEquals(1.0, hssfRow.getCell(3).getNumericCellValue()); - Assertions.assertEquals(14, hssfRow.getCell(0).getCellStyle().getDataFormat()); - Assertions.assertEquals(0, hssfRow.getCell(1).getCellStyle().getDataFormat()); - Assertions.assertEquals(10, hssfRow.getCell(2).getCellStyle().getDataFormat()); - Assertions.assertEquals(49, hssfRow.getCell(3).getCellStyle().getDataFormat()); - Assertions.assertEquals("m/d/yy", hssfRow.getCell(0).getCellStyle().getDataFormatString()); - Assertions.assertEquals("General", hssfRow.getCell(1).getCellStyle().getDataFormatString()); - Assertions.assertEquals("0.00%", hssfRow.getCell(2).getCellStyle().getDataFormatString()); - Assertions.assertEquals("@", hssfRow.getCell(3).getCellStyle().getDataFormatString()); - Assertions.assertTrue(isDate(hssfRow.getCell(0))); - Assertions.assertFalse(isDate(hssfRow.getCell(1))); - Assertions.assertFalse(isDate(hssfRow.getCell(2))); - Assertions.assertFalse(isDate(hssfRow.getCell(3))); - } - - @Test - public void testFormatter() throws Exception { - ExcelStyleDateFormatter ff = new ExcelStyleDateFormatter("yyyy年m月d日"); - - System.out.println(ff.format(new Date())); - } - - @Test - public void testFormatter2() throws Exception { - StyleData styleData = new StyleData(); - Field field = styleData.getClass().getDeclaredField("byteValue"); - log.info("field:{}", field.getType().getName()); - field = styleData.getClass().getDeclaredField("byteValue2"); - log.info("field:{}", field.getType().getName()); - field = styleData.getClass().getDeclaredField("byteValue4"); - log.info("field:{}", field.getType()); - field = styleData.getClass().getDeclaredField("byteValue3"); - log.info("field:{}", field.getType()); - } - - @Test - public void testFormatter3() throws Exception { - log.info("field:{}", Byte.class == Byte.class); - } - - private boolean isDate(Cell cell) { - return DateUtil.isADateFormat( - cell.getCellStyle().getDataFormat(), cell.getCellStyle().getDataFormatString()); - } - - @Test - public void testBuiltinFormats() throws Exception { - System.out.println(BuiltinFormats.getBuiltinFormat(48)); - System.out.println(BuiltinFormats.getBuiltinFormat(57)); - System.out.println(BuiltinFormats.getBuiltinFormat(28)); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/TempFillData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/TempFillData.java deleted file mode 100644 index 4d230a447..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/TempFillData.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.write.style.ContentRowHeight; - -/** - * - */ -@Getter -@Setter -@EqualsAndHashCode -@ContentRowHeight(30) -public class TempFillData { - private String name; - private double number; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/WriteLargeTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/WriteLargeTest.java deleted file mode 100644 index 33f6f38a7..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/WriteLargeTest.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.ExcelWriter; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.read.listener.PageReadListener; -import org.apache.fesod.sheet.temp.large.LargeData; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.metadata.WriteSheet; -import org.apache.fesod.sheet.write.metadata.style.WriteCellStyle; -import org.apache.fesod.sheet.write.metadata.style.WriteFont; -import org.apache.fesod.sheet.write.style.HorizontalCellStyleStrategy; -import org.apache.poi.hssf.eventusermodel.HSSFEventFactory; -import org.apache.poi.hssf.eventusermodel.HSSFListener; -import org.apache.poi.hssf.eventusermodel.HSSFRequest; -import org.apache.poi.hssf.record.BOFRecord; -import org.apache.poi.hssf.record.BoundSheetRecord; -import org.apache.poi.hssf.record.Record; -import org.apache.poi.hssf.record.SSTRecord; -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.junit.jupiter.api.Test; - -/** - * - */ -@Slf4j -public class WriteLargeTest { - - @Test - public void test() throws Exception { - // 方法2 如果写到不同的sheet 同一个对象 - String fileName = TestFileUtil.getPath() + "large" + System.currentTimeMillis() + ".xlsx"; - // 头的策略 - WriteCellStyle headWriteCellStyle = new WriteCellStyle(); - // 背景设置为红色 - headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); - WriteFont headWriteFont = new WriteFont(); - headWriteFont.setFontHeightInPoints((short) 20); - headWriteCellStyle.setWriteFont(headWriteFont); - // 内容的策略 - WriteCellStyle contentWriteCellStyle = new WriteCellStyle(); - // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定 - contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND); - // 背景绿色 - contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex()); - WriteFont contentWriteFont = new WriteFont(); - // 字体大小 - contentWriteFont.setFontHeightInPoints((short) 20); - contentWriteCellStyle.setWriteFont(contentWriteFont); - // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现 - HorizontalCellStyleStrategy horizontalCellStyleStrategy = - new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle); - - ExcelWriter excelWriter = FastExcel.write(fileName, LargeData.class) - .registerWriteHandler(horizontalCellStyleStrategy) - .build(); - WriteSheet writeSheet = FastExcel.writerSheet().build(); - for (int j = 0; j < 100; j++) { - excelWriter.write(data(), writeSheet); - log.info("{} fill success.", j); - } - excelWriter.finish(); - } - - @Test - public void read() throws Exception { - log.info("start"); - String fileName = "src/test/resources/poi/last_row_number_xssf_date_test.xls"; - // 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭 - // 这里默认每次会读取100条数据 然后返回过来 直接调用使用数据就行 - // 具体需要返回多少行可以在`PageReadListener`的构造函数设置 - FastExcel.read(fileName, new PageReadListener>>(dataList -> { - log.info("SIZEL:{}", dataList.size()); - })) - .sheet() - .doRead(); - - log.info("test"); - } - - @Test - public void read2() throws Exception { - // 使用输入的文件创建一个新的文件输入流 - // FileInputStream fin = new FileInputStream("/Users/zhuangjiaju/Downloads/1e9e0578a9634abbbbd9b67f338f142a - // .xls"); - // 创建一个新的org.apache.poi.poifs.filesystem.Filesystem - POIFSFileSystem poifs = - new POIFSFileSystem(new File("src/test/resources/poi/last_row_number_xssf_date_test.xls")); - // 在InputStream中获取Workbook流 - InputStream din = poifs.createDocumentInputStream("Workbook"); - // 构造出HSSFRequest对象 - HSSFRequest req = new HSSFRequest(); - // 注册全部的监听器 - req.addListenerForAllRecords(new EventExample()); - // 创建事件工厂 - HSSFEventFactory factory = new HSSFEventFactory(); - // 根据文档输入流处理我们监听的事件 - factory.processEvents(req, din); - // 关闭文件输入流 - // fin.close(); - // 关闭文档输入流 - din.close(); - System.out.println("读取结束"); - } - - @Test - public void read3() throws Exception { - HSSFWorkbook hwb = - new HSSFWorkbook(new FileInputStream("src/test/resources/poi/last_row_number_xssf_date_test.xls")); - HSSFSheet sheet = hwb.getSheetAt(0); - HSSFRow row = null; - HSSFCell cell = null; - for (int i = sheet.getFirstRowNum(); i <= sheet.getPhysicalNumberOfRows(); i++) { - row = sheet.getRow(i); - if (row != null) { - log.info("r:{}", row.getRowNum()); - } - } - - log.info("end"); - } - - public static class EventExample implements HSSFListener { - private SSTRecord sstrec; - - /** - * 此方法监听传入记录并根据需要处理它们 - * - * @param record 读取时找到的记录 - */ - public void processRecord(Record record) { - switch (record.getSid()) { - // BOFRecord可以表示工作表或工作簿的开头 - case BOFRecord.sid: - BOFRecord bof = (BOFRecord) record; - if (bof.getType() == BOFRecord.TYPE_WORKBOOK) { - System.out.println("监听到工作表"); - } else if (bof.getType() == BOFRecord.TYPE_WORKSHEET) { - System.out.println("监听到工作簿"); - } - break; - case BoundSheetRecord.sid: - BoundSheetRecord bsr = (BoundSheetRecord) record; - System.out.println("工作簿名称: " + bsr.getSheetname()); - break; - } - } - } - - @Test - public void test2() throws Exception { - // 方法2 如果写到不同的sheet 同一个对象 - String fileName = TestFileUtil.getPath() + "large" + System.currentTimeMillis() + ".xlsx"; - - ExcelWriter excelWriter = FastExcel.write(fileName, LargeData.class).build(); - WriteSheet writeSheet = FastExcel.writerSheet().build(); - for (int j = 0; j < 100; j++) { - excelWriter.write(data(), writeSheet); - log.info("{} fill success.", j); - } - excelWriter.finish(); - } - - private List> data() { - List> list = new ArrayList<>(); - - for (int j = 0; j < 10000; j++) { - List oneRow = new ArrayList<>(); - for (int i = 0; i < 150; i++) { - oneRow.add("这是测试字段" + i); - } - list.add(oneRow); - } - - return list; - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/WriteV33Test.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/WriteV33Test.java deleted file mode 100644 index e5f38f141..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/WriteV33Test.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import org.apache.fesod.common.util.BooleanUtils; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.demo.write.DemoData; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.handler.CellWriteHandler; -import org.apache.fesod.sheet.write.handler.context.CellWriteHandlerContext; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Workbook; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -/** - * 临时测试 - * - * - **/ -public class WriteV33Test { - - @Test - public void handlerStyleWrite() { - // 方法1 使用已有的策略 推荐 - // HorizontalCellStyleStrategy 每一行的样式都一样 或者隔行一样 - // AbstractVerticalCellStyleStrategy 每一列的样式都一样 需要自己回调每一页 - String fileName = TestFileUtil.getPath() + "handlerStyleWrite" + System.currentTimeMillis() + ".xlsx"; - //// 头的策略 - // WriteCellStyle headWriteCellStyle = new WriteCellStyle(); - //// 背景设置为红色 - // headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); - // WriteFont headWriteFont = new WriteFont(); - // headWriteFont.setFontHeightInPoints((short)20); - // headWriteCellStyle.setWriteFont(headWriteFont); - //// 内容的策略 - // WriteCellStyle contentWriteCellStyle = new WriteCellStyle(); - //// 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定 - // contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND); - //// 背景绿色 - // contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex()); - // WriteFont contentWriteFont = new WriteFont(); - //// 字体大小 - // contentWriteFont.setFontHeightInPoints((short)20); - // contentWriteCellStyle.setWriteFont(contentWriteFont); - //// 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现 - // HorizontalCellStyleStrategy horizontalCellStyleStrategy = - // new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle); - // - //// 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 - // FastExcel.write(fileName, DemoData.class) - // .registerWriteHandler(horizontalCellStyleStrategy) - // .sheet("模板") - // .doWrite(data()); - // - // 方法2: 使用FastExcel的方式完全自己写 不太推荐 尽量使用已有策略 - // fileName = TestFileUtil.getPath() + "handlerStyleWrite" + System.currentTimeMillis() + ".xlsx"; - // FastExcel.write(fileName, DemoData.class) - // .registerWriteHandler(new CellWriteHandler() { - // @Override - // public void afterCellDispose(CellWriteHandlerContext context) { - // // 当前事件会在 数据设置到poi的cell里面才会回调 - // // 判断不是头的情况 如果是fill 的情况 这里会==null 所以用not true - // if (BooleanUtils.isNotTrue(context.getHead())) { - // // 第一个单元格 - // // 只要不是头 一定会有数据 当然fill的情况 可能要context.getCellDataList() ,这个需要看模板,因为一个单元格会有多个 WriteCellData - // WriteCellData cellData = context.getFirstCellData(); - // // 这里需要去cellData 获取样式 - // // 很重要的一个原因是 WriteCellStyle 和 dataFormatData绑定的 简单的说 比如你加了 DateTimeFormat - // // ,已经将writeCellStyle里面的dataFormatData 改了 如果你自己new了一个WriteCellStyle,可能注解的样式就失效了 - // // 然后 getOrCreateStyle 用于返回一个样式,如果为空,则创建一个后返回 - // WriteCellStyle writeCellStyle = cellData.getOrCreateStyle(); - // writeCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); - // // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND - // writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND); - // - // // 这样样式就设置好了 后面有个FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到 cell里面去 所以可以不用管了 - // } - // } - // }).sheet("模板") - // .doWrite(data()); - - // 方法3: 使用poi的样式完全自己写 不推荐 - // 坑1:style里面有dataformat 用来格式化数据的 所以自己设置可能导致格式化注解不生效 - // 坑2:不要一直去创建style 记得缓存起来 最多创建6W个就挂了 - fileName = TestFileUtil.getPath() + "handlerStyleWrite" + System.currentTimeMillis() + ".xlsx"; - FastExcel.write(fileName, DemoData.class) - .registerWriteHandler(new CellWriteHandler() { - @Override - public void afterCellDispose(CellWriteHandlerContext context) { - // 当前事件会在 数据设置到poi的cell里面才会回调 - // 判断不是头的情况 如果是fill 的情况 这里会==null 所以用not true - if (BooleanUtils.isNotTrue(context.getHead())) { - Cell cell = context.getCell(); - // 拿到poi的workbook - Workbook workbook = context.getWriteWorkbookHolder().getWorkbook(); - // 这里千万记住 想办法能复用的地方把他缓存起来 一个表格最多创建6W个样式 - // 不同单元格尽量传同一个 cellStyle - CellStyle cellStyle = workbook.createCellStyle(); - cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); - // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND - cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - cell.setCellStyle(cellStyle); - - // 由于这里没有指定datafrmat 所以格式化出来的数据需要 - - // 这里要把 WriteCellData的样式清空, 不然后面还有一个拦截器 FillStyleCellWriteHandler 默认会将 WriteCellStyle 设置到 - // cell里面去 会导致自己设置的不一样 - context.getFirstCellData().setWriteCellStyle(null); - } - } - }) - .sheet("模板") - .doWrite(data()); - } - - private List data() { - List list = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - DemoData data = new DemoData(); - data.setString("字符串" + i); - data.setDate(new Date()); - data.setDoubleData(0.56); - list.add(data); - } - return list; - } - - @Test - public void test4(@TempDir Path tempDir) throws Exception { - Path path = Files.createTempFile(tempDir, System.currentTimeMillis() + "", ".jpg"); - System.out.println(path); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/WriteV34Test.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/WriteV34Test.java deleted file mode 100644 index c812f6bff..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/WriteV34Test.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp; - -import java.util.ArrayList; -import java.util.List; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.demo.read.DemoData; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.metadata.style.WriteCellStyle; -import org.apache.fesod.sheet.write.metadata.style.WriteFont; -import org.apache.fesod.sheet.write.style.HorizontalCellStyleStrategy; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.junit.jupiter.api.Test; - -/** - * 临时测试 - * - * - **/ -public class WriteV34Test { - - @Test - public void test() throws Exception { - String fileName = TestFileUtil.getPath() + "handlerStyleWrite" + System.currentTimeMillis() + ".xlsx"; - // 头的策略 - WriteCellStyle headWriteCellStyle = new WriteCellStyle(); - // 背景设置为红色 - headWriteCellStyle.setFillForegroundColor(IndexedColors.RED.getIndex()); - WriteFont headWriteFont = new WriteFont(); - headWriteFont.setFontHeightInPoints((short) 20); - headWriteCellStyle.setWriteFont(headWriteFont); - // 内容的策略 - WriteCellStyle contentWriteCellStyle = new WriteCellStyle(); - // 这里需要指定 FillPatternType 为FillPatternType.SOLID_FOREGROUND 不然无法显示背景颜色.头默认了 FillPatternType所以可以不指定 - contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND); - // 背景绿色 - contentWriteCellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex()); - WriteFont contentWriteFont = new WriteFont(); - // 字体大小 - contentWriteFont.setFontHeightInPoints((short) 20); - contentWriteCellStyle.setWriteFont(contentWriteFont); - // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现 - HorizontalCellStyleStrategy horizontalCellStyleStrategy = - new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle); - - // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 - FastExcel.write(fileName, DemoData.class) - .head(head()) - .registerWriteHandler(horizontalCellStyleStrategy) - .sheet("模板") - .doWrite(data(1)); - } - - private List> head() { - List> list = new ArrayList>(); - List head0 = new ArrayList(); - head0.add("字符串" + System.currentTimeMillis()); - head0.add("再找找"); - List head1 = new ArrayList(); - head1.add("数字" + System.currentTimeMillis()); - List head2 = new ArrayList(); - head2.add("日期" + System.currentTimeMillis()); - list.add(head0); - list.add(head1); - list.add(head2); - return list; - } - - private List data(int no) { - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - DemoData data = new DemoData(); - data.setString("字符串" + no + "---" + i); - list.add(data); - } - return list; - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/Xls03Test.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/Xls03Test.java deleted file mode 100644 index 25a8fc055..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/Xls03Test.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp; - -import com.alibaba.fastjson2.JSON; -import java.nio.file.Path; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.shaded.cglib.beans.BeanMap; -import org.apache.fesod.shaded.cglib.core.DebuggingClassWriter; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.util.BeanMapUtils; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -/** - * 临时测试 - * - * - **/ -@Slf4j -public class Xls03Test { - - @TempDir - Path tempDir; - - @Test - public void test() { - List list = FastExcel.read("src/test/resources/compatibility/t07.xlsx") - .sheet() - .doReadSync(); - for (Object data : list) { - log.info("返回数据:{}", JSON.toJSONString(data)); - } - } - - @Test - public void test2() { - System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true"); - System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, tempDir.toString()); - - CamlData camlData = new CamlData(); - // camlData.setTest("test2"); - // camlData.setAEst("test3"); - // camlData.setTEST("test4"); - - BeanMap beanMap = BeanMapUtils.create(camlData); - - log.info("test:{}", beanMap.get("test")); - log.info("test:{}", beanMap.get("Test")); - log.info("test:{}", beanMap.get("TEst")); - log.info("test:{}", beanMap.get("TEST")); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/bug/DataType.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/bug/DataType.java deleted file mode 100644 index bdb95c926..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/bug/DataType.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.bug; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -/** - */ -@Getter -@Setter -@EqualsAndHashCode -public class DataType { - /** - * 任务id - */ - @ExcelProperty("任务ID") - private Integer id; - - @ExcelProperty("多余字段1") - private String firstSurplus; - - @ExcelProperty("多余字段2") - private String secSurplus; - - @ExcelProperty("多余字段3") - private String thirdSurplus; - - @ExcelProperty(value = "备注1") - private String firstRemark; - - @ExcelProperty(value = "备注2") - private String secRemark; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/bug/ExcelCreat.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/bug/ExcelCreat.java deleted file mode 100644 index d24bc4c41..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/bug/ExcelCreat.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.bug; - -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.util.Collections; -import java.util.List; -import org.apache.fesod.sheet.ExcelWriter; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.write.metadata.WriteSheet; - -/** - */ -public class ExcelCreat { - - public static void main(String[] args) throws FileNotFoundException { - List data = getData(); - ExcelWriter excelWriter = null; - excelWriter = FastExcel.write(new FileOutputStream("all.xlsx")).build(); - WriteSheet writeSheet = - FastExcel.writerSheet(1, "test").head(HeadType.class).build(); - excelWriter.write(data, writeSheet); - excelWriter.finish(); - } - - private static List getData() { - DataType vo = new DataType(); - vo.setId(738); - vo.setFirstRemark("1222"); - vo.setSecRemark("22222"); - return Collections.singletonList(vo); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/bug/HeadType.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/bug/HeadType.java deleted file mode 100644 index 7fee53f1d..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/bug/HeadType.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.bug; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -/** - */ -@Getter -@Setter -@EqualsAndHashCode -public class HeadType { - - /** - * 任务id - */ - @ExcelProperty("任务ID") - private Integer id; - - @ExcelProperty(value = "备注1") - private String firstRemark; - - @ExcelProperty(value = "备注2") - private String secRemark; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/cache/CacheTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/cache/CacheTest.java deleted file mode 100644 index 91d9e9a7a..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/cache/CacheTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.cache; - -import com.alibaba.fastjson2.JSON; -import java.io.File; -import java.util.HashMap; -import java.util.UUID; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.util.FileUtils; -import org.ehcache.Cache; -import org.ehcache.PersistentCacheManager; -import org.ehcache.config.builders.CacheConfigurationBuilder; -import org.ehcache.config.builders.CacheManagerBuilder; -import org.ehcache.config.builders.ResourcePoolsBuilder; -import org.ehcache.config.units.MemoryUnit; -import org.junit.jupiter.api.Test; - -/** - * - **/ -@Slf4j -public class CacheTest { - - @Test - public void cache() throws Exception { - - File readTempFile = FileUtils.createCacheTmpFile(); - - File cacheFile = new File(readTempFile.getPath(), UUID.randomUUID().toString()); - PersistentCacheManager persistentCacheManager = CacheManagerBuilder.newCacheManagerBuilder() - .with(CacheManagerBuilder.persistence(cacheFile)) - .withCache( - "cache", - CacheConfigurationBuilder.newCacheConfigurationBuilder( - Integer.class, - HashMap.class, - ResourcePoolsBuilder.newResourcePoolsBuilder().disk(10, MemoryUnit.GB))) - .build(true); - Cache cache = persistentCacheManager.getCache("cache", Integer.class, HashMap.class); - - HashMap map = new HashMap(); - map.put(1, "test"); - - cache.put(1, map); - log.info("dd1:{}", JSON.toJSONString(cache.get(1))); - - cache.clear(); - - log.info("dd2:{}", JSON.toJSONString(cache.get(1))); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/csv/CsvDataListener.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/csv/CsvDataListener.java deleted file mode 100644 index 86ba99c79..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/csv/CsvDataListener.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.csv; - -import com.alibaba.fastjson2.JSON; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.apache.fesod.sheet.exception.ExcelDataConvertException; - -@Slf4j -public class CsvDataListener extends AnalysisEventListener { - - @Override - public void onException(Exception exception, AnalysisContext context) { - log.error("Parsing failed, but continue parsing the next row: {}", exception.getMessage()); - if (exception instanceof ExcelDataConvertException) { - ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception; - log.error( - "Row {}, Column {} parsing exception, data is: {}", - excelDataConvertException.getRowIndex(), - excelDataConvertException.getColumnIndex(), - excelDataConvertException.getCellData()); - } - } - - @Override - public void invoke(Object data, AnalysisContext context) { - log.info("data:{}", JSON.toJSONString(data)); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) {} -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/csv/CsvReadTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/csv/CsvReadTest.java deleted file mode 100644 index 7d89df973..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/csv/CsvReadTest.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.csv; - -import com.alibaba.fastjson2.JSON; -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.csv.CSVFormat; -import org.apache.commons.csv.CSVPrinter; -import org.apache.commons.csv.CSVRecord; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.poi.poifs.filesystem.FileMagic; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -@Slf4j -public class CsvReadTest { - - @Test - public void write() throws Exception { - Appendable out = new PrintWriter( - new OutputStreamWriter(new FileOutputStream(TestFileUtil.createNewFile("csvWrite1.csv")))); - CSVPrinter printer = CSVFormat.DEFAULT.withHeader("userId", "userName").print(out); - for (int i = 0; i < 10; i++) { - printer.printRecord("userId" + i, "userName" + i); - } - printer.flush(); - printer.close(); - } - - @Test - public void read1() throws Exception { - Iterable records = CSVFormat.DEFAULT - .withNullString("") - .parse(new FileReader("src/test/resources/poi/last_row_number_xssf_date_test.csv")); - for (CSVRecord record : records) { - String lastName = record.get(0); - String firstName = record.get(1); - log.info("row:{},{}", lastName, firstName); - } - } - - @Test - public void csvWrite() throws Exception { - // 写法1 - String fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".csv"; - // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 - // 如果这里想使用03 则 传入excelType参数即可 - FastExcel.write(fileName, CsvData.class).sheet().doWrite(data()); - - // 读 - List list = FastExcel.read(fileName).sheet(0).headRowNumber(0).doReadSync(); - log.info("数据:{}", list.size()); - for (Object data : list) { - log.info("返回数据:{}", JSON.toJSONString(data)); - } - } - - @Test - public void writev2() throws Exception { - // 写法1 - String fileName = TestFileUtil.getPath() + "simpleWrite" + System.currentTimeMillis() + ".csv"; - // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 - // 如果这里想使用03 则 传入excelType参数即可 - FastExcel.write(fileName, CsvData.class).sheet().doWrite(data()); - - FastExcel.read(fileName, CsvData.class, new CsvDataListener()).sheet().doRead(); - } - - @Test - public void writeFile() throws Exception { - FileMagic fileMagic = FileMagic.valueOf(new File("src/test/resources/poi/last_row_number_xssf_date_test.csv")); - Assertions.assertEquals(FileMagic.UNKNOWN, fileMagic); - log.info("{}", fileMagic); - } - - private List data() { - List list = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - CsvData data = new CsvData(); - data.setString("字符,串" + i); - // data.setDate(new Date()); - data.setDoubleData(0.56); - data.setIgnore("忽略" + i); - list.add(data); - } - return list; - } - - @Test - public void read() { - // - // Iterable records = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(in); - // for (CSVRecord record : records) { - // String lastName = record.get("id"); - // String firstName = record.get("name"); - // System.out.println(lastName); - // System.out.println(firstName); - // } - - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/data/DataType.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/data/DataType.java deleted file mode 100644 index bf0b7401f..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/data/DataType.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.data; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -@Getter -@Setter -@EqualsAndHashCode -public class DataType { - /** - * 任务id - */ - @ExcelProperty("任务ID") - private Integer id; - - @ExcelProperty("多余字段1") - private String firstSurplus; - - @ExcelProperty("多余字段2") - private String secSurplus; - - @ExcelProperty("多余字段3") - private String thirdSurplus; - - @ExcelProperty(value = "备注1") - private String firstRemark; - - @ExcelProperty(value = "备注2") - private String secRemark; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/data/EncryptData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/data/EncryptData.java deleted file mode 100644 index 1307b9e31..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/data/EncryptData.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.data; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -/** - * - */ -@Getter -@Setter -@EqualsAndHashCode -@ToString -public class EncryptData { - @ExcelProperty("姓名") - private String name; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/data/HeadType.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/data/HeadType.java deleted file mode 100644 index 4f1d0c58e..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/data/HeadType.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.data; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -@Getter -@Setter -@EqualsAndHashCode -public class HeadType { - - /** - * 任务id - */ - @ExcelProperty("任务ID") - private Integer id; - - @ExcelProperty(value = "备注1") - private String firstRemark; - - @ExcelProperty(value = "备注2") - private String secRemark; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/data/SimpleData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/data/SimpleData.java deleted file mode 100644 index 4d00117f3..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/data/SimpleData.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.data; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -/** - * mock data format for simple read/write - *

- * Use ExcelProperty {@link ExcelProperty} to mark headers - *

- * - * - */ -@Getter -@Setter -@EqualsAndHashCode -public class SimpleData { - @ExcelProperty("姓名") - private String name; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/dataformat/DataFormatData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/dataformat/DataFormatData.java deleted file mode 100644 index 28dc326f3..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/dataformat/DataFormatData.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.dataformat; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.metadata.data.ReadCellData; - -/** - **/ -@Getter -@Setter -@EqualsAndHashCode -public class DataFormatData { - private ReadCellData date; - private ReadCellData num; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/dataformat/DataFormatTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/dataformat/DataFormatTest.java deleted file mode 100644 index 6eb8d6f3a..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/dataformat/DataFormatTest.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.dataformat; - -import com.alibaba.fastjson2.JSON; -import java.io.File; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.regex.Pattern; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.metadata.data.FormulaData; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * 格式测试 - * - * - **/ -@Slf4j -public class DataFormatTest { - - @Test - public void test() throws Exception { - - File file = TestFileUtil.readFile("dataformat" + File.separator + "dataformat.xlsx"); - - List list = FastExcel.read(file, DataFormatData.class, null) - .sheet() - .headRowNumber(1) - .doReadSync(); - log.info("数据:{}", list.size()); - for (DataFormatData data : list) { - org.apache.fesod.sheet.metadata.data.DataFormatData dataFormat = - data.getDate().getDataFormatData(); - - FormulaData dataFormatString = data.getDate().getFormulaData(); - - if (dataFormat == null || dataFormatString == null) { - - } else { - log.info( - "格式化:{};{}:{}", - dataFormat.getIndex(), - dataFormatString.getFormulaValue(), - DateUtil.isADateFormat(dataFormat.getIndex(), dataFormatString.getFormulaValue())); - } - - log.info("返回数据:{}", JSON.toJSONString(data)); - } - } - - @Test - public void testxls() throws Exception { - File file = TestFileUtil.readFile("dataformat" + File.separator + "dataformat.xls"); - - List list = FastExcel.read(file, DataFormatData.class, null) - .sheet() - .headRowNumber(1) - .doReadSync(); - log.info("数据:{}", list.size()); - for (DataFormatData data : list) { - org.apache.fesod.sheet.metadata.data.DataFormatData dataFormat = - data.getDate().getDataFormatData(); - - FormulaData dataFormatString = data.getDate().getFormulaData(); - - if (dataFormat == null || dataFormatString == null) { - - } else { - log.info( - "格式化:{};{}:{}", - dataFormat.getIndex(), - dataFormatString.getFormulaValue(), - DateUtil.isADateFormat(dataFormat.getIndex(), dataFormatString.getFormulaValue())); - } - - log.info("返回数据:{}", JSON.toJSONString(data)); - } - } - - @Test - public void test3() throws IOException { - - File file = TestFileUtil.readFile("dataformat" + File.separator + "dataformat.xlsx"); - XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file.getAbsoluteFile().getAbsolutePath()); - Sheet xssfSheet = xssfWorkbook.getSheetAt(0); - Cell cell = xssfSheet.getRow(0).getCell(0); - DataFormatter d = new DataFormatter(); - System.out.println(d.formatCellValue(cell)); - } - - @Test - public void test31() throws IOException { - System.out.println(DateUtil.isADateFormat(181, "[DBNum1][$-404]m\"\u6708\"d\"\u65e5\";@")); - } - - @Test - public void test43() throws IOException { - SimpleDateFormat s = new SimpleDateFormat("yyyy'年'm'月'd'日' h'点'mm'哈哈哈m'"); - System.out.println(s.format(new Date())); - } - - @Test - public void test463() throws IOException { - SimpleDateFormat s = new SimpleDateFormat("[$-804]yyyy年m月"); - System.out.println(s.format(new Date())); - } - - @Test - public void test1() throws Exception { - System.out.println(DateUtil.isADateFormat(181, "yyyy\"年啊\"m\"月\"d\"日\"\\ h")); - System.out.println(DateUtil.isADateFormat(180, "yyyy\"年\"m\"月\"d\"日\"\\ h\"点\"")); - } - - @Test - public void test2() throws Exception { - List list1 = new ArrayList(3000); - long start = System.currentTimeMillis(); - for (int i = 0; i < 10000; i++) { - list1.clear(); - } - System.out.println("end:" + (System.currentTimeMillis() - start)); - start = System.currentTimeMillis(); - for (int i = 0; i < 10000; i++) { - list1 = new ArrayList(3000); - } - System.out.println("end:" + (System.currentTimeMillis() - start)); - } - - @Test - public void tests() throws IOException, InvalidFormatException { - SimpleDateFormat s1 = new SimpleDateFormat("yyyy\"5E74\"m\"6708\"d\"65E5\""); - System.out.println(s1.format(new Date())); - s1 = new SimpleDateFormat("yyyy年m月d日"); - System.out.println(s1.format(new Date())); - } - - @Test - public void tests3() throws IOException, InvalidFormatException { - SimpleDateFormat s1 = new SimpleDateFormat("ah\"时\"mm\"分\""); - System.out.println(s1.format(new Date())); - } - - private static final Pattern date_ptrn6 = Pattern.compile("^.*(年|月|日|时|分|秒)+.*$"); - - @Test - public void tests34() throws IOException, InvalidFormatException { - System.out.println(date_ptrn6.matcher("2017但是").matches()); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/fill/FillData2.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/fill/FillData2.java deleted file mode 100644 index 82dd08bb7..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/fill/FillData2.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.fill; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; - -/** - * - */ -@Getter -@Setter -@EqualsAndHashCode -public class FillData2 { - private String test; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/fill/FillTempTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/fill/FillTempTest.java deleted file mode 100644 index 5921272a1..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/fill/FillTempTest.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.fill; - -import java.io.File; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.fesod.sheet.ExcelWriter; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.demo.fill.FillData; -import org.apache.fesod.sheet.enums.WriteDirectionEnum; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.metadata.WriteSheet; -import org.apache.fesod.sheet.write.metadata.fill.FillConfig; -import org.apache.fesod.sheet.write.metadata.fill.FillWrapper; -import org.junit.jupiter.api.Test; - -/** - * Example of filling data into Excel templates. - */ -public class FillTempTest { - /** - * Simplest example of filling data. - */ - @Test - public void simpleFill() { - // Template note: Use {} to represent variables. If the template contains "{", "}" as special characters, use - // "\{", "\}" instead. - String templateFileName = "src/test/resources/fill/simple.xlsx"; - - // Option 1: Fill using an object - String fileName = TestFileUtil.getPath() + "simpleFill" + System.currentTimeMillis() + ".xlsx"; - // This will fill the first sheet, and the file stream will be closed automatically. - FillData fillData = new FillData(); - fillData.setName("Zhang San"); - fillData.setNumber(5.2); - FastExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(fillData); - - /* - // Option 2: Fill using a Map - fileName = TestFileUtil.getPath() + "simpleFill" + System.currentTimeMillis() + ".xlsx"; - // This will fill the first sheet, and the file stream will be closed automatically. - Map map = new HashMap(); - map.put("name", "Zhang San"); - map.put("number", 5.2); - FastExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(map); - */ - } - - /** - * Example of filling a list of data. - */ - @Test - public void listFill() { - // Template note: Use {} to represent variables. If the template contains "{", "}" as special characters, use - // "\{", "\}" instead. - // When filling a list, note that {.} in the template indicates a list. - String templateFileName = - TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "list.xlsx"; - - // Option 1: Load all data into memory at once and fill - String fileName = TestFileUtil.getPath() + "listFill" + System.currentTimeMillis() + ".xlsx"; - // This will fill the first sheet, and the file stream will be closed automatically. - FastExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(data()); - - // Option 2: Fill in multiple passes using file caching (saves memory) - fileName = TestFileUtil.getPath() + "listFill" + System.currentTimeMillis() + ".xlsx"; - ExcelWriter excelWriter = - FastExcel.write(fileName).withTemplate(templateFileName).build(); - WriteSheet writeSheet = FastExcel.writerSheet().build(); - excelWriter.fill(data(), writeSheet); - excelWriter.fill(data(), writeSheet); - // Do not forget to close the stream - excelWriter.finish(); - } - - /** - * Example of complex data filling. - */ - @Test - public void complexFill() { - // Template note: Use {} to represent variables. If the template contains "{", "}" as special characters, use - // "\{", "\}" instead. - // {} represents a regular variable, {.} represents a list variable. - String templateFileName = - TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "complex.xlsx"; - - String fileName = TestFileUtil.getPath() + "complexFill" + System.currentTimeMillis() + ".xlsx"; - ExcelWriter excelWriter = - FastExcel.write(fileName).withTemplate(templateFileName).build(); - WriteSheet writeSheet = FastExcel.writerSheet().build(); - // Note: The `forceNewRow` parameter ensures that a new row is created when writing a list, even if there are no - // empty rows below it. - // By default, it is false, meaning it will use the next row if available, or create one if not. - // Setting `forceNewRow=true` has the drawback of loading all data into memory, so use it cautiously. - // If your template has a list and data below it, you must set `forceNewRow=true`, but this will consume more - // memory. - // For large datasets where the list is not the last row, refer to the next example. - FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build(); - excelWriter.fill(data(), fillConfig, writeSheet); - excelWriter.fill(data(), fillConfig, writeSheet); - Map map = new HashMap(); - map.put("date", "2019-10-09 13:28:28"); - map.put("total", 1000); - excelWriter.fill(map, writeSheet); - excelWriter.finish(); - } - - /** - * Example of complex data filling with large datasets. - *

- * The solution here is to ensure the list in the template is the last row, then append a table. - * Note: Excel 2003 format is not supported and requires more memory. - */ - @Test - public void complexFillWithTable() { - // Template note: Use {} to represent variables. If the template contains "{", "}" as special characters, use - // "\{", "\}" instead. - // {} represents a regular variable, {.} represents a list variable. - // Here, the template removes data after the list, such as summary rows. - String templateFileName = TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator - + "complexFillWithTable.xlsx"; - - String fileName = TestFileUtil.getPath() + "complexFillWithTable" + System.currentTimeMillis() + ".xlsx"; - ExcelWriter excelWriter = - FastExcel.write(fileName).withTemplate(templateFileName).build(); - WriteSheet writeSheet = FastExcel.writerSheet().build(); - // Directly write data - excelWriter.fill(data(), writeSheet); - excelWriter.fill(data(), writeSheet); - - // Write data before the list - Map map = new HashMap(); - map.put("date", "2019-10-09 13:28:28"); - excelWriter.fill(map, writeSheet); - - // Manually write summary data after the list - // Here, we use a list for simplicity, but an object could also be used. - List> totalListList = new ArrayList>(); - List totalList = new ArrayList(); - totalListList.add(totalList); - totalList.add(null); - totalList.add(null); - totalList.add(null); - // Fourth column - totalList.add("Total: 1000"); - // Use `write` instead of `fill` here - excelWriter.write(totalListList, writeSheet); - excelWriter.finish(); - // Overall, this approach is complex, but no better solution is available. - // Asynchronous writing to Excel does not support row deletion or movement, nor does it support comments. - // Therefore, this workaround is necessary. - } - - /** - * Example of horizontal data filling. - */ - @Test - public void horizontalFill() { - // Template note: Use {} to represent variables. If the template contains "{", "}" as special characters, use - // "\{", "\}" instead. - // {} represents a regular variable, {.} represents a list variable. - String templateFileName = - TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "horizontal.xlsx"; - - String fileName = TestFileUtil.getPath() + "horizontalFill" + System.currentTimeMillis() + ".xlsx"; - ExcelWriter excelWriter = - FastExcel.write(fileName).withTemplate(templateFileName).build(); - WriteSheet writeSheet = FastExcel.writerSheet().build(); - FillConfig fillConfig = - FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build(); - excelWriter.fill(data(), fillConfig, writeSheet); - excelWriter.fill(data(), fillConfig, writeSheet); - - Map map = new HashMap(); - map.put("date", "2019-10-09 13:28:28"); - excelWriter.fill(map, writeSheet); - - // Do not forget to close the stream - excelWriter.finish(); - } - - /** - * Example of composite data filling with multiple lists. - */ - @Test - public void compositeFill() { - // Template note: Use {} to represent variables. If the template contains "{", "}" as special characters, use - // "\{", "\}" instead. - // {} represents a regular variable, {.} represents a list variable, and {prefix.} distinguishes different - // lists. - String templateFileName = - TestFileUtil.getPath() + "demo" + File.separator + "fill" + File.separator + "composite.xlsx"; - - String fileName = TestFileUtil.getPath() + "compositeFill" + System.currentTimeMillis() + ".xlsx"; - ExcelWriter excelWriter = - FastExcel.write(fileName).withTemplate(templateFileName).build(); - WriteSheet writeSheet = FastExcel.writerSheet().build(); - FillConfig fillConfig = - FillConfig.builder().direction(WriteDirectionEnum.HORIZONTAL).build(); - // If there are multiple lists, the template must use {prefix.}, where "data1" is the prefix. - // Multiple lists must be wrapped in FillWrapper. - excelWriter.fill(new FillWrapper("data1", data()), fillConfig, writeSheet); - excelWriter.fill(new FillWrapper("data1", data()), fillConfig, writeSheet); - excelWriter.fill(new FillWrapper("data2", data()), writeSheet); - excelWriter.fill(new FillWrapper("data2", data()), writeSheet); - excelWriter.fill(new FillWrapper("data3", data()), writeSheet); - excelWriter.fill(new FillWrapper("data3", data()), writeSheet); - - Map map = new HashMap(); - // map.put("date", "2019-10-09 13:28:28"); - map.put("date", new Date()); - - excelWriter.fill(map, writeSheet); - - // Do not forget to close the stream - excelWriter.finish(); - } - - /** - * Generates sample data for filling. - * - * @return A list of FillData objects. - */ - private List data() { - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - FillData fillData = new FillData(); - list.add(fillData); - fillData.setName("Zhang San"); - fillData.setNumber(5.2); - } - return list; - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue1662/Data1662.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue1662/Data1662.java deleted file mode 100644 index 832c33513..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue1662/Data1662.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.issue1662; - -import java.util.Date; -import lombok.AllArgsConstructor; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -@Getter -@Setter -@EqualsAndHashCode -@AllArgsConstructor -@NoArgsConstructor -public class Data1662 { - @ExcelProperty(index = 0) - private String str; - - @ExcelProperty(index = 1) - private Date date; - - @ExcelProperty(index = 2) - private double r; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue1662/Issue1662Test.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue1662/Issue1662Test.java deleted file mode 100644 index 1aadd5d49..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue1662/Issue1662Test.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.issue1662; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.Test; - -public class Issue1662Test { - @Test - public void test1662() { - String fileName = TestFileUtil.getPath() + "Test1939" + ".xlsx"; - System.out.println(fileName); - FastExcel.write(fileName).head(head()).sheet("模板").doWrite(dataList()); - } - - private List> head() { - List> list = new ArrayList>(); - List head0 = new ArrayList(); - List head1 = new ArrayList(); - head0.add("xx"); - head0.add("日期"); - list.add(head0); - head1.add("日期"); - list.add(head1); - return list; - } - - private List> dataList() { - List> list = new ArrayList>(); - List data = new ArrayList(); - data.add("字符串"); - data.add(new Date()); - data.add(0.56); - list.add(data); - return list; - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue1663/FillTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue1663/FillTest.java deleted file mode 100644 index 15ffe68bd..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue1663/FillTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.issue1663; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.apache.fesod.sheet.ExcelWriter; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.enums.WriteDirectionEnum; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.metadata.WriteSheet; -import org.apache.fesod.sheet.write.metadata.fill.FillConfig; -import org.apache.fesod.sheet.write.metadata.fill.FillWrapper; -import org.junit.jupiter.api.Test; - -public class FillTest { - @Test - public void TestFillNullPoint() { - String templateFileName = TestFileUtil.getPath() + "temp/issue1663" + File.separator + "template.xlsx"; - - String fileName = TestFileUtil.getPath() + "temp/issue1663" + File.separator + "issue1663.xlsx"; - ExcelWriter excelWriter = - FastExcel.write(fileName).withTemplate(templateFileName).build(); - WriteSheet writeSheet = FastExcel.writerSheet().build(); - FillConfig fillConfig = - FillConfig.builder().direction(WriteDirectionEnum.VERTICAL).build(); - excelWriter.fill(new FillWrapper("data1", data()), fillConfig, writeSheet); - - Map map = new HashMap(); - // Variable {date} does not exist in the template.xlsx, which should be ignored instead of reporting an error. - map.put("date", "2019年10月9日13:28:28"); - excelWriter.fill(map, writeSheet); - excelWriter.finish(); - } - - private List data() { - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - FillData fillData = new FillData(); - list.add(fillData); - fillData.setName("张三"); - fillData.setNumber(5.2); - } - return list; - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue2319/Issue2319.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue2319/Issue2319.java deleted file mode 100644 index a54fc1d87..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue2319/Issue2319.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.issue2319; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; - -@Getter -@Setter -@EqualsAndHashCode -public class Issue2319 { - private String num1; - private String num2; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue2319/Issue2319Test.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue2319/Issue2319Test.java deleted file mode 100644 index 1298d5c64..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue2319/Issue2319Test.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.issue2319; - -import com.alibaba.fastjson2.JSON; -import java.io.File; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.read.listener.PageReadListener; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.Test; - -@Slf4j -public class Issue2319Test { - @Test - public void IssueTest1() { - String fileName = TestFileUtil.getPath() + "temp/issue2319" + File.separator + "test1.xlsx"; - FastExcel.read(fileName, Issue2319.class, new PageReadListener(dataList -> { - for (Issue2319 issueData : dataList) { - System.out.println(("读取到一条数据{}" + JSON.toJSONString(issueData))); - } - })) - .sheet() - .doRead(); - } - - @Test - public void IssueTest2() { - String fileName = TestFileUtil.getPath() + "temp/issue2319" + File.separator + "test2.xlsx"; - FastExcel.read(fileName, Issue2319.class, new PageReadListener(dataList -> { - for (Issue2319 issueData : dataList) { - System.out.println(("读取到一条数据{}" + JSON.toJSONString(issueData))); - } - })) - .sheet() - .doRead(); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue2443/Issue2443.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue2443/Issue2443.java deleted file mode 100644 index 5e30e174b..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue2443/Issue2443.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.issue2443; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; - -@Getter -@Setter -@EqualsAndHashCode -public class Issue2443 { - private int a; - private int b; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue2443/Issue2443Test.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue2443/Issue2443Test.java deleted file mode 100644 index 9acf373a7..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue2443/Issue2443Test.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.issue2443; - -import com.alibaba.fastjson2.JSON; -import java.io.File; -import java.text.ParseException; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.metadata.property.ExcelContentProperty; -import org.apache.fesod.sheet.read.listener.PageReadListener; -import org.apache.fesod.sheet.util.NumberUtils; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -@Slf4j -public class Issue2443Test { - @Test - public void IssueTest1() { - String fileName = TestFileUtil.getPath() + "temp/issue2443" + File.separator + "date1.xlsx"; - FastExcel.read(fileName, Issue2443.class, new PageReadListener(dataList -> { - for (Issue2443 issueData : dataList) { - log.info("读取到一条数据{}", JSON.toJSONString(issueData)); - } - })) - .sheet() - .doRead(); - } - - @Test - public void IssueTest2() { - String fileName = TestFileUtil.getPath() + "temp/issue2443" + File.separator + "date2.xlsx"; - FastExcel.read(fileName, Issue2443.class, new PageReadListener(dataList -> { - for (Issue2443 issueData : dataList) { - log.info("读取到一条数据{}", JSON.toJSONString(issueData)); - } - })) - .sheet() - .doRead(); - } - - @Test - public void parseIntegerTest1() throws ParseException { - String string = "1.00"; - ExcelContentProperty contentProperty = null; - int Int = NumberUtils.parseInteger(string, contentProperty); - Assertions.assertEquals(1, Int); - } - - @Test - public void parseIntegerTest2() throws ParseException { - String string = "2.00"; - ExcelContentProperty contentProperty = null; - int Int = NumberUtils.parseInteger(string, contentProperty); - Assertions.assertEquals(2, Int); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue406/ReadSheetTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue406/ReadSheetTest.java deleted file mode 100644 index a3d59264b..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/issue406/ReadSheetTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.issue406; - -import org.apache.fesod.sheet.read.metadata.ReadSheet; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -class ReadSheetTest { - - @Test - void testAll() { - testEquals_SameInstance(); - testEquals_Null(); - testEquals_DifferentClass(); - testEquals_EqualObjects(); - - testHashCode_Consistency(); - testHashCode_EqualityForEqualObjects(); - - // If @EqualsAndHashCode is not implemented, the following error will occur - testEquals_DifferentSheetNo(); - testEquals_DifferentSheetName(); - testEquals_DifferentNumRows(); - testEquals_DifferentHiddenState(); - testEquals_DifferentVeryHiddenState(); - } - - @Test - void testEquals_SameInstance() { - ReadSheet sheet = new ReadSheet(1, "Sheet1"); - Assertions.assertEquals(sheet, sheet); - } - - @Test - void testEquals_Null() { - ReadSheet sheet = new ReadSheet(1, "Sheet1"); - Assertions.assertNotEquals(null, sheet); - } - - @Test - void testEquals_DifferentClass() { - ReadSheet sheet = new ReadSheet(1, "Sheet1"); - Assertions.assertNotEquals("Not a ReadSheet object", sheet); - } - - @Test - void testEquals_EqualObjects() { - ReadSheet sheet1 = new ReadSheet(1, "Sheet1"); - sheet1.setNumRows(100); - sheet1.setHidden(false); - sheet1.setVeryHidden(true); - - ReadSheet sheet2 = new ReadSheet(1, "Sheet1"); - sheet2.setNumRows(100); - sheet2.setHidden(false); - sheet2.setVeryHidden(true); - - Assertions.assertEquals(sheet1, sheet2); - } - - @Test - void testEquals_DifferentSheetNo() { - ReadSheet sheet1 = new ReadSheet(1, "Sheet1"); - ReadSheet sheet2 = new ReadSheet(2, "Sheet1"); - Assertions.assertNotEquals(sheet1, sheet2); - } - - @Test - void testEquals_DifferentSheetName() { - ReadSheet sheet1 = new ReadSheet(1, "Sheet1"); - ReadSheet sheet2 = new ReadSheet(1, "Sheet2"); - Assertions.assertNotEquals(sheet1, sheet2); - } - - @Test - void testEquals_DifferentNumRows() { - ReadSheet sheet1 = new ReadSheet(1, "Sheet1"); - sheet1.setNumRows(100); - ReadSheet sheet2 = new ReadSheet(1, "Sheet1"); - sheet2.setNumRows(200); - Assertions.assertNotEquals(sheet1, sheet2); - } - - @Test - void testEquals_DifferentHiddenState() { - ReadSheet sheet1 = new ReadSheet(1, "Sheet1"); - sheet1.setHidden(true); - ReadSheet sheet2 = new ReadSheet(1, "Sheet1"); - sheet2.setHidden(false); - Assertions.assertNotEquals(sheet1, sheet2); - } - - @Test - void testEquals_DifferentVeryHiddenState() { - ReadSheet sheet1 = new ReadSheet(1, "Sheet1"); - sheet1.setVeryHidden(true); - ReadSheet sheet2 = new ReadSheet(1, "Sheet1"); - sheet2.setVeryHidden(false); - Assertions.assertNotEquals(sheet1, sheet2); - } - - @Test - void testHashCode_Consistency() { - ReadSheet sheet = new ReadSheet(1, "Sheet1"); - int initialHashCode = sheet.hashCode(); - Assertions.assertEquals(initialHashCode, sheet.hashCode()); - } - - @Test - void testHashCode_EqualityForEqualObjects() { - ReadSheet sheet1 = new ReadSheet(1, "Sheet1"); - sheet1.setNumRows(100); - sheet1.setHidden(false); - sheet1.setVeryHidden(true); - - ReadSheet sheet2 = new ReadSheet(1, "Sheet1"); - sheet2.setNumRows(100); - sheet2.setHidden(false); - sheet2.setVeryHidden(true); - - Assertions.assertEquals(sheet1.hashCode(), sheet2.hashCode()); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/large/LargeData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/large/LargeData.java deleted file mode 100644 index d73546692..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/large/LargeData.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.large; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -/** - * - */ -@Getter -@Setter -@EqualsAndHashCode -@NoArgsConstructor -public class LargeData { - - private String str1; - - private String str2; - - private String str3; - - private String str4; - - private String str5; - - private String str6; - - private String str7; - - private String str8; - - private String str9; - - private String str10; - - private String str11; - - private String str12; - - private String str13; - - private String str14; - - private String str15; - - private String str16; - - private String str17; - - private String str18; - - private String str19; - - private String str20; - - private String str21; - - private String str22; - - private String str23; - - private String str24; - - private String str25; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/large/LargeDataListener.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/large/LargeDataListener.java deleted file mode 100644 index 85348b090..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/large/LargeDataListener.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.large; - -import com.alibaba.fastjson2.JSON; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; - -/** - * - */ -@Slf4j -public class LargeDataListener extends AnalysisEventListener { - - private int count = 0; - - @Override - public void invoke(LargeData data, AnalysisContext context) { - if (count == 0) { - log.info("First row:{}", JSON.toJSONString(data)); - } - count++; - if (count % 100000 == 0) { - log.info("Already read:{}", count); - } - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - log.info("Large row count:{}", count); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/large/NoModelLargeDataListener.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/large/NoModelLargeDataListener.java deleted file mode 100644 index 436d56272..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/large/NoModelLargeDataListener.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.large; - -import com.alibaba.fastjson2.JSON; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; - -/** - * - */ -@Slf4j -public class NoModelLargeDataListener extends AnalysisEventListener> { - - private int count = 0; - - @Override - public void invoke(Map data, AnalysisContext context) { - if (count == 0) { - log.info("First row:{}", JSON.toJSONString(data)); - } - count++; - if (count % 100000 == 0) { - log.info("Already read:{}", count); - } - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - log.info("Large row count:{}", count); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/large/TempLargeDataTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/large/TempLargeDataTest.java deleted file mode 100644 index ce7563f19..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/large/TempLargeDataTest.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.large; - -import java.io.File; -import java.io.FileOutputStream; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.IntStream; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.ExcelWriter; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.metadata.WriteSheet; -import org.apache.poi.openxml4j.util.ZipSecureFile; -import org.apache.poi.xssf.streaming.SXSSFCell; -import org.apache.poi.xssf.streaming.SXSSFRow; -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.junit.jupiter.api.*; - -/** - * - */ -@Slf4j -public class TempLargeDataTest { - - private int i = 0; - - private static File fileFill07; - - private static File template07; - - private static File fileCsv; - - private static File fileWrite07; - - private static File fileWriteTemp07; - - private static File fileWritePoi07; - - @BeforeAll - public static void init() { - fileFill07 = TestFileUtil.createNewFile("largefill07.xlsx"); - fileWrite07 = TestFileUtil.createNewFile("large" + File.separator + "fileWrite07.xlsx"); - fileWriteTemp07 = TestFileUtil.createNewFile("large" + File.separator + "fileWriteTemp07.xlsx"); - fileWritePoi07 = TestFileUtil.createNewFile("large" + File.separator + "fileWritePoi07.xlsx"); - template07 = TestFileUtil.readFile("large" + File.separator + "fill.xlsx"); - fileCsv = TestFileUtil.createNewFile("largefileCsv.csv"); - } - - @Test - public void read() throws Exception { - long start = System.currentTimeMillis(); - FastExcel.read( - Files.newInputStream(Paths.get("src/test/resources/simple/LargeData.xlsx")), - LargeData.class, - new LargeDataListener()) - .headRowNumber(2) - .sheet() - .doRead(); - log.info("Large data total time spent:{}", System.currentTimeMillis() - start); - } - - @Test - public void noModelRead() throws Exception { - ZipSecureFile.setMaxEntrySize(Long.MAX_VALUE); - long start = System.currentTimeMillis(); - FastExcel.read("src/test/resources/simple/no_model_10000_rows.xlsx", new NoModelLargeDataListener()) - .sheet() - .doRead(); - log.info("Large data total time spent:{}", System.currentTimeMillis() - start); - } - - @Test - public void t04Write() throws Exception { - ExcelWriter excelWriter = - FastExcel.write(fileWriteTemp07, LargeData.class).build(); - WriteSheet writeSheet = FastExcel.writerSheet().build(); - for (int j = 0; j < 2; j++) { - excelWriter.write(data(), writeSheet); - } - excelWriter.finish(); - - long start = System.currentTimeMillis(); - excelWriter = FastExcel.write(fileWrite07, LargeData.class).build(); - writeSheet = FastExcel.writerSheet().build(); - for (int j = 0; j < 5000; j++) { - excelWriter.write(data(), writeSheet); - log.info("{} write success.", j); - } - excelWriter.finish(); - long cost = System.currentTimeMillis() - start; - log.info("write cost:{}", cost); - start = System.currentTimeMillis(); - try (FileOutputStream fileOutputStream = new FileOutputStream(fileWritePoi07)) { - SXSSFWorkbook workbook = new SXSSFWorkbook(); - SXSSFSheet sheet = workbook.createSheet("sheet1"); - for (int i = 0; i < 100 * 5000; i++) { - SXSSFRow row = sheet.createRow(i); - for (int j = 0; j < 25; j++) { - SXSSFCell cell = row.createCell(j); - cell.setCellValue("str-" + j + "-" + i); - } - if (i % 5000 == 0) { - log.info("{} write success.", i); - } - } - workbook.write(fileOutputStream); - workbook.close(); - } - long costPoi = System.currentTimeMillis() - start; - log.info("poi write cost:{}", System.currentTimeMillis() - start); - log.info("{} vs {}", cost, costPoi); - Assertions.assertTrue(costPoi * 2 > cost); - } - - @Test - public void t04WriteExcel() { - IntStream.rangeClosed(0, 100).forEach(index -> { - try (ExcelWriter excelWriter = - FastExcel.write(fileWriteTemp07, LargeData.class).build()) { - WriteSheet writeSheet = FastExcel.writerSheet().build(); - for (int j = 0; j < 5000; j++) { - excelWriter.write(data(), writeSheet); - } - excelWriter.finish(); - } - log.info("{} 完成", index); - }); - } - - @Test - public void t04WriteExcelNo() throws Exception { - IntStream.rangeClosed(0, 10000).forEach(index -> { - try (ExcelWriter excelWriter = - FastExcel.write(fileWriteTemp07, LargeData.class).build()) { - WriteSheet writeSheet = FastExcel.writerSheet().build(); - for (int j = 0; j < 50; j++) { - excelWriter.write(data(), writeSheet); - } - excelWriter.finish(); - } - log.info("{} 完成", index); - }); - } - - @Test - public void t04WriteExcelPoi() throws Exception { - IntStream.rangeClosed(0, 10000).forEach(index -> { - try (FileOutputStream fileOutputStream = new FileOutputStream(fileWritePoi07)) { - SXSSFWorkbook workbook = new SXSSFWorkbook(500); - // workbook.setCompressTempFiles(true); - SXSSFSheet sheet = workbook.createSheet("sheet1"); - for (int i = 0; i < 100 * 50; i++) { - SXSSFRow row = sheet.createRow(i); - for (int j = 0; j < 25; j++) { - String str = "str-" + j + "-" + i; - // if (i + 10000 == j) { - SXSSFCell cell = row.createCell(j); - cell.setCellValue(str); - // System.out.println(str); - // } - } - if (i % 5000 == 0) { - log.info("{} write success.", i); - } - } - workbook.write(fileOutputStream); - workbook.close(); - } catch (Exception e) { - log.error(e.getMessage(), e); - } - log.info("{} 完成", index); - }); - } - - private List data() { - List list = new ArrayList<>(); - - int size = i + 100; - for (; i < size; i++) { - LargeData largeData = new LargeData(); - list.add(largeData); - largeData.setStr1("str1-" + i); - largeData.setStr2("str2-" + i); - largeData.setStr3("str3-" + i); - largeData.setStr4("str4-" + i); - largeData.setStr5("str5-" + i); - largeData.setStr6("str6-" + i); - largeData.setStr7("str7-" + i); - largeData.setStr8("str8-" + i); - largeData.setStr9("str9-" + i); - largeData.setStr10("str10-" + i); - largeData.setStr11("str11-" + i); - largeData.setStr12("str12-" + i); - largeData.setStr13("str13-" + i); - largeData.setStr14("str14-" + i); - largeData.setStr15("str15-" + i); - largeData.setStr16("str16-" + i); - largeData.setStr17("str17-" + i); - largeData.setStr18("str18-" + i); - largeData.setStr19("str19-" + i); - largeData.setStr20("str20-" + i); - largeData.setStr21("str21-" + i); - largeData.setStr22("str22-" + i); - largeData.setStr23("str23-" + i); - largeData.setStr24("str24-" + i); - largeData.setStr25("str25-" + i); - } - return list; - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/Poi2Test.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/Poi2Test.java deleted file mode 100644 index 81817b9b4..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/Poi2Test.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.poi; - -import java.io.IOException; -import lombok.extern.slf4j.Slf4j; -import org.apache.poi.xssf.streaming.SXSSFRow; -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * 测试poi - * - * - **/ -@Slf4j -public class Poi2Test { - - @Test - public void test() throws IOException { - String file = "src/test/resources/poi/last_row_number_test.xlsx"; - SXSSFWorkbook xssfWorkbook = new SXSSFWorkbook(new XSSFWorkbook(file)); - SXSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0); - log.info("一共行数:{}", xssfSheet.getLastRowNum()); - SXSSFRow row = xssfSheet.getRow(0); - log.info("第一行数据:{}", row); - } - - @Test - public void lastRowNumXSSF() throws IOException { - String file = "src/test/resources/poi/last_row_number_xssf_test.xlsx"; - XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file); - log.info("一共:{}个sheet", xssfWorkbook.getNumberOfSheets()); - XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0); - log.info("一共行数:{}", xssfSheet.getLastRowNum()); - XSSFRow row = xssfSheet.getRow(0); - log.info("第一行数据:{}", row); - xssfSheet.createRow(20); - log.info("一共行数:{}", xssfSheet.getLastRowNum()); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/Poi3Test.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/Poi3Test.java deleted file mode 100644 index a1bf5411c..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/Poi3Test.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.poi; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.nio.file.Path; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.poi.EncryptedDocumentException; -import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.openxml4j.opc.OPCPackage; -import org.apache.poi.openxml4j.opc.PackageAccess; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.EncryptionMode; -import org.apache.poi.poifs.crypt.Encryptor; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -/** - * 测试poi - * - * - **/ -@Slf4j -public class Poi3Test { - - @Test - public void Encryption(@TempDir Path tempDir) throws Exception { - // Write out the encrypted version - try (POIFSFileSystem fs = new POIFSFileSystem(); - FileOutputStream fos = new FileOutputStream( - tempDir.resolve(System.currentTimeMillis() + ".xlsx").toFile()); ) { - String file = TestFileUtil.getPath() + "large" + File.separator + "large07.xlsx"; - EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile); - Encryptor enc = info.getEncryptor(); - enc.confirmPassword("foobaa"); - OPCPackage opc = OPCPackage.open(new File(file), PackageAccess.READ_WRITE); - OutputStream os = enc.getDataStream(fs); - opc.save(os); - opc.close(); - fs.writeFilesystem(fos); - } - } - - @Test - public void Encryption2() throws Exception { - Biff8EncryptionKey.setCurrentUserPassword("incorrect pwd"); - POIFSFileSystem fs = new POIFSFileSystem(new File("src/test/resources/demo/pwd_123.xls"), true); - Assertions.assertThrows(EncryptedDocumentException.class, () -> new HSSFWorkbook(fs.getRoot(), true)); - Biff8EncryptionKey.setCurrentUserPassword("123"); - HSSFWorkbook hwb = new HSSFWorkbook( - new POIFSFileSystem(new File("src/test/resources/demo/pwd_123.xls"), true).getRoot(), true); - Assertions.assertEquals("Sheet1", hwb.getSheetAt(0).getSheetName()); - Biff8EncryptionKey.setCurrentUserPassword(null); - System.out.println(hwb.getSheetAt(0).getSheetName()); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/PoiDateFormatTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/PoiDateFormatTest.java deleted file mode 100644 index 9f0874cca..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/PoiDateFormatTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.poi; - -import java.io.IOException; -import lombok.extern.slf4j.Slf4j; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * 测试poi - * - * - **/ -@Slf4j -public class PoiDateFormatTest { - - @Test - public void read() throws IOException { - String file = "src/test/resources/dataformat/dataformat.xlsx"; - XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file); - XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0); - log.info("一共行数:{}", xssfSheet.getLastRowNum()); - XSSFRow row = xssfSheet.getRow(7); - XSSFCell cell = row.getCell(0); - log.info("dd{}", cell.getDateCellValue()); - log.info("dd{}", cell.getNumericCellValue()); - - log.info("dd{}", DateUtil.isCellDateFormatted(cell)); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/PoiEncryptTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/PoiEncryptTest.java deleted file mode 100644 index 9da348006..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/PoiEncryptTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.poi; - -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.temp.data.EncryptData; -import org.apache.fesod.sheet.temp.data.SimpleData; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.poi.poifs.crypt.EncryptionInfo; -import org.apache.poi.poifs.crypt.EncryptionMode; -import org.apache.poi.poifs.crypt.Encryptor; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * TODO - * - * - */ -public class PoiEncryptTest { - @Test - public void encrypt() throws Exception { - - XSSFWorkbook workbook = new XSSFWorkbook(); - SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(workbook); - - Sheet sheet = sxssfWorkbook.createSheet("sheet1"); - sheet.createRow(0).createCell(0).setCellValue("T2"); - - POIFSFileSystem fs = new POIFSFileSystem(); - EncryptionInfo info = new EncryptionInfo(EncryptionMode.agile); - - Encryptor enc = info.getEncryptor(); - enc.confirmPassword("123456"); - - // write the workbook into the encrypted OutputStream - OutputStream encos = enc.getDataStream(fs); - sxssfWorkbook.write(encos); - sxssfWorkbook.dispose(); - sxssfWorkbook.close(); - encos.close(); // this is necessary before writing out the FileSystem - - OutputStream os = - new FileOutputStream(TestFileUtil.createNewFile("encrypt" + System.currentTimeMillis() + ".xlsx")); - fs.writeFilesystem(os); - os.close(); - fs.close(); - } - - @Test - public void encryptExcel() throws Exception { - FastExcel.write( - TestFileUtil.createNewFile("encryptv2" + System.currentTimeMillis() + ".xlsx"), - EncryptData.class) - .password("123456") - .sheet() - .doWrite(data()); - } - - private List data() { - List list = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - SimpleData simpleData = new SimpleData(); - simpleData.setName("姓名" + i); - list.add(simpleData); - } - return list; - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/PoiFormatTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/PoiFormatTest.java deleted file mode 100644 index 2a5753cc3..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/PoiFormatTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.poi; - -import java.io.IOException; -import java.util.Locale; -import lombok.extern.slf4j.Slf4j; -import org.apache.poi.ss.usermodel.DataFormatter; -import org.apache.poi.xssf.streaming.SXSSFRow; -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFCell; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Test; - -/** - * 测试poi - * - * - **/ -@Slf4j -public class PoiFormatTest { - - @Test - public void lastRowNum() throws IOException { - String file = "src/test/resources/poi/last_row_number_test.xlsx"; - SXSSFWorkbook xssfWorkbook = new SXSSFWorkbook(new XSSFWorkbook(file)); - SXSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0); - log.info("一共行数:{}", xssfSheet.getLastRowNum()); - SXSSFRow row = xssfSheet.getRow(0); - log.info("第一行数据:{}", row); - xssfSheet.createRow(20); - log.info("一共行数:{}", xssfSheet.getLastRowNum()); - } - - @Test - public void lastRowNumXSSF() throws IOException { - String file = "src/test/resources/poi/last_row_number_xssf_test.xlsx"; - XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file); - log.info("一共:{}个sheet", xssfWorkbook.getNumberOfSheets()); - XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0); - log.info("一共行数:{}", xssfSheet.getLastRowNum()); - XSSFRow row = xssfSheet.getRow(1); - XSSFCell xssfCell = row.getCell(0); - DataFormatter d = new DataFormatter(Locale.CHINA); - log.info("fo:{}", d.formatCellValue(xssfCell)); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/PoiTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/PoiTest.java deleted file mode 100644 index f5bb515ce..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/PoiTest.java +++ /dev/null @@ -1,361 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.poi; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Date; -import lombok.SneakyThrows; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.util.FileUtils; -import org.apache.poi.hssf.usermodel.HSSFCellStyle; -import org.apache.poi.hssf.usermodel.HSSFFont; -import org.apache.poi.hssf.usermodel.HSSFRow; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.openxml4j.exceptions.InvalidFormatException; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.xssf.streaming.SXSSFCell; -import org.apache.poi.xssf.streaming.SXSSFRow; -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFColor; -import org.apache.poi.xssf.usermodel.XSSFFont; -import org.apache.poi.xssf.usermodel.XSSFRow; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -/** - * 测试poi - * - * - **/ -@Slf4j -public class PoiTest { - - @TempDir - Path tempDir; - - @SneakyThrows - @Test - public void lastRowNum() throws IOException { - String sourceFile = "src/test/resources/poi/last_row_number_xssf_date_test.xlsx"; - String file = tempDir.resolve(System.currentTimeMillis() + ".xlsx").toString(); - Files.copy(Paths.get(sourceFile), Paths.get(file)); - try (SXSSFWorkbook xssfWorkbook = new SXSSFWorkbook(new XSSFWorkbook(new File(file))); ) { - SXSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0); - Assertions.assertEquals(-1, xssfSheet.getLastRowNum()); - log.info("一共行数:{}", xssfSheet.getLastRowNum()); - xssfSheet.createRow(10); - SXSSFRow row = xssfSheet.getRow(10); - SXSSFCell cell1 = row.createCell(0); - SXSSFCell cell2 = row.createCell(1); - cell1.setCellValue(new Date()); - cell2.setCellValue(new Date()); - log.info("dd{}", row.getCell(0).getColumnIndex()); - Date date = row.getCell(1).getDateCellValue(); - } - } - - @Test - public void lastRowNumXSSF() throws IOException { - - String sourceFile = "src/test/resources/poi/last_row_number_xssf_date_test.xlsx"; - String file = tempDir.resolve(System.currentTimeMillis() + ".xlsx").toString(); - Files.copy(Paths.get(sourceFile), Paths.get(file)); - try (XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file); - FileOutputStream fileOutputStream = new FileOutputStream( - tempDir.resolve(System.currentTimeMillis() + ".xlsx").toFile()); ) { - - log.info("一共:{}个sheet", xssfWorkbook.getNumberOfSheets()); - XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0); - log.info("一共行数:{}", xssfSheet.getLastRowNum()); - XSSFRow row = xssfSheet.getRow(1); - log.info("dd{}", row.getCell(0).getRow().getRowNum()); - log.info("dd{}", xssfSheet.getLastRowNum()); - - XSSFCellStyle cellStyle = row.getCell(0).getCellStyle(); - log.info("size1:{}", cellStyle.getFontIndexAsInt()); - - XSSFCellStyle cellStyle1 = xssfWorkbook.createCellStyle(); - log.info("size2:{}", cellStyle1.getFontIndexAsInt()); - - cellStyle1.cloneStyleFrom(cellStyle); - log.info("size3:{}", cellStyle1.getFontIndexAsInt()); - - log.info("bbb:{}", cellStyle1.getFont().getXSSFColor().getIndex()); - log.info("bbb:{}", cellStyle1.getFont().getXSSFColor().getIndexed()); - XSSFColor myColor = - new XSSFColor(cellStyle1.getFont().getXSSFColor().getRGB(), null); - log.info("bbb:{}", cellStyle1.getFont().getXSSFColor().getRGB()); - log.info("bbb:{}", cellStyle1.getFont().getXSSFColor().getARGBHex()); - - log.info("bbb:{}", cellStyle1.getFont().getBold()); - log.info("bbb:{}", cellStyle1.getFont().getFontName()); - - XSSFFont xssfFont = xssfWorkbook.createFont(); - - xssfFont.setColor(myColor); - - xssfFont.setFontHeightInPoints((short) 50); - xssfFont.setBold(Boolean.TRUE); - cellStyle1.setFont(xssfFont); - cellStyle1.setFillForegroundColor(IndexedColors.PINK.getIndex()); - - log.info("aaa:{}", cellStyle1.getFont().getColor()); - - row.getCell(1).setCellStyle(cellStyle1); - row.getCell(1).setCellValue(3334l); - - XSSFCellStyle cellStyle2 = xssfWorkbook.createCellStyle(); - cellStyle2.cloneStyleFrom(cellStyle); - cellStyle2.setFillForegroundColor(IndexedColors.BLUE.getIndex()); - // cellStyle2.setFont(cellStyle1.getFont()); - row.getCell(2).setCellStyle(cellStyle2); - row.getCell(2).setCellValue(3334l); - // log.info("date1:{}", row.getCell(0).getStringCellValue()); - // log.info("date2:{}", ((XSSFColor) cellStyle.getFillForegroundColorColor()).getIndex()); - // log.info("date2:{}", ((XSSFColor) cellStyle.getFillForegroundColorColor()).isRGB()); - // log.info("date4:{}", ((XSSFColor) cellStyle.getFillForegroundColorColor()).isIndexed()); - // log.info("date3:{}", cellStyle.getFont().getXSSFColor().getRGB()); - // log.info("date4:{}", cellStyle.getFont().getCTFont().getColorArray(0).getRgb()); - xssfWorkbook.write(fileOutputStream); - } - } - - @Test - public void lastRowNumXSSFv22() throws IOException { - - String sourceFile = "src/test/resources/poi/last_row_number_xssf_date_test.xls"; - String file = tempDir.resolve(System.currentTimeMillis() + ".xls").toString(); - Files.copy(Paths.get(sourceFile), Paths.get(file)); - try (HSSFWorkbook xssfWorkbook = new HSSFWorkbook(Files.newInputStream(Paths.get(file.toString()))); - FileOutputStream fileOutputStream = new FileOutputStream(new File(file))) { - log.info("一共:{}个sheet", xssfWorkbook.getNumberOfSheets()); - HSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0); - log.info("一共行数:{}", xssfSheet.getLastRowNum()); - HSSFRow row = xssfSheet.getRow(1); - log.info("dd{}", row.getCell(0).getRow().getRowNum()); - log.info("dd{}", xssfSheet.getLastRowNum()); - - HSSFCellStyle cellStyle = row.getCell(0).getCellStyle(); - log.info("单元格1的字体:{}", cellStyle.getFontIndexAsInt()); - - HSSFCellStyle cellStyle1 = xssfWorkbook.createCellStyle(); - log.info("size2:{}", cellStyle1.getFontIndexAsInt()); - - cellStyle1.cloneStyleFrom(cellStyle); - log.info("单元格2的字体:{}", cellStyle1.getFontIndexAsInt()); - - log.info("bbb:{}", cellStyle1.getFont(xssfWorkbook).getColor()); - - HSSFFont xssfFont = xssfWorkbook.createFont(); - - xssfFont.setColor(cellStyle1.getFont(xssfWorkbook).getColor()); - xssfFont.setFontHeightInPoints((short) 50); - xssfFont.setBold(Boolean.TRUE); - cellStyle1.setFont(xssfFont); - cellStyle1.setFillForegroundColor(IndexedColors.PINK.getIndex()); - - log.info("aaa:{}", cellStyle1.getFont(xssfWorkbook).getColor()); - - row.getCell(1).setCellStyle(cellStyle1); - row.getCell(1).setCellValue(3334l); - - HSSFCellStyle cellStyle2 = xssfWorkbook.createCellStyle(); - cellStyle2.cloneStyleFrom(cellStyle); - cellStyle2.setFillForegroundColor(IndexedColors.BLUE.getIndex()); - // cellStyle2.setFont(cellStyle1.getFont()); - row.getCell(2).setCellStyle(cellStyle2); - row.getCell(2).setCellValue(3334l); - // log.info("date1:{}", row.getCell(0).getStringCellValue()); - // log.info("date2:{}", ((XSSFColor) cellStyle.getFillForegroundColorColor()).getIndex()); - // log.info("date2:{}", ((XSSFColor) cellStyle.getFillForegroundColorColor()).isRGB()); - // log.info("date4:{}", ((XSSFColor) cellStyle.getFillForegroundColorColor()).isIndexed()); - // log.info("date3:{}", cellStyle.getFont().getXSSFColor().getRGB()); - // log.info("date4:{}", cellStyle.getFont().getCTFont().getColorArray(0).getRgb()); - xssfWorkbook.write(fileOutputStream); - } - } - - @Test - public void lastRowNum233() throws IOException { - String sourceFile = "src/test/resources/poi/last_row_number_xssf_date_test.xlsx"; - String file = tempDir.resolve(System.currentTimeMillis() + ".xlsx").toString(); - Files.copy(Paths.get(sourceFile), Paths.get(file)); - try (XSSFWorkbook xx = new XSSFWorkbook(file); - SXSSFWorkbook xssfWorkbook = new SXSSFWorkbook(xx); - FileOutputStream fileout = new FileOutputStream( - tempDir.resolve(System.currentTimeMillis() + ".xlsx").toFile()); ) { - System.out.println(new File(file).exists()); - Sheet xssfSheet = xssfWorkbook.getXSSFWorkbook().getSheetAt(0); - Cell cell = xssfSheet.getRow(0).createCell(9); - cell.setCellValue("testssdf是士大夫否t"); - xssfWorkbook.write(fileout); - } - } - - @Test - public void lastRowNum255() throws IOException, InvalidFormatException { - String sourceFile = "src/test/resources/poi/last_row_number_xssf_date_test.xlsx"; - String file = tempDir.resolve(System.currentTimeMillis() + ".xlsx").toString(); - Files.copy(Paths.get(sourceFile), Paths.get(file)); - try (XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new File(file)); - SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(xssfWorkbook); - FileOutputStream fileout = new FileOutputStream( - tempDir.resolve(System.currentTimeMillis() + ".xlsx").toFile()); ) { - Sheet xssfSheet = xssfWorkbook.getSheetAt(0); - xssfSheet.shiftRows(1, 4, 10, true, true); - sxssfWorkbook.write(fileout); - } - } - - @Test - public void cp() throws IOException, InvalidFormatException { - String sourceFile = "src/test/resources/poi/last_row_number_xssf_date_test.xlsx"; - String file = tempDir.resolve(System.currentTimeMillis() + ".xlsx").toString(); - Files.copy(Paths.get(sourceFile), Paths.get(file)); - SXSSFWorkbook xssfWorkbook = new SXSSFWorkbook(new XSSFWorkbook(file)); - SXSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0); - log.info("一共行数:{}", xssfSheet.getLastRowNum()); - SXSSFRow row = xssfSheet.getRow(0); - log.info("第一行数据:{}", row); - xssfSheet.createRow(20); - log.info("一共行数:{}", xssfSheet.getLastRowNum()); - } - - @Test - public void lastRowNum233443() throws IOException, InvalidFormatException { - String sourceFile = "src/test/resources/poi/last_row_number_xssf_date_test.xlsx"; - String file = tempDir.resolve(System.currentTimeMillis() + ".xlsx").toString(); - Files.copy(Paths.get(sourceFile), Paths.get(file)); - XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new File(file)); - XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0); - System.out.println(xssfSheet.getLastRowNum()); - System.out.println(xssfSheet.getRow(0)); - } - - @Test - public void lastRowNum2333() throws IOException, InvalidFormatException { - String sourceFile = "src/test/resources/poi/last_row_number_xssf_date_test.xlsx"; - String file = tempDir.resolve(System.currentTimeMillis() + ".xlsx").toString(); - Files.copy(Paths.get(sourceFile), Paths.get(file)); - try (XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new File(file)); - SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(xssfWorkbook); - FileOutputStream fileout = new FileOutputStream( - tempDir.resolve(System.currentTimeMillis() + ".xlsx").toFile()); ) { - Sheet xssfSheet = xssfWorkbook.getSheetAt(0); - Cell cell = xssfSheet.getRow(0).createCell(9); - cell.setCellValue("testssdf是士大夫否t"); - sxssfWorkbook.write(fileout); - } - } - - @Test - public void testread() throws IOException { - String sourceFile = "src/test/resources/simple/simple07.xlsx"; - String file = tempDir.resolve(System.currentTimeMillis() + ".xlsx").toString(); - Files.copy(Paths.get(sourceFile), Paths.get(file)); - try (SXSSFWorkbook xssfWorkbook = new SXSSFWorkbook(new XSSFWorkbook(file)); ) { - Sheet xssfSheet = xssfWorkbook.getXSSFWorkbook().getSheetAt(0); - // - // Cell cell = xssfSheet.getRow(0).createCell(9); - } - - String file1 = tempDir.resolve(System.currentTimeMillis() + ".xlsx").toString(); - Files.copy(Paths.get(sourceFile), Paths.get(file1)); - - try (SXSSFWorkbook xssfWorkbook1 = new SXSSFWorkbook(new XSSFWorkbook(file1)); ) { - Sheet xssfSheet1 = xssfWorkbook1.getXSSFWorkbook().getSheetAt(0); - // Cell cell1 = xssfSheet1.getRow(0).createCell(9); - } - } - - @Test - public void testreadRead() throws IOException { - String sourceFile = "src/test/resources/poi/last_row_number_xssf_date_test.xlsx"; - String file = tempDir.resolve(System.currentTimeMillis() + ".xlsx").toString(); - Files.copy(Paths.get(sourceFile), Paths.get(file)); - FileUtils.readFileToByteArray(new File(file)); - } - - @Test - public void lastRowNum2332222() throws IOException { - String sourceFile = "src/test/resources/poi/last_row_number_xssf_date_test.xlsx"; - String file = tempDir.resolve(System.currentTimeMillis() + ".xlsx").toString(); - Files.copy(Paths.get(sourceFile), Paths.get(file)); - try (SXSSFWorkbook xssfWorkbook = new SXSSFWorkbook(new XSSFWorkbook(file)); - FileOutputStream fileout = new FileOutputStream( - tempDir.resolve(System.currentTimeMillis() + ".xlsx").toFile()); ) { - Sheet xssfSheet = xssfWorkbook.getXSSFWorkbook().getSheetAt(0); - Cell cell = xssfSheet.getRow(0).createCell(9); - cell.setCellValue("testssdf是士大夫否t"); - xssfWorkbook.write(fileout); - } - } - - @Test - public void lastRowNum23443() throws IOException { - String sourceFile = "src/test/resources/poi/last_row_number_xssf_date_test.xlsx"; - String file = tempDir.resolve(System.currentTimeMillis() + ".xlsx").toString(); - Files.copy(Paths.get(sourceFile), Paths.get(file)); - try (SXSSFWorkbook xssfWorkbook = new SXSSFWorkbook(new XSSFWorkbook(file)); - FileOutputStream fileout = new FileOutputStream( - tempDir.resolve(System.currentTimeMillis() + ".xlsx").toFile()); ) { - Sheet xssfSheet = xssfWorkbook.getSheetAt(0); - xssfWorkbook.write(fileout); - } - } - - @Test - public void lastRowNum2() throws IOException { - String sourceFile = "src/test/resources/poi/last_row_number_xssf_date_test.xlsx"; - String file = tempDir.resolve(System.currentTimeMillis() + ".xlsx").toString(); - Files.copy(Paths.get(sourceFile), Paths.get(file)); - SXSSFWorkbook xssfWorkbook = new SXSSFWorkbook(new XSSFWorkbook(file)); - Sheet xssfSheet = xssfWorkbook.getXSSFWorkbook().getSheetAt(0); - log.info("一共行数:{}", xssfSheet.getPhysicalNumberOfRows()); - log.info("一共行数:{}", xssfSheet.getLastRowNum()); - log.info("一共行数:{}", xssfSheet.getFirstRowNum()); - } - - @Test - public void lastRowNumXSSF2() throws IOException { - String sourceFile = "src/test/resources/poi/last_row_number_xssf_date_test.xlsx"; - String file = tempDir.resolve(System.currentTimeMillis() + ".xlsx").toString(); - Files.copy(Paths.get(sourceFile), Paths.get(file)); - XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file); - log.info("一共:{}个sheet", xssfWorkbook.getNumberOfSheets()); - XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0); - log.info("一共行数:{}", xssfSheet.getLastRowNum()); - XSSFRow row = xssfSheet.getRow(0); - log.info("第一行数据:{}", row); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/PoiWriteTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/PoiWriteTest.java deleted file mode 100644 index 9ce1941f8..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/PoiWriteTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.poi; - -import com.alibaba.fastjson2.JSON; -import java.io.FileOutputStream; -import java.io.IOException; -import java.math.BigDecimal; -import java.nio.file.Path; -import org.apache.poi.xssf.streaming.SXSSFCell; -import org.apache.poi.xssf.streaming.SXSSFRow; -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -/** - * 测试poi - * - * - **/ -public class PoiWriteTest { - - @Test - public void write0(@TempDir Path path) throws IOException { - try (FileOutputStream fileOutputStream = - new FileOutputStream(path.resolve("PoiWriteTest_" + System.currentTimeMillis() + ".xlsx") - .toFile()); - SXSSFWorkbook workbook = new SXSSFWorkbook()) { - SXSSFSheet sheet = workbook.createSheet("t1"); - SXSSFRow row = sheet.createRow(0); - SXSSFCell cell1 = row.createCell(0); - cell1.setCellValue(999999999999999L); - SXSSFCell cell2 = row.createCell(1); - cell2.setCellValue(1000000000000001L); - SXSSFCell cell32 = row.createCell(2); - cell32.setCellValue(300.35f); - workbook.write(fileOutputStream); - } - } - - @Test - public void write01() throws IOException { - float ff = 300.35f; - BigDecimal bd = new BigDecimal(Float.toString(ff)); - System.out.println(bd.doubleValue()); - System.out.println(bd.floatValue()); - } - - @Test - public void write(@TempDir Path path) throws IOException { - try (FileOutputStream fileOutputStream = - new FileOutputStream(path.resolve("PoiWriteTest_" + System.currentTimeMillis() + ".xlsx") - .toFile()); - SXSSFWorkbook workbook = new SXSSFWorkbook()) { - SXSSFSheet sheet = workbook.createSheet("t1"); - SXSSFRow row = sheet.createRow(0); - SXSSFCell cell1 = row.createCell(0); - cell1.setCellValue(Long.toString(999999999999999L)); - SXSSFCell cell2 = row.createCell(1); - cell2.setCellValue(Long.toString(1000000000000001L)); - workbook.write(fileOutputStream); - } - } - - @Test - public void write1() { - System.out.println(JSON.toJSONString(long2Bytes(-999999999999999L))); - System.out.println(JSON.toJSONString(long2Bytes(-9999999999999999L))); - } - - public static byte[] long2Bytes(long num) { - byte[] byteNum = new byte[8]; - for (int ix = 0; ix < 8; ++ix) { - int offset = 64 - (ix + 1) * 8; - byteNum[ix] = (byte) ((num >> offset) & 0xff); - } - return byteNum; - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/TestCell.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/TestCell.java deleted file mode 100644 index e389f3d89..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/poi/TestCell.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.poi; - -import java.util.List; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.metadata.data.CellData; - -/** - * - */ -@Getter -@Setter -@EqualsAndHashCode -public class TestCell { - private CellData c1; - private CellData> c2; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/CommentTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/CommentTest.java deleted file mode 100644 index 1e02657c6..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/CommentTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.read; - -import com.alibaba.fastjson2.JSON; -import java.io.File; -import java.util.Arrays; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.enums.CellExtraTypeEnum; -import org.apache.fesod.sheet.metadata.CellExtra; -import org.apache.fesod.sheet.read.listener.ReadListener; -import org.apache.fesod.sheet.support.ExcelTypeEnum; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -@Slf4j -public class CommentTest { - - private final List commentList = Arrays.asList("测试", "comment"); - - private void runCommentTest(String filePath, ExcelTypeEnum excelType) throws Exception { - File file = new File(filePath); - FastExcel.read(file, new ReadListener() { - @Override - public void invoke(Object data, AnalysisContext context) { - // 当前测试不关心数据读取 - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - // 当前测试不关心读取完成后的逻辑 - } - - @Override - public void extra(CellExtra extra, AnalysisContext context) { - log.info("读取到了一条额外信息:{}", JSON.toJSONString(extra)); - if (extra.getType().equals(CellExtraTypeEnum.COMMENT)) { - Assertions.assertTrue(commentList.contains(extra.getText())); - } - } - }) - .excelType(excelType) - .extraRead(CellExtraTypeEnum.COMMENT) - .sheet() - .doRead(); - } - - @Test - public void xlsxCommentTest() throws Exception { - runCommentTest("src/test/resources/comment/comment.xlsx", ExcelTypeEnum.XLSX); - } - - @Test - public void xlsCommentTest() throws Exception { - runCommentTest("src/test/resources/comment/comment.xls", ExcelTypeEnum.XLS); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/HDListener.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/HDListener.java deleted file mode 100644 index 00824d97d..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/HDListener.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.read; - -import com.alibaba.fastjson2.JSON; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; - -/** - * 模板的读取类 - * - * - */ -@Slf4j -public class HDListener extends AnalysisEventListener { - - /** - * 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收 - */ - private static final int BATCH_COUNT = 5; - - @Override - public void invokeHeadMap(Map headMap, AnalysisContext context) { - log.info("HEAD:{}", JSON.toJSONString(headMap)); - log.info("total:{}", context.readSheetHolder().getTotal()); - } - - @Override - public void invoke(HeadReadData data, AnalysisContext context) { - log.info("index:{}", context.readRowHolder().getRowIndex()); - log.info("解析到一条数据:{}", JSON.toJSONString(data)); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - log.info("所有数据解析完成!"); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/HeadListener.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/HeadListener.java deleted file mode 100644 index 5486c7751..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/HeadListener.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.read; - -import com.alibaba.fastjson2.JSON; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; - -/** - * 模板的读取类 - * - * - */ -@Slf4j -public class HeadListener extends AnalysisEventListener { - - /** - * 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收 - */ - private static final int BATCH_COUNT = 5; - - @Override - public void invokeHeadMap(Map headMap, AnalysisContext context) { - log.info("HEAD:{}", JSON.toJSONString(headMap)); - log.info("total:{}", context.readSheetHolder().getTotal()); - } - - @Override - public void invoke(HeadReadData data, AnalysisContext context) { - log.info("index:{}", context.readRowHolder().getRowIndex()); - log.info("解析到一条数据:{}", JSON.toJSONString(data)); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - log.info("所有数据解析完成!"); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/HeadReadData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/HeadReadData.java deleted file mode 100644 index d7db31931..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/HeadReadData.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.read; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelProperty; - -/** - * 临时测试 - * - * - **/ -@Getter -@Setter -@EqualsAndHashCode -public class HeadReadData { - @ExcelProperty({"主标题", "数据1"}) - private String h1; - - @ExcelProperty({"主标题", "数据2"}) - private String h2; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/HeadReadTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/HeadReadTest.java deleted file mode 100644 index 9d5069769..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/HeadReadTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.read; - -import java.io.File; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.cache.Ehcache; -import org.junit.jupiter.api.Test; - -/** - * 临时测试 - * - * - **/ -@Slf4j -public class HeadReadTest { - - @Test - public void test() throws Exception { - File file = new File("src/test/resources/cache/t2.xlsx"); - FastExcel.read(file, HeadReadData.class, new HeadListener()) - .ignoreEmptyRow(false) - .sheet(0) - .doRead(); - } - - @Test - public void testCache() throws Exception { - File file = new File("src/test/resources/cache/headt1.xls"); - FastExcel.read(file, HeadReadData.class, new HDListener()) - .readCache(new Ehcache(20)) - .sheet(0) - .doRead(); - - log.info("------------------"); - FastExcel.read(file, HeadReadData.class, new HDListener()) - .readCache(new Ehcache(20)) - .sheet(0) - .doRead(); - log.info("------------------"); - FastExcel.read(file, HeadReadData.class, new HDListener()) - .readCache(new Ehcache(20)) - .sheet(0) - .doRead(); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/WebStreamReadTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/WebStreamReadTest.java deleted file mode 100644 index 40fd68e96..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/read/WebStreamReadTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.read; - -import static org.mockserver.model.HttpRequest.request; -import static org.mockserver.model.HttpResponse.response; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.LinkedList; -import java.util.List; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.demo.read.Sample; -import org.apache.fesod.sheet.read.listener.ReadListener; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.mockserver.integration.ClientAndServer; - -public class WebStreamReadTest { - - private ClientAndServer mockServer; - - @BeforeEach - public void startServer() { - this.mockServer = ClientAndServer.startClientAndServer(); - } - - @Test - public void urlLoadInputStreamTest() throws IOException { - mockServer - .when(request().withMethod("GET").withPath("/sample.xlsx")) - .respond(response() - .withStatusCode(200) - .withHeader("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") - .withBody(Files.readAllBytes(Paths.get("src/test/resources/web/io.xlsx")))); - URL url = new URL("http://localhost:" + mockServer.getPort() + "/sample.xlsx"); - InputStream is = url.openStream(); - List body = new LinkedList<>(); - FastExcel.read(is, Sample.class, new ReadListener() { - @Override - public void invoke(Sample data, AnalysisContext context) { - body.add(data.getHeader()); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) {} - }) - .sheet() - .doRead(); - Assertions.assertTrue(body.contains("body")); - } - - @AfterEach - public void stopServer() { - mockServer.stop(); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/DemoData1.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/DemoData1.java deleted file mode 100644 index 0c2bd33e7..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/DemoData1.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.simple; - -import java.util.Date; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelIgnore; -import org.apache.fesod.sheet.annotation.ExcelProperty; -import org.apache.fesod.sheet.annotation.write.style.HeadStyle; -import org.apache.fesod.sheet.enums.poi.FillPatternTypeEnum; - -@Getter -@Setter -@EqualsAndHashCode -public class DemoData1 { - @ExcelProperty("字符串标题") - @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 42) - private String string; - - @ExcelProperty("日期标题") - private Date date; - - @ExcelProperty("数字标题") - private Double doubleData; - /** - * 忽略这个字段 - */ - @ExcelIgnore - private String ignore; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/DemoData2.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/DemoData2.java deleted file mode 100644 index 9d774ef11..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/DemoData2.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.simple; - -import java.util.Date; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; -import org.apache.fesod.sheet.annotation.ExcelIgnore; -import org.apache.fesod.sheet.annotation.ExcelProperty; -import org.apache.fesod.sheet.annotation.write.style.HeadStyle; -import org.apache.fesod.sheet.enums.poi.FillPatternTypeEnum; - -@Getter -@Setter -@EqualsAndHashCode -public class DemoData2 { - @ExcelProperty("字符串标题") - @HeadStyle(fillPatternType = FillPatternTypeEnum.SOLID_FOREGROUND, fillForegroundColor = 42) - private String string; - - @ExcelProperty("日期标题") - private Date date; - - @ExcelProperty("数字标题") - private Double doubleData; - /** - * 忽略这个字段 - */ - @ExcelIgnore - private String ignore; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/HgListener.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/HgListener.java deleted file mode 100644 index 93bca3cb5..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/HgListener.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.simple; - -import com.alibaba.fastjson2.JSON; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; - -/** - * 模板的读取类 - * - * - */ -@Slf4j -public class HgListener extends AnalysisEventListener> { - - /** - * 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收 - */ - private static final int BATCH_COUNT = 5; - - @Override - public void invoke(Map data, AnalysisContext context) { - log.info("index:{}", context.readRowHolder().getRowIndex()); - log.info("解析到一条数据:{}", JSON.toJSONString(data)); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - log.info("所有数据解析完成!"); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/JsonData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/JsonData.java deleted file mode 100644 index 6c42beaa7..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/JsonData.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.simple; - -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; - -/** - * TODO - * - * - **/ -@Getter -@Setter -@EqualsAndHashCode -public class JsonData { - private String SS1; - private String sS2; - private String ss3; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/RepeatListener.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/RepeatListener.java deleted file mode 100644 index f649e56b7..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/RepeatListener.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.simple; - -import com.alibaba.fastjson2.JSON; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.context.AnalysisContext; -import org.apache.fesod.sheet.event.AnalysisEventListener; -import org.apache.fesod.sheet.temp.LockData; - -/** - * 模板的读取类 - * - * - */ -@Slf4j -public class RepeatListener extends AnalysisEventListener { - - /** - * 每隔5条存储数据库,实际使用中可以100条,然后清理list ,方便内存回收 - */ - private static final int BATCH_COUNT = 5; - - List list = new ArrayList(); - - @Override - public void invoke(LockData data, AnalysisContext context) { - log.info("解析到一条数据:{}", JSON.toJSONString(data)); - list.add(data); - if (list.size() >= BATCH_COUNT) { - saveData(); - list.clear(); - } - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - saveData(); - log.info("所有数据解析完成!"); - } - - /** - * 加上存储数据库 - */ - private void saveData() { - log.info("{}条数据,开始存储数据库!", list.size()); - log.info("存储数据库成功!"); - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/RepeatTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/RepeatTest.java deleted file mode 100644 index ec21316e1..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/RepeatTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.simple; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import org.apache.fesod.sheet.ExcelReader; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.read.metadata.ReadSheet; -import org.apache.fesod.sheet.temp.LockData; -import org.junit.jupiter.api.Test; - -/** - * 测试poi - * - * - **/ -public class RepeatTest { - - @Test - public void xlsTest1() throws IOException { - try (ExcelReader reader = FastExcel.read( - Files.newInputStream(Paths.get("src/test/resources/repeat/repeat.xls")), - LockData.class, - new RepeatListener()) - .headRowNumber(0) - .build()) { - ReadSheet r1 = FastExcel.readSheet(0).build(); - ReadSheet r2 = FastExcel.readSheet(2).build(); - reader.read(r1); - reader.read(r2); - reader.finish(); - } - } - - @Test - public void xlsTest2() throws IOException { - try (ExcelReader reader = FastExcel.read( - Files.newInputStream(Paths.get("src/test/resources/repeat/repeat.xls")), - LockData.class, - new RepeatListener()) - .headRowNumber(0) - .build()) { - ReadSheet r2 = FastExcel.readSheet(1).build(); - reader.read(r2); - reader.finish(); - } - } - - @Test - public void xlsTest3() throws IOException { - try (ExcelReader reader = FastExcel.read( - Files.newInputStream(Paths.get("src/test/resources/repeat/repeat.xls")), - LockData.class, - new RepeatListener()) - .headRowNumber(0) - .build()) { - ReadSheet r2 = FastExcel.readSheet(0).build(); - reader.read(r2); - reader.finish(); - } - } - - @Test - public void xlsxTest1() throws IOException { - try (ExcelReader reader = FastExcel.read( - Files.newInputStream(Paths.get("src/test/resources/repeat/repeat.xlsx")), - LockData.class, - new RepeatListener()) - .headRowNumber(0) - .build()) { - ReadSheet r1 = FastExcel.readSheet(0).build(); - ReadSheet r2 = FastExcel.readSheet(2).build(); - reader.read(r1); - reader.read(r2); - reader.finish(); - } - } - - @Test - public void xlsxTest2() throws IOException { - try (ExcelReader reader = FastExcel.read( - Files.newInputStream(Paths.get("src/test/resources/repeat/repeat.xlsx")), - LockData.class, - new RepeatListener()) - .headRowNumber(0) - .build()) { - ReadSheet r2 = FastExcel.readSheet(1).build(); - reader.read(r2); - reader.finish(); - } - } - - @Test - public void xlsxTest3() throws IOException { - try (ExcelReader reader = FastExcel.read( - Files.newInputStream(Paths.get("src/test/resources/repeat/repeat.xlsx")), - LockData.class, - new RepeatListener()) - .headRowNumber(0) - .build()) { - ReadSheet r2 = FastExcel.readSheet(0).build(); - reader.read(r2); - reader.finish(); - } - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/Write.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/Write.java deleted file mode 100644 index e2c01ac2b..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/Write.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.simple; - -import com.alibaba.fastjson2.JSON; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.ExcelWriter; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.demo.write.DemoData; -import org.apache.fesod.sheet.temp.large.LargeData; -import org.apache.fesod.sheet.util.BeanMapUtils; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.fesod.sheet.write.metadata.WriteSheet; -import org.apache.fesod.sheet.write.metadata.WriteTable; -import org.junit.jupiter.api.Test; - -/** - * 测试poi - * - * - **/ -@Slf4j -public class Write { - - @Test - public void simpleWrite1() { - LargeData ss = new LargeData(); - ss.setStr23("ttt"); - Map map = BeanMapUtils.create(ss); - System.out.println(map.containsKey("str23")); - System.out.println(map.containsKey("str22")); - System.out.println(map.get("str23")); - System.out.println(map.get("str22")); - } - - @Test - public void simpleWrite() { - log.info("t5"); - // 写法1 - String fileName = TestFileUtil.getPath() + "t22" + System.currentTimeMillis() + ".xlsx"; - // 这里 需要指定写用哪个class去读,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 - // 如果这里想使用03 则 传入excelType参数即可 - FastExcel.write(fileName, DemoData.class) - .relativeHeadRowIndex(10) - .sheet("模板") - .doWrite(data()); - } - - @Test - public void simpleWrite2() { - // 写法1 - String fileName = TestFileUtil.getPath() + "t22" + System.currentTimeMillis() + ".xlsx"; - // 这里 需要指定写用哪个class去读,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 - // 如果这里想使用03 则 传入excelType参数即可 - FastExcel.write(fileName, WriteData.class) - .sheet("模板") - .registerWriteHandler(new WriteHandler()) - .doWrite(data1()); - } - - @Test - public void simpleWrite3() { - // 写法1 - String fileName = TestFileUtil.getPath() + "t33" + System.currentTimeMillis() + ".xlsx"; - // 这里 需要指定写用哪个class去读,然后写到第一个sheet,名字为模板 然后文件流会自动关闭 - // 如果这里想使用03 则 传入excelType参数即可 - FastExcel.write(fileName) - .head(head()) - .inMemory(true) - .sheet("模板") - .registerWriteHandler(new WriteCellHandler()) - .doWrite(data1()); - } - - @Test - public void json() { - JsonData jsonData = new JsonData(); - jsonData.setSS1("11"); - jsonData.setSS2("22"); - jsonData.setSs3("33"); - System.out.println(JSON.toJSONString(jsonData)); - } - - @Test - public void json3() { - String json = "{\"SS1\":\"11\",\"sS2\":\"22\",\"ss3\":\"33\"}"; - - JsonData jsonData = JSON.parseObject(json, JsonData.class); - System.out.println(JSON.toJSONString(jsonData)); - } - - @Test - public void tableWrite() { - String fileName = TestFileUtil.getPath() + "tableWrite" + System.currentTimeMillis() + ".xlsx"; - // 这里直接写多个table的案例了,如果只有一个 也可以直一行代码搞定,参照其他案例 - // 这里 需要指定写用哪个class去写 - ExcelWriter excelWriter = FastExcel.write(fileName).build(); - // 把sheet设置为不需要头 不然会输出sheet的头 这样看起来第一个table 就有2个头了 - WriteSheet writeSheet = FastExcel.writerSheet("模板").build(); - // 这里必须指定需要头,table 会继承sheet的配置,sheet配置了不需要,table 默认也是不需要 - WriteTable writeTable0 = FastExcel.writerTable(0).head(DemoData1.class).build(); - // 第一次写入会创建头 - excelWriter.write(data(), writeSheet, writeTable0); - // 第二次写如也会创建头,然后在第一次的后面写入数据 - /// 千万别忘记close 会帮忙关闭流 - excelWriter.finish(); - } - - private List> head() { - List> list = new ArrayList>(); - List head0 = new ArrayList(); - head0.add("字符串" + System.currentTimeMillis()); - List head1 = new ArrayList(); - head1.add("数字" + System.currentTimeMillis()); - List head2 = new ArrayList(); - head2.add("日期" + System.currentTimeMillis()); - list.add(head0); - list.add(head1); - list.add(head2); - return list; - } - - private List data() { - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - DemoData data = new DemoData(); - data.setString("640121807369666560" + i); - data.setDate(new Date()); - data.setDoubleData(null); - list.add(data); - } - return list; - } - - private List data1() { - List list = new ArrayList(); - for (int i = 0; i < 10; i++) { - WriteData data = new WriteData(); - data.setDd(new Date()); - data.setF1(33f); - list.add(data); - } - return list; - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/WriteCellHandler.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/WriteCellHandler.java deleted file mode 100644 index cf83f413e..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/WriteCellHandler.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.simple; - -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.sheet.metadata.Head; -import org.apache.fesod.sheet.metadata.data.WriteCellData; -import org.apache.fesod.sheet.write.handler.CellWriteHandler; -import org.apache.fesod.sheet.write.metadata.holder.WriteSheetHolder; -import org.apache.fesod.sheet.write.metadata.holder.WriteTableHolder; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.DataFormat; -import org.apache.poi.ss.usermodel.IndexedColors; - -/** - * - */ -@Slf4j -public class WriteCellHandler implements CellWriteHandler { - - @Override - public void afterCellDataConverted( - WriteSheetHolder writeSheetHolder, - WriteTableHolder writeTableHolder, - WriteCellData cellData, - Cell cell, - Head head, - Integer integer, - Boolean isHead) { - - if (!isHead) { - CreationHelper createHelper = - writeSheetHolder.getSheet().getWorkbook().getCreationHelper(); - CellStyle cellStyle = writeSheetHolder.getSheet().getWorkbook().createCellStyle(); - if (cellStyle != null) { - DataFormat dataFormat = createHelper.createDataFormat(); - cellStyle.setWrapText(true); - cellStyle.setFillBackgroundColor(IndexedColors.RED.getIndex()); - cellStyle.setBottomBorderColor(IndexedColors.RED.getIndex()); - cellStyle.setDataFormat(dataFormat.getFormat("yyyy-MM-dd")); - cell.setCellStyle(cellStyle); - } - } - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/WriteData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/WriteData.java deleted file mode 100644 index 84926fa1d..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/simple/WriteData.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.simple; - -import java.util.Date; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.Setter; - -/** - * write data - * - * - **/ -@Getter -@Setter -@EqualsAndHashCode -public class WriteData { - // @ContentStyle(locked = true) - private Date dd; - // @ContentStyle(locked = false) - private float f1; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/write/TempWriteData.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/write/TempWriteData.java deleted file mode 100644 index ad2fcd483..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/write/TempWriteData.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.write; - -import lombok.Data; -import org.apache.fesod.sheet.annotation.ExcelProperty; -import org.apache.fesod.sheet.annotation.write.style.ContentStyle; -import org.apache.fesod.sheet.annotation.write.style.HeadStyle; -import org.apache.fesod.sheet.enums.BooleanEnum; - -@Data -// @Accessors(chain = true) -public class TempWriteData { - private String name1; - - @ExcelProperty(" 换行\r\n \\ \r\n的名字") - @HeadStyle(wrapped = BooleanEnum.TRUE) - @ContentStyle(wrapped = BooleanEnum.TRUE) - private String name; -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/write/TempWriteTest.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/write/TempWriteTest.java deleted file mode 100644 index 0866b30c7..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/temp/write/TempWriteTest.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.temp.write; - -import java.io.File; -import java.io.FileOutputStream; -import java.nio.file.Path; -import java.util.HashMap; -import java.util.Map; -import lombok.extern.slf4j.Slf4j; -import org.apache.fesod.common.util.ListUtils; -import org.apache.fesod.shaded.cglib.beans.BeanMap; -import org.apache.fesod.sheet.FastExcel; -import org.apache.fesod.sheet.demo.write.CustomStringStringConverter; -import org.apache.fesod.sheet.util.BeanMapUtils; -import org.apache.fesod.sheet.util.FileUtils; -import org.apache.fesod.sheet.util.TestFileUtil; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.CreationHelper; -import org.apache.poi.ss.usermodel.Picture; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.streaming.SXSSFCell; -import org.apache.poi.xssf.streaming.SXSSFDrawing; -import org.apache.poi.xssf.streaming.SXSSFRow; -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -@Slf4j -public class TempWriteTest { - - @Test - public void write() { - TempWriteData tempWriteData = new TempWriteData(); - tempWriteData.setName("zs\r\n \\ \r\n t4"); - FastExcel.write( - TestFileUtil.getPath() + "TempWriteTest" + System.currentTimeMillis() + ".xlsx", - TempWriteData.class) - .sheet() - .registerConverter(new CustomStringStringConverter()) - .doWrite(ListUtils.newArrayList(tempWriteData)); - - FastExcel.write( - TestFileUtil.getPath() + "TempWriteTest" + System.currentTimeMillis() + ".xlsx", - TempWriteData.class) - .sheet() - .doWrite(ListUtils.newArrayList(tempWriteData)); - } - - @Test - public void cglib() { - TempWriteData tempWriteData = new TempWriteData(); - tempWriteData.setName("1"); - tempWriteData.setName1("2"); - BeanMap beanMap = BeanMapUtils.create(tempWriteData); - - log.info("d1{}", beanMap.get("name")); - log.info("d2{}", beanMap.get("name1")); - - TempWriteData tempWriteData2 = new TempWriteData(); - - Map map = new HashMap<>(); - map.put("name", "zs"); - BeanMap beanMap2 = BeanMapUtils.create(tempWriteData2); - beanMap2.putAll(map); - log.info("3{}", tempWriteData2.getName()); - } - - @Test - public void imageWrite() throws Exception { - // String fileName = TestFileUtil.getPath() + "imageWrite" + System.currentTimeMillis() + ".xlsx"; - // - //// 这里 需要指定写用哪个class去写 - // try (ExcelWriter excelWriter = FastExcel.write(fileName, DemoData.class).build()) { - // // 这里注意 如果同一个sheet只要创建一次 - // WriteSheet writeSheet = FastExcel.writerSheet("模板").build(); - // // 去调用写入,这里我调用了五次,实际使用时根据数据库分页的总的页数来 - // for (int i = 0; i < 5; i++) { - // // 分页去数据库查询数据 这里可以去数据库查询每一页的数据 - // List data = data(); - // excelWriter.write(data, writeSheet); - // } - // } - } - - @Test - public void imageWritePoi(@TempDir Path tempDir) throws Exception { - String file = tempDir.resolve(System.currentTimeMillis() + ".xlsx").toString(); - try (SXSSFWorkbook workbook = new SXSSFWorkbook(); - FileOutputStream fileOutputStream = new FileOutputStream(file); ) { - SXSSFSheet sheet = workbook.createSheet("测试"); - CreationHelper helper = workbook.getCreationHelper(); - SXSSFDrawing sxssfDrawin = sheet.createDrawingPatriarch(); - - byte[] imagebyte = FileUtils.readFileToByteArray(new File("src/test/resources/converter/img.jpg")); - - for (int i = 0; i < 1 * 10000; i++) { - SXSSFRow row = sheet.createRow(i); - SXSSFCell cell = row.createCell(0); - cell.setCellValue(i); - int pictureIdx = workbook.addPicture(imagebyte, Workbook.PICTURE_TYPE_JPEG); - ClientAnchor anchor = helper.createClientAnchor(); - anchor.setCol1(0); - anchor.setRow1(i); - // 插入图片 - Picture pict = sxssfDrawin.createPicture(anchor, pictureIdx); - pict.resize(); - log.info("新增行:{}", i); - } - workbook.write(fileOutputStream); - } - } - - @Test - public void tep(@TempDir Path tempDir) throws Exception { - String file = tempDir.resolve(System.currentTimeMillis() + ".xlsx").toString(); - try (SXSSFWorkbook workbook = new SXSSFWorkbook(); - FileOutputStream fileOutputStream = new FileOutputStream(file); ) { - SXSSFSheet sheet = workbook.createSheet("测试"); - CreationHelper helper = workbook.getCreationHelper(); - SXSSFDrawing sxssfDrawin = sheet.createDrawingPatriarch(); - - byte[] imagebyte = FileUtils.readFileToByteArray(new File("src/test/resources/converter/img.jpg")); - - for (int i = 0; i < 1 * 10000; i++) { - SXSSFRow row = sheet.createRow(i); - SXSSFCell cell = row.createCell(0); - cell.setCellValue(i); - int pictureIdx = workbook.addPicture(imagebyte, Workbook.PICTURE_TYPE_JPEG); - ClientAnchor anchor = helper.createClientAnchor(); - anchor.setCol1(0); - anchor.setRow1(i); - // 插入图片 - Picture pict = sxssfDrawin.createPicture(anchor, pictureIdx); - pict.resize(); - log.info("新增行:{}", i); - } - workbook.write(fileOutputStream); - } - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/util/StyleTestUtils.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/util/StyleTestUtils.java deleted file mode 100644 index c474aa971..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/util/StyleTestUtils.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.util; - -import org.apache.poi.hssf.usermodel.HSSFCell; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.xssf.usermodel.XSSFCell; - -public class StyleTestUtils { - - public static byte[] getFillForegroundColor(Cell cell) { - if (cell instanceof XSSFCell) { - return ((XSSFCell) cell) - .getCellStyle() - .getFillForegroundColorColor() - .getRGB(); - } else { - return short2byte(((HSSFCell) cell) - .getCellStyle() - .getFillForegroundColorColor() - .getTriplet()); - } - } - - public static byte[] getFontColor(Cell cell, Workbook workbook) { - if (cell instanceof XSSFCell) { - return ((XSSFCell) cell).getCellStyle().getFont().getXSSFColor().getRGB(); - } else { - return short2byte(((HSSFCell) cell) - .getCellStyle() - .getFont(workbook) - .getHSSFColor((HSSFWorkbook) workbook) - .getTriplet()); - } - } - - public static short getFontHeightInPoints(Cell cell, Workbook workbook) { - if (cell instanceof XSSFCell) { - return ((XSSFCell) cell).getCellStyle().getFont().getFontHeightInPoints(); - } else { - return ((HSSFCell) cell).getCellStyle().getFont(workbook).getFontHeightInPoints(); - } - } - - private static byte[] short2byte(short[] shorts) { - byte[] bytes = new byte[shorts.length]; - for (int i = 0; i < shorts.length; i++) { - bytes[i] = (byte) shorts[i]; - } - return bytes; - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/util/TestFileUtil.java b/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/util/TestFileUtil.java deleted file mode 100644 index 094d9d3ee..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/java/org/apache/fesod/sheet/util/TestFileUtil.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * 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 org.apache.fesod.sheet.util; - -import java.io.File; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; -import org.apache.commons.collections4.CollectionUtils; - -public class TestFileUtil { - - public static InputStream getResourcesFileInputStream(String fileName) { - return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName); - } - - public static String getPath() { - return TestFileUtil.class.getResource("/").getPath(); - } - - public static TestPathBuild pathBuild() { - return new TestPathBuild(); - } - - public static File createNewFile(String pathName) { - File file = new File(getPath() + pathName); - if (file.exists()) { - file.delete(); - } else { - if (!file.getParentFile().exists()) { - file.getParentFile().mkdirs(); - } - } - return file; - } - - public static File readFile(String pathName) { - return new File(getPath() + pathName); - } - - public static File readUserHomeFile(String pathName) { - return new File(System.getProperty("user.home") + File.separator + pathName); - } - - /** - * build to test file path - **/ - public static class TestPathBuild { - private TestPathBuild() { - subPath = new ArrayList<>(); - } - - private final List subPath; - - public TestPathBuild sub(String dirOrFile) { - subPath.add(dirOrFile); - return this; - } - - public String getPath() { - if (CollectionUtils.isEmpty(subPath)) { - return TestFileUtil.class.getResource("/").getPath(); - } - if (subPath.size() == 1) { - return TestFileUtil.class.getResource("/").getPath() + subPath.get(0); - } - StringBuilder path = - new StringBuilder(TestFileUtil.class.getResource("/").getPath()); - path.append(subPath.get(0)); - for (int i = 1; i < subPath.size(); i++) { - path.append(File.separator).append(subPath.get(i)); - } - return path.toString(); - } - } -} diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/bom/no_bom.csv b/fesod-examples/fesod-sheet-examples/src/test/resources/bom/no_bom.csv deleted file mode 100644 index 461c1eb00..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/resources/bom/no_bom.csv +++ /dev/null @@ -1,11 +0,0 @@ -姓名,年纪 -姓名0,20 -姓名1,20 -姓名2,20 -姓名3,20 -姓名4,20 -姓名5,20 -姓名6,20 -姓名7,20 -姓名8,20 -姓名9,20 \ No newline at end of file diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/bom/office_bom.csv b/fesod-examples/fesod-sheet-examples/src/test/resources/bom/office_bom.csv deleted file mode 100644 index b6a80992d..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/resources/bom/office_bom.csv +++ /dev/null @@ -1,11 +0,0 @@ -姓名,年纪 -姓名0,20 -姓名1,20 -姓名2,20 -姓名3,20 -姓名4,20 -姓名5,20 -姓名6,20 -姓名7,20 -姓名8,20 -姓名9,20 \ No newline at end of file diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/cache/headt1.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/cache/headt1.xls deleted file mode 100644 index 4ff512e50..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/cache/headt1.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/cache/t2.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/cache/t2.xlsx deleted file mode 100644 index a2f2dbeee..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/cache/t2.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/comment/comment.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/comment/comment.xls deleted file mode 100644 index 5b54b24ce..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/comment/comment.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/comment/comment.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/comment/comment.xlsx deleted file mode 100644 index 9e3999b65..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/comment/comment.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t01.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t01.xls deleted file mode 100644 index eb0782f56..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t01.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t02.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t02.xlsx deleted file mode 100644 index b8d755de8..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t02.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t03.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t03.xlsx deleted file mode 100644 index 3a31ef78e..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t03.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t04.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t04.xlsx deleted file mode 100644 index 7c95d425c..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t04.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t05.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t05.xlsx deleted file mode 100644 index 248ec7d17..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t05.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t06.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t06.xlsx deleted file mode 100644 index b27be0279..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t06.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t07.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t07.xlsx deleted file mode 100644 index a7b0eac74..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t07.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t09.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t09.xlsx deleted file mode 100644 index 0b29141d2..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/compatibility/t09.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/converter/converter03.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/converter/converter03.xls deleted file mode 100644 index 89c2ab6ef..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/converter/converter03.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/converter/converter07.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/converter/converter07.xlsx deleted file mode 100644 index 99ace690b..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/converter/converter07.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/converter/converterCsv.csv b/fesod-examples/fesod-sheet-examples/src/test/resources/converter/converterCsv.csv deleted file mode 100644 index 01bcf2efc..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/resources/converter/converterCsv.csv +++ /dev/null @@ -1,2 +0,0 @@ -大数的布尔(不支持),大数的数字,大数的字符串,大整数的布尔(不支持),大整数的数字,大整数的字符串,布尔的布尔,布尔的数字(不支持),布尔的字符串,字节的布尔(不支持),字节的数字,字节的字符串,日期的数字,日期的字符串,本地日期的数字,本地日期的字符串,双精度浮点的布尔(不支持),双精度浮点的数字,双精度浮点的字符串,浮点的布尔(不支持),浮点的数字,浮点的字符串,整型的布尔(不支持),整型的数字,整型的字符串,长整型的布尔(不支持),长整型的数字,长整型的字符串,短整型的布尔(不支持),短整型的数字,短整型的字符串,字符串的布尔,字符串的数字,字符串的字符串,字符串的错误,字符串的数字公式,字符串的字符串公式,字符串的数字日期 -1,1,1,1,1,1,TRUE,TRUE,TRUE,1,1,1,2020-01-01 01:01:01,2020-01-01 01:01:01,2020-01-01 01:01:01,2020-01-01 01:01:01,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,TRUE,1,测试,#VALUE!,2,1测试,2020-01-01 01:01:01 \ No newline at end of file diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/csv/simple-delimiter.csv b/fesod-examples/fesod-sheet-examples/src/test/resources/csv/simple-delimiter.csv deleted file mode 100644 index bb74db80b..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/resources/csv/simple-delimiter.csv +++ /dev/null @@ -1,11 +0,0 @@ -字符串标题#日期标题#数字标题 -String0#2020-01-01 01:01:00#1 -String1#2020-01-02 01:01:00#2 -String2#2020-01-03 01:01:00#3 -String3#2020-01-04 01:01:00#4 -String4#2020-01-05 01:01:00#5 -String5#2020-01-06 01:01:00#6 -String6#2020-01-07 01:01:00#7 -String7#2020-01-08 01:01:00#8 -String8#2020-01-09 01:01:00#9 -String9#2020-01-10 01:01:00#10 \ No newline at end of file diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/csv/simple-quote.csv b/fesod-examples/fesod-sheet-examples/src/test/resources/csv/simple-quote.csv deleted file mode 100644 index 0af30b141..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/resources/csv/simple-quote.csv +++ /dev/null @@ -1,11 +0,0 @@ -"字符串标题","日期标题","数字标题" -"String0,""quote""","2020-01-01 01:01:00",1 -"String1","2020-01-02 01:01:00",2 -"String2","2020-01-03 01:01:00",3 -"String3","2020-01-04 01:01:00",4 -"String4","2020-01-05 01:01:00",5 -"String5","2020-01-06 01:01:00",6 -"String6","2020-01-07 01:01:00",7 -"String7","2020-01-08 01:01:00",8 -"String8","2020-01-09 01:01:00",9 -"String9","2020-01-10 01:01:00",10 \ No newline at end of file diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/csv/simple.csv b/fesod-examples/fesod-sheet-examples/src/test/resources/csv/simple.csv deleted file mode 100644 index 31bbc9161..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/resources/csv/simple.csv +++ /dev/null @@ -1,11 +0,0 @@ -字符串标题,日期标题,数字标题 -String0,2020-01-01 01:01:00,1 -String1,2020-01-02 01:01:00,2 -String2,2020-01-03 01:01:00,3 -String3,2020-01-04 01:01:00,4 -String4,2020-01-05 01:01:00,5 -String5,2020-01-06 01:01:00,6 -String6,2020-01-07 01:01:00,7 -String7,2020-01-08 01:01:00,8 -String8,2020-01-09 01:01:00,9 -String9,2020-01-10 01:01:00,10 \ No newline at end of file diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/dataformat/dataformat.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/dataformat/dataformat.xls deleted file mode 100644 index 95c306ce0..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/dataformat/dataformat.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/dataformat/dataformat.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/dataformat/dataformat.xlsx deleted file mode 100644 index 34a05cc92..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/dataformat/dataformat.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/dataformat/dataformatv2.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/dataformat/dataformatv2.xlsx deleted file mode 100644 index c49aa0440..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/dataformat/dataformatv2.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/datewindowing/1900DateWindowing.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/datewindowing/1900DateWindowing.xls deleted file mode 100644 index 625655242..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/datewindowing/1900DateWindowing.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/datewindowing/1904DateWindowing.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/datewindowing/1904DateWindowing.xls deleted file mode 100644 index 0abd3bfdc..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/datewindowing/1904DateWindowing.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/cellDataDemo.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/demo/cellDataDemo.xlsx deleted file mode 100644 index d2addac81..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/cellDataDemo.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/demo.csv b/fesod-examples/fesod-sheet-examples/src/test/resources/demo/demo.csv deleted file mode 100644 index 6aa112a2c..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/demo.csv +++ /dev/null @@ -1,11 +0,0 @@ -String,Date,Number -String0,2020-01-01 01:01:00,1 -String1,2020-01-02 01:01:00,2 -String2,2020-01-03 01:01:00,3 -String3,2020-01-04 01:01:00,4 -String4,2020-01-05 01:01:00,5 -String5,2020-01-06 01:01:00,6 -String6,2020-01-07 01:01:00,7 -String7,2020-01-08 01:01:00,8 -String8,2020-01-09 01:01:00,9 -String9,2020-01-10 01:01:00,10 \ No newline at end of file diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/demo.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/demo/demo.xlsx deleted file mode 100644 index 2924c353d..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/demo.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/extra.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/demo/extra.xlsx deleted file mode 100644 index cbae5fb57..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/extra.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/complex.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/complex.xlsx deleted file mode 100644 index 18e3894b4..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/complex.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/complexFillWithTable.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/complexFillWithTable.xlsx deleted file mode 100644 index bca5ac732..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/complexFillWithTable.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/composite.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/composite.xlsx deleted file mode 100644 index 55df81242..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/composite.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/dateFormat.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/dateFormat.xlsx deleted file mode 100644 index 956b09f15..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/dateFormat.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/horizontal.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/horizontal.xlsx deleted file mode 100644 index 89d341265..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/fill/horizontal.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/generic-demo.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/demo/generic-demo.xlsx deleted file mode 100644 index 9dde7d2d4..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/generic-demo.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/pwd_123.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/demo/pwd_123.xls deleted file mode 100644 index ff323a134..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/demo/pwd_123.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/extra/extra.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/extra/extra.xls deleted file mode 100644 index 89f389bed..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/extra/extra.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/extra/extra.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/extra/extra.xlsx deleted file mode 100644 index 4936b05a0..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/extra/extra.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/extra/extraRelationships.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/extra/extraRelationships.xlsx deleted file mode 100644 index 5784cd8b6..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/extra/extraRelationships.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/annotation.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/fill/annotation.xls deleted file mode 100644 index 46ad21b0d..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/annotation.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/annotation.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/fill/annotation.xlsx deleted file mode 100644 index ee4c2452a..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/annotation.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/byName.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/fill/byName.xls deleted file mode 100644 index e3e29165a..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/byName.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/byName.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/fill/byName.xlsx deleted file mode 100644 index 7b2d6fc72..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/byName.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/complex.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/fill/complex.xls deleted file mode 100644 index e2b695602..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/complex.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/complex.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/fill/complex.xlsx deleted file mode 100644 index 26f331927..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/complex.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/composite.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/fill/composite.xls deleted file mode 100644 index bf8597f05..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/composite.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/composite.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/fill/composite.xlsx deleted file mode 100644 index 0480dbb5c..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/composite.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/horizontal.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/fill/horizontal.xls deleted file mode 100644 index 3b2563539..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/horizontal.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/horizontal.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/fill/horizontal.xlsx deleted file mode 100644 index 959d52532..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/horizontal.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/simple.csv b/fesod-examples/fesod-sheet-examples/src/test/resources/fill/simple.csv deleted file mode 100644 index 0fce4f59c..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/simple.csv +++ /dev/null @@ -1,2 +0,0 @@ -Name,Number,Complex,Ignored,Empty -{name},{number},{name} is {number} years old this year,\{name\} ignored, {name},Empty{.empty} \ No newline at end of file diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/simple.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/fill/simple.xls deleted file mode 100644 index ae8526370..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/simple.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/simple.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/fill/simple.xlsx deleted file mode 100644 index a2b15b885..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/simple.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/style.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/fill/style.xls deleted file mode 100644 index 551d1087c..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/style.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/style.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/fill/style.xlsx deleted file mode 100644 index d98bde261..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/fill/style.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/hiddensheets/hiddensheets.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/hiddensheets/hiddensheets.xls deleted file mode 100644 index 6c52c76eb..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/hiddensheets/hiddensheets.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/hiddensheets/hiddensheets.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/hiddensheets/hiddensheets.xlsx deleted file mode 100644 index 6ed39209f..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/hiddensheets/hiddensheets.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/large/fill.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/large/fill.xlsx deleted file mode 100644 index c3c376d31..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/large/fill.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/large/large07.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/large/large07.xlsx deleted file mode 100644 index a317e71f9..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/large/large07.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/multiplesheets/multiplesheets.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/multiplesheets/multiplesheets.xls deleted file mode 100644 index a5601288c..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/multiplesheets/multiplesheets.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/multiplesheets/multiplesheets.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/multiplesheets/multiplesheets.xlsx deleted file mode 100644 index f90680a14..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/multiplesheets/multiplesheets.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/poi/last_row_number_test.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/poi/last_row_number_test.xlsx deleted file mode 100644 index 20d357b9a..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/poi/last_row_number_test.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/poi/last_row_number_xssf_date_test.csv b/fesod-examples/fesod-sheet-examples/src/test/resources/poi/last_row_number_xssf_date_test.csv deleted file mode 100644 index e9a033efa..000000000 --- a/fesod-examples/fesod-sheet-examples/src/test/resources/poi/last_row_number_xssf_date_test.csv +++ /dev/null @@ -1,10 +0,0 @@ -2025/3/25,2025/3/25,2025/3/25,2025/3/25,2025/3/25,2025/3/25,,,,testssdf是士大夫否t -2025/3/26,1909/2/15,1909/2/15,2025/3/26,2025/3/26,2025/3/26,,,, -2025/3/27,2025/3/27,2025/3/27,2025/3/27,2025/3/27,2025/3/27,,,, -2025/3/28,2025/3/28,2025/3/28,2025/3/28,2025/3/28,2025/3/28,,,, -2025/3/29,2025/3/29,2025/3/29,2025/3/29,2025/3/29,2025/3/29,,,, -2025/3/30,2025/3/30,2025/3/30,2025/3/30,2025/3/30,2025/3/30,,,, -2025/3/31,2025/3/31,2025/3/31,2025/3/31,2025/3/31,2025/3/31,,,, -2025/4/1,2025/4/1,2025/4/1,2025/4/1,2025/4/1,2025/4/1,,,, -2025/4/2,2025/4/2,2025/4/2,2025/4/2,2025/4/2,2025/4/2,,,, -2025/4/3,2025/4/3,2025/4/3,2025/4/3,2025/4/3,2025/4/3,,,, diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/poi/last_row_number_xssf_date_test.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/poi/last_row_number_xssf_date_test.xls deleted file mode 100644 index d078b708d..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/poi/last_row_number_xssf_date_test.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/poi/last_row_number_xssf_date_test.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/poi/last_row_number_xssf_date_test.xlsx deleted file mode 100644 index f849ebb1f..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/poi/last_row_number_xssf_date_test.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/poi/last_row_number_xssf_test.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/poi/last_row_number_xssf_test.xlsx deleted file mode 100644 index 356812976..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/poi/last_row_number_xssf_test.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/repeat/repeat.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/repeat/repeat.xls deleted file mode 100644 index 7072ab9a9..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/repeat/repeat.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/repeat/repeat.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/repeat/repeat.xlsx deleted file mode 100644 index 00c77d061..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/repeat/repeat.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/simple/LargeData.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/simple/LargeData.xlsx deleted file mode 100644 index 6baefb7f7..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/simple/LargeData.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/simple/no_model_10000_rows.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/simple/no_model_10000_rows.xlsx deleted file mode 100644 index aab11d6a3..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/simple/no_model_10000_rows.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/simple/simple07.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/simple/simple07.xlsx deleted file mode 100644 index 3d25fcd8c..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/simple/simple07.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/style/styleTest.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/style/styleTest.xls deleted file mode 100644 index 5cfffb6b5..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/style/styleTest.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/style/styleTest.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/style/styleTest.xlsx deleted file mode 100644 index 60c85b005..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/style/styleTest.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue1663/template.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue1663/template.xlsx deleted file mode 100644 index a968ff415..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue1663/template.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue220/test01.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue220/test01.xlsx deleted file mode 100644 index e1df77a21..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue220/test01.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue220/test02.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue220/test02.xlsx deleted file mode 100644 index 3a35a1be1..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue220/test02.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue220/test03.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue220/test03.xlsx deleted file mode 100644 index 357f3cc06..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue220/test03.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue2319/test1.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue2319/test1.xlsx deleted file mode 100644 index 6c6cc8d7c..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue2319/test1.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue2319/test2.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue2319/test2.xlsx deleted file mode 100644 index 96a99bd8a..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue2319/test2.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue2443/date1.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue2443/date1.xlsx deleted file mode 100644 index 92ef811d9..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue2443/date1.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue2443/date2.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue2443/date2.xlsx deleted file mode 100644 index c6feb3251..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/issue2443/date2.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/lock_data.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/temp/lock_data.xlsx deleted file mode 100644 index 65cf41e50..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/lock_data.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/number_format.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/temp/number_format.xlsx deleted file mode 100644 index c8758e1a8..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/temp/number_format.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/template/template03.xls b/fesod-examples/fesod-sheet-examples/src/test/resources/template/template03.xls deleted file mode 100644 index 7c17eee9e..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/template/template03.xls and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/template/template07.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/template/template07.xlsx deleted file mode 100644 index a046fbcba..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/template/template07.xlsx and /dev/null differ diff --git a/fesod-examples/fesod-sheet-examples/src/test/resources/web/io.xlsx b/fesod-examples/fesod-sheet-examples/src/test/resources/web/io.xlsx deleted file mode 100644 index f7f228efd..000000000 Binary files a/fesod-examples/fesod-sheet-examples/src/test/resources/web/io.xlsx and /dev/null differ diff --git a/fesod-examples/pom.xml b/fesod-examples/pom.xml index 22aea12bd..4a7fcca4c 100644 --- a/fesod-examples/pom.xml +++ b/fesod-examples/pom.xml @@ -32,6 +32,11 @@ pom Fesod Examples + + UTF-8 + true + true + fesod-sheet-examples diff --git a/fesod-sheet/src/test/resources/logback.xml b/fesod-sheet/src/test/resources/logback.xml index 6ef9578b8..c08e110fd 100644 --- a/fesod-sheet/src/test/resources/logback.xml +++ b/fesod-sheet/src/test/resources/logback.xml @@ -20,7 +20,7 @@ --> - + @@ -29,7 +29,7 @@ - + diff --git a/pom.xml b/pom.xml index bb53a1062..ef228f3a1 100644 --- a/pom.xml +++ b/pom.xml @@ -104,7 +104,8 @@ 1.7.36 1.7.36 1.7.36 - 1.5.32 + 2.24.3 + 1.2.13 5.15.0 0.8.14 5.13.4 @@ -213,11 +214,6 @@ fastjson2 ${fastjson2.version} - - org.slf4j - slf4j-simple - ${slf4j-simple.version} - org.slf4j jcl-over-slf4j @@ -228,6 +224,11 @@ log4j-over-slf4j ${log4j-over-slf4j.version} + + org.apache.logging.log4j + log4j-to-slf4j + ${log4j-to-slf4j.version} + ch.qos.logback logback-classic @@ -238,6 +239,12 @@ spring-boot-starter-web ${spring-boot-starter-web.version} + + org.springframework.boot + spring-boot-starter-test + ${spring-boot-starter-web.version} + test + org.mock-server mockserver-netty @@ -326,17 +333,17 @@ org.slf4j - slf4j-simple + jcl-over-slf4j test org.slf4j - jcl-over-slf4j + log4j-over-slf4j test - org.slf4j - log4j-over-slf4j + org.apache.logging.log4j + log4j-to-slf4j test