### beforePerPage Example for Logging Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ImportHandler.md An example implementation of the beforePerPage method that logs the start of batch processing, including the starting row and batch size. ```java @Override public void beforePerPage(ImportContext ctx, List list, DataImportParam param) throws Exception { log.info("Processing batch starting at row {}, size {}", list.get(0).getRow(), list.size()); } ``` -------------------------------- ### Implement Custom S3StorageService for File Storage Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/configuration.md Provides an example implementation of the IStorageService interface for storing and retrieving files from AWS S3. Requires Spring configuration and S3 client setup. ```java @Component public class S3StorageService implements IStorageService { @Autowired private AmazonS3 s3Client; @Value("${app.s3.bucket:excel-exports}") private String bucket; @Override public String write(String name, InputStream data) throws Exception { String key = "excel/" + System.currentTimeMillis() + "/" + name; s3Client.putObject(bucket, key, data, new ObjectMetadata()); return "s3://" + bucket + "/" + key; } @Override public String write(String name, Consumer osConsumer) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); osConsumer.accept(baos); return write(name, new ByteArrayInputStream(baos.toByteArray())); } @Override public InputStream read(String path) throws Exception { String key = path.replace("s3://" + bucket + "/", ""); return s3Client.getObject(bucket, key).getObjectContent(); } @Override public boolean delete(String path) throws Exception { String key = path.replace("s3://" + bucket + "/", ""); s3Client.deleteObject(bucket, key); return true; } } ``` -------------------------------- ### Example: Performing User Import Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ExcelService.md Example demonstrating how to initiate a user import using ExcelService. This involves setting up DataImportParam with file stream, model class, batch size, and tenant/user codes. ```java @Resource ExcelService excelService; @PostMapping("/imports") public Long importUsers(@RequestBody MultipartFile file) throws Exception { DataImportParam dataImportParam = new DataImportParam() .setStream(file.getInputStream()) .setModel(UserImportModel.class) .setBatchSize(500) .setFilename("user-batch-import") .setValidHead(true) .setTenantCode("tenant-001") .setCreateUserCode("user-001"); Long taskId = excelService.doImport(UserImportHandler.class, dataImportParam); return taskId; } ``` -------------------------------- ### UserExportHandler Implementation Example Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/DataExportParam.md An example implementation of an ExportHandler for user data. It demonstrates fetching paginated data using IUserService and transforming it into the ExportPage format. ```java @ExcelHandle public class UserExportHandler implements ExportHandler { @Autowired IUserService userService; @Override public ExportPage exportData(int startPage, int limit, DataExportParam param) { IPage iPage = new Page<>(startPage, limit); IPage result = userService.page(iPage); ExportPage exportPage = new ExportPage<>(); exportPage.setTotal(result.getTotal()); exportPage.setCurrent(result.getCurrent()); exportPage.setSize(result.getSize()); exportPage.setRecords(ExportListUtil.transform(result.getRecords(), UserExportModel.class)); return exportPage; } } ``` -------------------------------- ### Example Handler Class Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/EnableAsyncExcel.md An example of a class annotated with @ExcelHandle that implements ImportHandler for processing imported data. ```java package com.myapp.excel.handlers; import com.asyncexcel.core.annotation.ExcelHandle; import com.asyncexcel.core.importer.ImportHandler; import org.springframework.stereotype.Component; @ExcelHandle public class UserImportHandler implements ImportHandler { @Autowired private IUserService userService; @Override public List importData(List list, DataImportParam param) throws Exception { // Implementation } } ``` -------------------------------- ### Example: Performing User Export Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ExcelService.md Example demonstrating how to initiate a user export using ExcelService. This involves setting up DataExportParam with export file name, limit, head class, and tenant/business codes. ```java @PostMapping("/exports") public Long exportUsers() { DataExportParam dataExportParam = new DataExportParam() .setExportFileName("users-export") .setLimit(1000) .setHeadClass(UserExportModel.class) .setTenantCode("tenant-001") .setBusinessCode("user-module"); Long taskId = excelService.doExport(UserExportHandler.class, dataExportParam); return taskId; } ``` -------------------------------- ### beforePerPage Hook Example Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ExportHandler.md Example implementation of the beforePerPage lifecycle hook. This hook is invoked before each page is fetched and can be used for logging or validating export state. ```java @Override public void beforePerPage(ExportContext ctx, DataExportParam param) { int pageNum = ctx.getTask().getSuccessCount() / ctx.getLimit() + 1; log.info("Exporting page {}", pageNum); } ``` -------------------------------- ### Example: Performing Multi-Sheet Export Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ExcelService.md Example demonstrating how to initiate a multi-sheet export using ExcelService. This involves setting up shared export parameters and providing multiple handler classes for each sheet. ```java @PostMapping("/exports-multi") public Long exportMultiSheet() { DataExportParam param = new DataExportParam() .setExportFileName("company-report") .setLimit(500); Long taskId = excelService.doExport( param, UserExportHandler.class, ProductExportHandler.class, OrderExportHandler.class ); return taskId; } ``` -------------------------------- ### Multiple Packages Example Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/EnableAsyncExcel.md Demonstrates how to specify multiple packages for scanning @ExcelHandle classes using the basePackages attribute. ```java @EnableAsyncExcel(basePackages = { "com.acme.excel", "com.acme.import", "com.acme.export" }) ``` -------------------------------- ### EnableAsyncExcel Usage Example Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/types.md Example of how to use the @EnableAsyncExcel annotation in a Spring Boot application's main class to configure the async-excel component. ```java @SpringBootApplication @EnableAsyncExcel(basePackages = "com.myapp.excel") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` -------------------------------- ### afterPerPage Example for Logging and Auditing Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ImportHandler.md An example implementation of the afterPerPage method that logs the number of successful and failed rows and logs import batch details for successful rows. ```java @Override public void afterPerPage(ImportContext ctx, List list, DataImportParam param, List errorMsgList) throws Exception { int successCount = list.size() - errorMsgList.size(); log.info("Batch complete: {} success, {} failed", successCount, errorMsgList.size()); if (successCount > 0) { auditService.logImportBatch("user-import", successCount); } } ``` -------------------------------- ### Complete Spring Boot Application Example with Async Excel Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/EnableAsyncExcel.md Integrate @EnableAsyncExcel into your main application class and configure both the Excel-specific and application-specific data sources. ```java package com.acme; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.asyncexcel.springboot.EnableAsyncExcel; @SpringBootApplication @EnableAsyncExcel(basePackages = { "com.acme.excel.importers", "com.acme.excel.exporters" }) public class ExcelApplication { public static void main(String[] args) { SpringApplication.run(ExcelApplication.class, args); } } ``` ```properties # Excel database (separate from application database) spring.excel.datasource.url=jdbc:mysql://localhost:3306/async-excel spring.excel.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.excel.datasource.username=root spring.excel.datasource.password=root # Application database (for business logic) spring.datasource.url=jdbc:mysql://localhost:3306/app-db spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=app_user spring.datasource.password=app_password ``` -------------------------------- ### init Method Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ImportHandler.md Called once at the beginning of an import process, before any rows are read. It's used for setup tasks like initializing connections, validating configuration, or fetching necessary data. ```APIDOC ## init Method ### Description Called once at import start, before any rows are read. Used for initialization tasks. ### Signature ```java default void init(ExcelContext ctx, DataParam param) ``` ### Parameters #### Path Parameters - **ctx** (ExcelContext) - Cast to ImportContext for import-specific fields. - **param** (DataParam) - Cast to DataImportParam to access stream, model, batchSize, etc. ### Use cases: - Initialize connections, thread-local state, or caches - Validate handler configuration - Fetch reference data needed for all batches ### Example: ```java @Override public void init(ExcelContext ctx, DataParam param) { ImportContext importCtx = (ImportContext) ctx; DataImportParam importParam = (DataImportParam) param; log.info("Starting import: {}, model: {}, batchSize: {}", importParam.getFilename(), importParam.getModel().getSimpleName(), importParam.getBatchSize()); } ``` ``` -------------------------------- ### UserExportHandler Implementation Example Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ExportHandler.md Example implementation of ExportHandler for exporting user data. It fetches user records page by page using an IUserService and transforms them into UserExportModel. ```java @ExcelHandle public class UserExportHandler implements ExportHandler { @Autowired IUserService userService; @Override public ExportPage exportData(int startPage, int limit, DataExportParam param) { String tenantCode = param.getTenantCode(); IPage iPage = new Page<>(startPage, limit); IPage result = userService.page(iPage, new QueryWrapper().eq("tenant_code", tenantCode)); ExportPage exportPage = new ExportPage<>(); exportPage.setTotal(result.getTotal()); exportPage.setCurrent(result.getCurrent()); exportPage.setSize(result.getSize()); exportPage.setRecords(ExportListUtil.transform(result.getRecords(), UserExportModel.class)); return exportPage; } } ``` -------------------------------- ### ExcelHandle Usage Examples Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/types.md Examples demonstrating the usage of the @ExcelHandle annotation for both import and export handlers, including specifying a custom bean name. ```java @ExcelHandle public class UserImportHandler implements ImportHandler { } @ExcelHandle(name = "customName") public class UserExportHandler implements ExportHandler { } ``` -------------------------------- ### User Import Handler Example Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ImportHandler.md An example implementation of the importData method for handling user imports. It validates mobile numbers and checks for existing user codes, returning specific error messages for invalid rows. ```java @ExcelHandle public class UserImportHandler implements ImportHandler { @Autowired IUserService userService; @Override public List importData(List list, DataImportParam param) throws Exception { List errorList = new ArrayList<>(); List validUsers = new ArrayList<>(); for (UserImportModel importModel : list) { if (importModel.getMobile().contains("00000000")) { errorList.add(new ErrorMsg(importModel.getRow(), "手机号包含太多0")); } else if (userService.existsByUserCode(importModel.getUserCode())) { errorList.add(new ErrorMsg(importModel.getRow(), "用户编码已存在")); } else { User user = new User(); BeanUtils.copyProperties(importModel, user); validUsers.add(user); } } userService.saveBatch(validUsers); return errorList; } } ``` -------------------------------- ### Async Framework Exception Log Example Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/errors.md Illustrates the default ERROR level logging format for exceptions encountered by the async framework, including the exception type and message. ```log ERROR com.asyncexcel.core.importer.AsyncExcelImporter - 导入发生异常 java.lang.ImportException: 表头校验失败... at com.asyncexcel.core.importer.AsyncPageReadListener.invokeHead(...) ... ``` -------------------------------- ### User Import Handler Implementation Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/INDEX.md Example of a custom import handler for User data. It demonstrates initializing the handler, processing batches of rows, validating phone numbers, saving valid users, and logging import progress and completion. ```java @ExcelHandle public class UserImportHandler implements ImportHandler { @Autowired private IUserService userService; @Override public void init(ExcelContext ctx, DataParam param) { DataImportParam importParam = (DataImportParam) param; log.info("Starting import: {}", importParam.getFilename()); } @Override public void beforePerPage(ImportContext ctx, List list, DataImportParam param) { log.info("Processing batch of {} rows", list.size()); } @Override public List importData(List list, DataImportParam param) throws Exception { List errors = new ArrayList<>(); List validUsers = new ArrayList<>(); for (UserImportModel row : list) { if (!isValidPhone(row.getMobile())) { errors.add(new ErrorMsg(row.getRow(), "Invalid phone number")); } else { User user = new User(); BeanUtils.copyProperties(row, user); user.setTenantCode(param.getTenantCode()); validUsers.add(user); } } if (!validUsers.isEmpty()) { userService.saveBatch(validUsers); } return errors; } @Override public void afterPerPage(ImportContext ctx, List list, DataImportParam param, List errorMsgList) throws Exception { int successCount = list.size() - errorMsgList.size(); log.info("Batch complete: {} success, {} failed", successCount, errorMsgList.size()); } @Override public void callBack(ExcelContext ctx, DataParam param) { log.info("Import finished. Total: {}, Success: {}, Failed: {}", ctx.getTotalCount(), ctx.getSuccessCount(), ctx.getFailCount()); } private boolean isValidPhone(String phone) { return phone != null && phone.matches("\\d{10,11}"); } } ``` -------------------------------- ### afterPerPage Hook Example Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ExportHandler.md Example implementation of the afterPerPage lifecycle hook. This hook is invoked after each page is exported and can be used for logging page completion or releasing resources. ```java @Override public void afterPerPage(List list, ExportContext ctx, DataExportParam param) { log.info("Exported {} rows, total progress: {}/{}", list.size(), ctx.getSuccessCount(), ctx.getTask().getEstimateCount()); } ``` -------------------------------- ### Initialize Import Handler Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ImportHandler.md Called once at the start of an import process. Use to initialize connections, validate configuration, or fetch reference data. ```java default void init(ExcelContext ctx, DataParam param) ``` ```java @Override public void init(ExcelContext ctx, DataParam param) { ImportContext importCtx = (ImportContext) ctx; DataImportParam importParam = (DataImportParam) param; log.info("Starting import: {}, model: {}, batchSize: {}", importParam.getFilename(), importParam.getModel().getSimpleName(), importParam.getBatchSize()); } ``` -------------------------------- ### UserImportModel Example Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/errors.md Defines a sample UserImportModel class with @ExcelProperty annotations for header mapping. This is used to illustrate the conditions that trigger HeadCheckException. ```java @Data public class UserImportModel extends ImportRow { @ExcelProperty("用户编码") // Expects column 1 private String userCode; @ExcelProperty("用户姓名") // Expects column 2 private String userName; } ``` -------------------------------- ### UserImportModel Example Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/types.md An example of a custom import DTO that extends the base ImportRow class. It defines specific fields for user data with Excel property annotations. ```java @Data public class UserImportModel extends ImportRow { @ExcelProperty("用户编码") private String userCode; @ExcelProperty("用户姓名") private String userName; } ``` -------------------------------- ### Custom MyBatis-Plus Configuration Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/configuration.md Example of a custom MyBatis-Plus configuration class. This allows overriding default settings, such as the logging implementation, for the async-excel module. ```java @Configuration public class CustomExcelMybatisPlusConfiguration { @Bean public ConfigurationCustomizer configurationCustomizer() { return configuration -> { // Customize global MyBatis-Plus settings configuration.setLogImpl(Slf4jImpl.class); }; } } ``` -------------------------------- ### ExportHandler init Method Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ExportHandler.md The init method is called once at the start of an export, before any pages are fetched. It's used to set up the export context, configure sheet properties, open file writers, and initialize caches or connections. The method accepts an ExcelContext and DataParam, which can be cast to ExportContext and DataExportParam respectively for specific configurations. ```APIDOC ## init Method ### Description Called once at export start, before any pages are fetched. Used to set up the export context, configure sheet properties, open file writers, and initialize caches or connections. ### Signature ```java default void init(ExcelContext ctx, DataParam param) ``` ### Parameters #### Path Parameters - **ctx** (ExcelContext) - Required - Cast to ExportContext to configure WriteSheet, file output, etc. - **param** (DataParam) - Required - Cast to DataExportParam to read limit, fileName, headClass ### Responsibilities - Set up WriteSheet with headers and styles - Open file writers - Initialize caches or connections - Validate configuration ### Example ```java @Override public void init(ExcelContext ctx, DataParam param) { ExportContext exportCtx = (ExportContext) ctx; DataExportParam exportParam = (DataExportParam) param; WriteSheet writeSheet = EasyExcel .writerSheet("用户列表") .head(UserExportModel.class) .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) .build(); exportCtx.setWriteSheet(writeSheet); log.info("Initialized export: {}, page size: {}", exportParam.getExportFileName(), exportParam.getLimit()); } ``` ``` -------------------------------- ### Database Connection Pool Configuration Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/configuration.md Example properties for configuring the HikariCP connection pool for the async-excel datasource. This includes settings for maximum and minimum idle connections, and connection timeout. ```properties # HikariCP defaults for asyncexcel datasource spring.excel.datasource.hikari.maximum-pool-size=20 spring.excel.datasource.hikari.minimum-idle=5 spring.excel.datasource.hikari.connection-timeout=30000 ``` -------------------------------- ### Controller Using ExcelService for Import and Export Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/EnableAsyncExcel.md Implement a REST controller to interact with the ExcelService for performing asynchronous data imports and exports. This example shows how to trigger import and export operations via API endpoints. ```java @RestController @RequestMapping("/excel") public class ExcelController { @Autowired private ExcelService excelService; @PostMapping("/import") public Long importUsers(@RequestBody MultipartFile file) throws Exception { DataImportParam param = new DataImportParam() .setStream(file.getInputStream()) .setModel(UserImportModel.class) .setFilename("user-import"); return excelService.doImport(UserImportHandler.class, param); } @PostMapping("/export") public Long exportUsers() { DataExportParam param = new DataExportParam() .setExportFileName("users-export") .setLimit(1000); return excelService.doExport(UserExportHandler.class, param); } } ``` -------------------------------- ### doImport Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ExcelService.md Initiates an asynchronous import from an Excel file. This method takes a handler class and import parameters to start the import process. It returns a task ID for tracking. ```APIDOC ## doImport ### Description Initiates asynchronous import from an Excel file. This method is used to start an Excel import process, returning a task ID for monitoring. ### Method Signature `public Long doImport(Class cls, DataImportParam param)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **cls** (Class) - Required - Handler class implementing import logic, must be annotated with @ExcelHandle. - **param** (DataImportParam) - Required - Import parameters including stream, model class, batch size, and validation options. ### Request Example ```java @Resource ExcelService excelService; @PostMapping("/imports") public Long importUsers(@RequestBody MultipartFile file) throws Exception { DataImportParam dataImportParam = new DataImportParam() .setStream(file.getInputStream()) .setModel(UserImportModel.class) .setBatchSize(500) .setFilename("user-batch-import") .setValidHead(true) .setTenantCode("tenant-001") .setCreateUserCode("user-001"); Long taskId = excelService.doImport(UserImportHandler.class, dataImportParam); return taskId; } ``` ### Response #### Success Response (200) - **taskId** (Long) - Task ID for progress tracking and status queries. #### Response Example ```json { "taskId": 1234567890 } ``` ``` -------------------------------- ### Setting Tenant and User Codes (Java) Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ExcelTask.md Demonstrates how to set tenant, user, and business codes on a DataImportParam object for multi-tenancy and filtering purposes. ```java // Set by client at import time DataImportParam param = new DataImportParam() .setTenantCode("acme-corp") .setCreateUserCode("user@acme.com") .setBusinessCode("sales-team"); // Later, filter queries to this tenant and user ExcelTask filter = new ExcelTask(); filter.setTenantCode("acme-corp"); filter.setCreateUserCode("user@acme.com"); IPage result = excelService.listPage(filter, 1, 10); ``` -------------------------------- ### Initialize Export Handler Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ExportHandler.md Implement the init method to set up the Excel sheet, file writers, and validate configurations before data fetching begins. Cast context and parameters to specific types for access to export-specific features. ```java default void init(ExcelContext ctx, DataParam param) ``` ```java @Override public void init(ExcelContext ctx, DataParam param) { ExportContext exportCtx = (ExportContext) ctx; DataExportParam exportParam = (DataExportParam) param; WriteSheet writeSheet = EasyExcel .writerSheet("用户列表") .head(UserExportModel.class) .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) .build(); exportCtx.setWriteSheet(writeSheet); log.info("Initialized export: {}, page size: ?", exportParam.getExportFileName(), exportParam.getLimit()); } ``` -------------------------------- ### Configure Basic DataImportParam Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/configuration.md Set up the essential parameters for importing data, including the input stream, model class, and optional filename and batch size. ```java DataImportParam param = new DataImportParam() .setStream(inputStream) // Required: Excel file input stream .setModel(UserImportModel.class) // Required: Row model class .setFilename("user-batch-01") // Optional: display name .setBatchSize(1000); // Default: 1000 ``` -------------------------------- ### Get Task Status Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/INDEX.md Retrieve the status and details of an Excel import or export task using its task ID. ```APIDOC ## GET /api/excel/tasks/{taskId} ### Description Retrieve the status and details of a specific Excel task using its ID. ### Method GET ### Endpoint /api/excel/tasks/{taskId} ### Parameters #### Path Parameters - **taskId** (long) - Required - The ID of the Excel task. ### Response #### Success Response (200) - **data** (ExcelTask) - An object containing the details of the Excel task. - **id** (long) - Task ID. - **fileUrl** (string) - URL to the exported file (if applicable). - **fileName** (string) - Name of the exported file (if applicable). - **failedFileUrl** (string) - URL to the file containing errors (if applicable). #### Response Example ```json { "code": 200, "message": "Success", "data": { "id": 12345, "fileUrl": "/path/to/export.xlsx", "fileName": "users-export.xlsx", "failedFileUrl": null } } ``` #### Error Response (404) - **message** (string) - "Task not found" ``` -------------------------------- ### Logback Configuration for Async-Excel Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/configuration.md Configures logging levels for the async-excel library in `logback.xml`. Sets general INFO level for the core package and DEBUG for specific importer classes. ```xml ``` -------------------------------- ### ISheetIndex Interface Definition Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/types.md Interface for sheet tracking, providing default implementations for setting and getting the sheet index. ```java public interface ISheetIndex { default void setSheetIndex(int sheetIndex) { } default int getSheetIndex() { return 0; } } ``` -------------------------------- ### Basic Excel Import Configuration Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/DataImportParam.md Configure a basic Excel import with stream, model, batch size, and filename. Use this for standard import tasks. ```java DataImportParam param = new DataImportParam() .setStream(inputStream) .setModel(UserImportModel.class) .setBatchSize(500) .setFilename("user-data-batch-1"); Long taskId = excelService.doImport(UserImportHandler.class, param); ``` -------------------------------- ### ISheetRow Interface Definition Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/types.md Interface for row tracking, requiring implementation of methods to set and get the row number. It extends ISheetIndex. ```java public interface ISheetRow extends ISheetIndex { void setRow(int row); int getRow(); } ``` -------------------------------- ### Multi-Tenant Excel Import with Context Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/DataImportParam.md Configure an import for a specific tenant, user, and business context. Useful for isolating data and permissions in multi-tenant applications. ```java DataImportParam param = new DataImportParam() .setStream(inputStream) .setModel(UserImportModel.class) .setTenantCode("tenant-001") .setCreateUserCode("user-123") .setBusinessCode("user-management") .setBatchSize(1000) .setFilename("tenant-001-users"); Long taskId = excelService.doImport(UserImportHandler.class, param); ``` -------------------------------- ### Alibaba OSS Storage Service Implementation Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/IStorageService.md Provides an IStorageService implementation for Alibaba Cloud Object Storage Service (OSS). This class is designed for handling Excel files in an OSS bucket, including functionalities for writing, reading, and deleting objects. ```java @Component public class OssStorageService implements IStorageService { @Autowired private OSS ossClient; @Value("${app.oss.bucket}") private String bucket; @Override public String write(String name, InputStream data) throws Exception { String key = "excel/" + UUID.randomUUID().toString() + "/" + name; ossClient.putObject(bucket, key, data); return "oss://" + bucket + "/" + key; } @Override public String write(String name, Consumer osConsumer) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); osConsumer.accept(baos); return write(name, new ByteArrayInputStream(baos.toByteArray())); } @Override public InputStream read(String path) throws Exception { String key = extractKeyFromPath(path); InputStream stream = ossClient.getObject(bucket, key); return stream; } @Override public boolean delete(String path) throws Exception { String key = extractKeyFromPath(path); try { ossClient.deleteObject(bucket, key); return true; } catch (OSSException e) { if (e.getErrorCode().equals("NoSuchKey")) { return false; } throw e; } } private String extractKeyFromPath(String path) { return path.replace("oss://" + bucket + "/", ""); } } ``` -------------------------------- ### Set Custom Filters for DataExportParam Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/configuration.md Add custom filter parameters to DataExportParam, such as status, start date, and end date, to be used by the handler for querying data. ```java Map filters = new HashMap<>(); filters.put("status", "active"); filters.put("startDate", "2024-01-01"); filters.put("endDate", "2024-12-31"); param.setParameters(filters); ``` -------------------------------- ### Configure Basic DataExportParam Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/configuration.md Set up the export filename and limit (page size) for data export operations. ```java DataExportParam param = new DataExportParam() .setExportFileName("users-report") // Optional: file name .setLimit(1000); // Default: 1000 (page size) ``` -------------------------------- ### Batch Size Tuning Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ImportHandler.md Guidance on tuning the `batchSize` parameter in `DataImportParam` to optimize import performance based on memory constraints and transaction overhead. ```APIDOC ## Batch Size Tuning ### Description The `batchSize` in `DataImportParam` controls how often `importData()` is called. Choosing an appropriate `batchSize` is crucial for balancing memory usage and transaction overhead. ### Recommendations: - **Small batches (100–500):** More frequent handler invocations; lower memory usage per batch; higher transaction overhead. - **Large batches (1000–5000):** Fewer handler invocations; higher memory usage per batch; lower transaction overhead. - **Very large (>10000):** Risk of `OutOfMemoryError`; suitable only for high-memory environments. **Note:** Choose `batchSize` based on the size of your row objects and available heap memory. ``` -------------------------------- ### Export with Multi-Tenant Context Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/DataExportParam.md Shows how to configure DataExportParam for multi-tenant exports by setting tenant code, user code, and business code. Also sets the export file name and page limit. ```java DataExportParam param = new DataExportParam() .setExportFileName("tenant-001-users") .setLimit(500) .setTenantCode("tenant-001") .setCreateUserCode("user-123") .setBusinessCode("user-management"); Long taskId = excelService.doExport(UserExportHandler.class, param); ``` -------------------------------- ### Handler Uses Custom Filters for DataExportParam Querying Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/configuration.md Demonstrates how a handler retrieves custom filter parameters like status, start date, and end date from DataExportParam to perform data querying. ```java @Override public ExportPage exportData(int startPage, int limit, DataExportParam param) { String status = (String) param.getParameters().get("status"); LocalDate startDate = LocalDate.parse((String) param.getParameters().get("startDate")); IPage result = userService.page(new Page<>(startPage, limit), new QueryWrapper() .eq("status", status) .between("created_at", startDate, endDate)); // Convert and return... } ``` -------------------------------- ### Configuration Class Usage Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/EnableAsyncExcel.md Shows how to place the @EnableAsyncExcel annotation on a separate configuration class instead of the main application class. ```java @Configuration @EnableAsyncExcel(basePackages = "com.myapp.excel") public class ExcelConfiguration { // Additional Excel-specific configuration } @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` -------------------------------- ### doExport (single sheet) Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ExcelService.md Initiates an asynchronous export to a single-sheet Excel file. This method takes a handler class and export parameters to start the export process. It returns a task ID for tracking. ```APIDOC ## doExport (single sheet) ### Description Initiates asynchronous export to an Excel file with a single sheet. This method is used to start an Excel export process, returning a task ID for monitoring. ### Method Signature `public Long doExport(Class cls, DataExportParam param)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **cls** (Class) - Required - Handler class implementing export logic, must be annotated with @ExcelHandle. - **param** (DataExportParam) - Required - Export parameters including page limit, file name, and head class. ### Request Example ```java @PostMapping("/exports") public Long exportUsers() { DataExportParam dataExportParam = new DataExportParam() .setExportFileName("users-export") .setLimit(1000) .setHeadClass(UserExportModel.class) .setTenantCode("tenant-001") .setBusinessCode("user-module"); Long taskId = excelService.doExport(UserExportHandler.class, dataExportParam); return taskId; } ``` ### Response #### Success Response (200) - **taskId** (Long) - Task ID for progress tracking and status queries. #### Response Example ```json { "taskId": 1234567890 } ``` ``` -------------------------------- ### Configure Excel Database Properties Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/EnableAsyncExcel.md Set up the database connection properties for asynchronous Excel processing. Ensure these properties are distinct from your application's main database. ```properties spring.excel.datasource.url=jdbc:mysql://localhost:3306/async-excel spring.excel.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.excel.datasource.username=root spring.excel.datasource.password=root ``` -------------------------------- ### Progress Tracking Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ImportHandler.md Information on how to track the progress of an asynchronous import using the `ExcelContext` and its associated task information. ```APIDOC ## Progress Tracking ### Description Import progress can be accessed via `ctx.getTask()`, which provides details like the total processed count and the estimated total count. ### Accessing Progress ```java @Override public void afterPerPage(ImportContext ctx, List list, DataImportParam param, List errorMsgList) throws Exception { Long processed = ctx.getTotalCount(); Long estimated = ctx.getTask().getEstimateCount(); log.info("Progress: {}/{}", processed, estimated); } ``` **Note:** Progress is also automatically tracked by `ExcelContext.record()` called after each batch. ``` -------------------------------- ### Export with Custom Parameters Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/DataExportParam.md Demonstrates setting custom parameters for an export operation using a Map. This allows passing additional filtering or context information to the export handler. Sets the export file name and page limit. ```java Map filters = new HashMap<>(); filters.put("status", "active"); filters.put("startDate", "2024-01-01"); DataExportParam param = new DataExportParam() .setExportFileName("active-users-2024") .setLimit(1000) .setParameters(filters); Long taskId = excelService.doExport(UserExportHandler.class, param); ``` -------------------------------- ### User Import Model with Excel Headers Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/DataImportParam.md Defines a model for user data import, mapping Excel column headers to class fields using @ExcelProperty annotations. Ensures header order matches the model. ```java @Data public class UserImportModel extends ImportRow { @ExcelProperty("用户编码") // Column 1 private String userCode; @ExcelProperty("用户姓名") // Column 2 private String userName; } ``` -------------------------------- ### Initiate Asynchronous Excel Import Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ExcelService.md Initiates an asynchronous import from an Excel file. Use this method when you need to process data from an Excel file in the background. Requires a handler class and import parameters. ```java public Long doImport(Class cls, DataImportParam param) ``` -------------------------------- ### Minimal Configuration Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/EnableAsyncExcel.md Place the @EnableAsyncExcel annotation on the main Spring Boot application class to enable async-excel functionality and scan the entire application package for @ExcelHandle classes. ```java @SpringBootApplication @EnableAsyncExcel public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` -------------------------------- ### Modern Excel Export Handler Pattern Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/DataExportParam.md Demonstrates the modern pattern for implementing an ExportHandler, including setting up the WriteSheet with a custom name, head, and style strategy. Use this pattern for new Excel export implementations. ```java import com.alibaba.excel.EasyExcel; import com.alibaba.excel.ExcelWriter; import com.alibaba.excel.write.builder.ExcelWriterBuilder; import com.alibaba.excel.write.handler.WriteHandler; import com.alibaba.excel.write.metadata.WriteSheet; import com.alibaba.excel.write.style.LongestMatchColumnWidthStyleStrategy; import java.io.OutputStream; import java.util.List; // Assuming these interfaces/classes exist for context interface ExcelContext {} interface DataParam {} interface ExportHandler { void init(ExcelContext ctx, DataParam param); ExportPage exportData(int startPage, int limit, DataExportParam param); default void beforePerPage(ExportContext exportCtx) {} default void afterPerPage(ExportContext exportCtx) {} } interface ExportPage { List getRecords(); boolean hasNextPage(); } class ExportContext implements ExcelContext { private WriteSheet writeSheet; public void setWriteSheet(WriteSheet writeSheet) { this.writeSheet = writeSheet; } public WriteSheet getWriteSheet() { return writeSheet; } } class DataExportParam { private String exportFileName; private Integer limit; private String tenantCode; private String businessCode; // getters and setters public String getExportFileName() { return exportFileName; } public Integer getLimit() { return limit; } public String getTenantCode() { return tenantCode; } public String getBusinessCode() { return businessCode; } } class UserExportModel {} @ExcelHandle public class UserExportHandler implements ExportHandler { private WriteSheet writeSheet; @Override public void init(ExcelContext ctx, DataParam param) { writeSheet = EasyExcel .writerSheet("用户列表") .head(UserExportModel.class) .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()) .build(); ExportContext exportCtx = (ExportContext) ctx; exportCtx.setWriteSheet(writeSheet); } @Override public ExportPage exportData(int startPage, int limit, DataExportParam param) { // fetch and return data return null; // Placeholder } } // Dummy annotation and class for compilation @interface ExcelHandle {} class EasyExcel { public static ExcelWriterBuilder writerSheet(String sheetName) { return new ExcelWriterBuilder(); } } class ExcelWriterBuilder { public ExcelWriterBuilder head(Class head) { return this; } public ExcelWriterBuilder registerWriteHandler(WriteHandler handler) { return this; } public WriteSheet build() { return new WriteSheet(); } } ``` -------------------------------- ### MySQL Data Source Configuration for Async-Excel Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/configuration.md Configure the JDBC URL, driver class, username, and password for the async-excel task database. This ensures Excel operations use a dedicated data source. ```properties # Async-Excel task database spring.excel.datasource.url=jdbc:mysql://localhost:3306/async-excel?serverTimezone=GMT%2B8&autoReconnect=true&allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false spring.excel.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.excel.datasource.username=root spring.excel.datasource.password=root # Application data source (separate) spring.datasource.url=jdbc:mysql://localhost:3306/app-database?... spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=app_user spring.datasource.password=app_password ``` -------------------------------- ### beforePerPage Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ExportHandler.md Lifecycle hook invoked before each page is fetched. Implementations can pre-fetch data, validate state, or update context. ```APIDOC ## beforePerPage (default) ### Description Lifecycle hook invoked before each page is fetched. Implementations can pre-fetch data, validate state, or update context. ### Method `beforePerPage(ExportContext ctx, DataExportParam param)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **ctx** (ExportContext) - Required - Current export context; read/write limit, headClass, WriteSheet, fileName - **param** (DataExportParam) - Required - Original export parameters ### Throws Exception - Any checked exception stops the export ``` -------------------------------- ### ImportSupport Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/types.md Provides support for import operations, including task creation and lifecycle callbacks during the import process. ```APIDOC ## ImportSupport ### Description Provides support for import operations, including task creation and lifecycle callbacks during the import process. ### Methods - `ExcelTask createTask(DataImportParam param)`: Creates a new Excel import task. - `void beforeImport()`: Callback executed before the import process begins. - `void onImport(ImportContext ctx)`: Callback executed during the import process. - `void onWrite(Collection dataList, ImportContext ctx, List errorMsgList)`: Callback executed when data is being written during import. - `void onError(ImportContext ctx)`: Callback executed if an error occurs during import. - `void onComplete(ImportContext ctx)`: Callback executed upon completion of the import process. ### Package `com.asyncexcel.core.importer` ``` -------------------------------- ### Basic Single-Sheet Export Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/DataExportParam.md Demonstrates a basic single-sheet export configuration using DataExportParam. Sets the export file name, page limit, and header class. ```java DataExportParam param = new DataExportParam() .setExportFileName("users-export") .setLimit(500) .setHeadClass(UserExportModel.class); Long taskId = excelService.doExport(UserExportHandler.class, param); ``` -------------------------------- ### Excel Import with Custom Context Data Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/DataImportParam.md Configure an import with custom key-value context data. This data can be accessed by the handler during processing. ```java Map contextData = new HashMap<>(); contextData.put("department", "sales"); contextData.put("region", "NA"); DataImportParam param = new DataImportParam() .setStream(inputStream) .setModel(UserImportModel.class) .setParameters(contextData) .setFilename("sales-team-users"); Long taskId = excelService.doImport(UserImportHandler.class, param); ``` -------------------------------- ### Batch Record Update (Java) Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ExcelTask.md Shows how to record batch processing results, updating success and failure counts based on the batch size and the number of errors encountered. ```java ctx.record(batch.size(), errorList.size()); // Internally: successCount += batch.size() - errorList.size(); failedCount += errorList.size() ``` -------------------------------- ### Default ServerLocalStorageService Implementation Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/IStorageService.md The default implementation for storing files locally in the /tmp/upload directory. It provides basic write, read, and delete operations for local file system storage. ```java @Component public class ServerLocalStorageService implements IStorageService { @Override public String write(String name, Consumer osConsumer) throws Exception { // Creates file in /tmp/upload/{taskId}/{name} // Returns file path } @Override public String write(String name, InputStream data) throws Exception { // Copies InputStream to /tmp/upload/{taskId}/{name} // Returns file path } @Override public InputStream read(String path) throws Exception { // Reads from file path } @Override public boolean delete(String path) throws Exception { // Deletes file at path } } ``` -------------------------------- ### Multi-Tenancy and Isolation Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ImportHandler.md Demonstrates how to access and utilize multi-tenancy and isolation context information provided through `DataImportParam` for tenant-specific data processing. ```APIDOC ## Multi-Tenancy and Isolation ### Description Access isolation context information, such as tenant code, user ID, and business module, via `DataImportParam` to ensure data is processed correctly within its specific context. ### Example Usage ```java @Override public List importData(List list, DataImportParam param) { String tenantCode = param.getTenantCode(); String userId = param.getCreateUserCode(); String businessModule = param.getBusinessCode(); // Filter or route data by tenant List usersForThisTenant = list.stream() .map(this::convertToEntity) .peek(u -> u.setTenantCode(tenantCode)) .collect(Collectors.toList()); userService.saveBatch(usersForThisTenant); return List.of(); } ``` ``` -------------------------------- ### Track Export Progress with afterPerPage Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/api-reference/ExportHandler.md Implement the afterPerPage method to monitor export progress. Access success and estimated counts from ExportContext to calculate and log the progress percentage. This method is called after each page is processed. ```java @Override public void afterPerPage(List list, ExportContext ctx, DataExportParam param) { Long exported = ctx.getSuccessCount(); Long estimated = ctx.getTask().getEstimateCount(); double progress = (double) exported / estimated * 100; log.info("Export progress: {:.1f}%", progress); } ``` -------------------------------- ### Configure DataImportParam Permission/Isolation Options Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/configuration.md Set tenant code, user code, and business code for permission and isolation control during data import. ```java param.setTenantCode("acme-corp"); param.setCreateUserCode("user@acme.com"); param.setBusinessCode("sales-team"); ``` -------------------------------- ### ImportSupport Interface Source: https://github.com/2229499815/async-excel/blob/master/_autodocs/types.md Provides framework support for import operations, defining lifecycle methods for task creation, import process, writing, error handling, and completion. ```java public interface ImportSupport extends Support { ExcelTask createTask(DataImportParam param); void beforeImport(); void onImport(ImportContext ctx); void onWrite(Collection dataList, ImportContext ctx, List errorMsgList); void onError(ImportContext ctx); void onComplete(ImportContext ctx); } ```