### Custom Cell Write Converter Source: https://github.com/wuwenze/excelkit/blob/master/README.md Implement WriteConverter to transform cell values when writing to Excel. This example appends a string to the converted value. ```java public class CustomizeFieldWriteConverter implements WriteConverter { /** * 写文件时,将值进行转换(此处示例为将数值拼接为指定格式的字符串) */ @Override public String convert(Object o) throws ExcelKitWriteConverterException { return (o + "_convertedValue"); } } ``` -------------------------------- ### Custom Cell Read Converter Source: https://github.com/wuwenze/excelkit/blob/master/README.md Implement ReadConverter to transform cell values when reading from Excel. This example calculates the sum of character integer values in a string. ```java public class CustomizeFieldReadConverter implements ReadConverter { /** * 读取单元格时,将值进行转换(此处示例为计算单元格字符串char的总和) */ @Override public Object convert(Object o) throws ExcelKitReadConverterException { String value = (String) o; int convertedValue = 0; for (char c : value.toCharArray()) { convertedValue += Integer.valueOf(c); } return convertedValue; } } ``` -------------------------------- ### Custom Dropdown Data Source with Options Interface Source: https://github.com/wuwenze/excelkit/blob/master/README.md Implement the Options interface to define custom data sources for dropdown lists in Excel import templates. ```java public class UserGroupNameOptions implements Options { @Override public String[] get() { return new String[]{"管理组", "普通会员组", "游客"}; } } ``` -------------------------------- ### Build Excel Import Template with One Line of Code Source: https://github.com/wuwenze/excelkit/blob/master/README.md Use the ExcelKit API to generate an import template. This will create comments and dropdowns based on the configuration. ```java import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletResponse; import java.util.List; // Assuming User class and DbUtil are defined elsewhere // import com.yourpackage.User; // import com.yourpackage.DbUtil; @RequestMapping(value = "/downTemplate", method = RequestMethod.GET) public void downTemplate(HttpServletResponse response) { List userList = DbUtil.getUserList(3); ExcelKit.$Export(User.class, response).downXlsx(userList, true); } ``` -------------------------------- ### Execute Excel Batch Export with One Line of Code Source: https://github.com/wuwenze/excelkit/blob/master/README.md Utilizes Apache POI SXSSF series API for optimized export performance. Generates a large dataset for testing export capabilities. ```java import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.servlet.http.HttpServletResponse; import java.util.List; // Assuming User class, DbUtil, and log are defined elsewhere // import com.yourpackage.User; // import com.yourpackage.DbUtil; // import org.slf4j.Logger; // import org.slf4j.LoggerFactory; // private static final Logger log = LoggerFactory.getLogger(YourController.class); @RequestMapping(value = "/downXlsx", method = RequestMethod.GET) public void downXlsx(HttpServletResponse response) { long beginMillis = System.currentTimeMillis(); List userList = DbUtil.getUserList(100000); // Generate 100,000 test data ExcelKit.$Export(User.class, response).downXlsx(userList, false); log.info("#ExcelKit.$Export success, size={},timeConsuming={}s", userList.size(), (System.currentTimeMillis() - beginMillis) / 1000L); } ``` -------------------------------- ### Execute File Import with Streaming Source: https://github.com/wuwenze/excelkit/blob/master/README.md Process Excel files using a streaming approach to avoid memory issues, regardless of file size. Handles both successful and erroneous rows. ```java import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.List; import java.util.Map; // Assuming User class, Lists, MapUtil, CollectionUtil, ExcelReadHandler, ExcelErrorField are defined elsewhere // import com.yourpackage.User; // import com.google.common.collect.Lists; // import com.yourpackage.util.MapUtil; // import com.yourpackage.util.CollectionUtil; // import com.yourpackage.handler.ExcelReadHandler; // import com.yourpackage.model.ExcelErrorField; @RequestMapping(value = "/importUser", method = RequestMethod.POST) public ResponseEntity importUser(@RequestParam MultipartFile file) throws IOException { long beginMillis = System.currentTimeMillis(); List successList = Lists.newArrayList(); List> errorList = Lists.newArrayList(); ExcelKit.$Import(User.class) .readXlsx(file.getInputStream(), new ExcelReadHandler() { @Override public void onSuccess(int sheetIndex, int rowIndex, User entity) { successList.add(entity); // Single row read successfully, add to import queue. } @Override public void onError(int sheetIndex, int rowIndex, List errorFields) { // Data read failed, record all failed data for the current row errorList.add(MapUtil.newHashMap( "sheetIndex", sheetIndex, "rowIndex", rowIndex, "errorFields", errorFields )); } }); // TODO: Execute the import operation for successList. return ResponseEntity.ok(MapUtil.newHashMap( "data", successList, "haveError", !CollectionUtil.isEmpty(errorList), "error", errorList, "timeConsuming", (System.currentTimeMillis() - beginMillis) / 1000L )); } ``` -------------------------------- ### XML Mapping Configuration for User Entity Source: https://github.com/wuwenze/excelkit/blob/master/README.md XML configuration for mapping User entity fields to Excel columns. This file should be placed at classpath:excel-mapping/{entityClassName}.xml. ```xml ``` -------------------------------- ### Execute File Import Source: https://github.com/wuwenze/excelkit/blob/master/README.md Executes file import using a streaming approach to handle large files without memory issues. It processes data row by row and handles success and error cases. ```APIDOC ## POST /importUser ### Description Imports data from an Excel file, processing it row by row to prevent memory overflows. It separates successful imports from errors. ### Method POST ### Endpoint /importUser ### Parameters #### Query Parameters - **file** (MultipartFile) - Required - The Excel file to import. ### Request Example ``` POST /importUser HTTP/1.1 Host: example.com Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="file"; filename="users.xlsx" Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet [Binary Excel file content] ------WebKitFormBoundary7MA4YWxkTrZu0gW-- ``` ### Response #### Success Response (200) - **data** (List) - A list of successfully imported User objects. - **haveError** (boolean) - Indicates if there were any errors during import. - **error** (List>) - A list of errors, each containing sheet index, row index, and error fields. - **timeConsuming** (long) - The time taken for the import process in seconds. #### Response Example ```json { "data": [ { "name": "John Doe", "age": 30 } ], "haveError": false, "error": [], "timeConsuming": 2 } ``` ``` -------------------------------- ### Generate Excel Import Template Source: https://github.com/wuwenze/excelkit/blob/master/README.md Generates an Excel import template based on the provided configuration. This includes features like comments and dropdowns. ```APIDOC ## GET /downTemplate ### Description Generates an Excel import template with optional example data. ### Method GET ### Endpoint /downTemplate ### Parameters None ### Request Example None ### Response #### Success Response (200) - Binary stream of an Excel file (.xlsx) #### Response Example None ``` -------------------------------- ### User Entity with XML Mapping Source: https://github.com/wuwenze/excelkit/blob/master/README.md Defines the User entity for XML mapping. The actual mapping configuration is provided in a separate XML file. ```java public class User2 { private Integer userId; private String username; private String password; private String email; private Integer sex; private UserGroup userGroup; private Date createAt; private Integer customizeField; // Getter and Setter .. } ``` -------------------------------- ### Execute Excel Bulk Export Source: https://github.com/wuwenze/excelkit/blob/master/README.md Performs a bulk export of data to an Excel file (.xlsx) using Apache POI SXSSF for optimized performance, suitable for large datasets. ```APIDOC ## GET /downXlsx ### Description Performs a bulk export of a large dataset to an Excel file (.xlsx), optimized for performance. ### Method GET ### Endpoint /downXlsx ### Parameters None ### Request Example None ### Response #### Success Response (200) - Binary stream of an Excel file (.xlsx) containing the exported data. #### Response Example None ``` -------------------------------- ### ExcelKit Maven Dependency Source: https://github.com/wuwenze/excelkit/blob/master/README.md Add this dependency to your project's pom.xml to include ExcelKit. ```xml com.wuwenze ExcelKit 2.0.72 ``` -------------------------------- ### User Entity with Annotation Mapping Source: https://github.com/wuwenze/excelkit/blob/master/README.md Defines the User entity and maps its fields to Excel columns using annotations. Supports custom validators, converters, and comments. ```java @Excel("用户信息") public class User { @ExcelField(value = "编号", width = 30) private Integer userId; @ExcelField(// value = "用户名",// required = true,// validator = UsernameValidator.class,// comment = "请填写用户名,最大长度为12,且不能重复" ) private String username; @ExcelField(value = "密码", required = true, maxLength = 32) private String password; @ExcelField(value = "邮箱", validator = UserEmailValidator.class) private String email; @ExcelField(// value = "性别",// readConverterExp = "未知=0,男=1,女=2",// writeConverterExp = "0=未知,1=男,2=女",// options = SexOptions.class// ) private Integer sex; @ExcelField(// value = "用户组",// name = "userGroup.name",// options = UserGroupNameOptions.class ) private UserGroup userGroup; @ExcelField(value = "创建时间", dateFormat = "yyyy/MM/dd HH:mm:ss") private Date createAt; @ExcelField(// value = "自定义字段",// maxLength = 80,// comment = "可以乱填,但是长度不能超过80,导入时最终会转换为数字",// writeConverter = CustomizeFieldWriteConverter.class,// 写文件时,将数字转字符串 readConverter = CustomizeFieldReadConverter.class// 读文件时,将字符串转数字 ) private Integer customizeField; // Getter and Setter .. } ``` -------------------------------- ### Custom Cell Validation with Validator Interface Source: https://github.com/wuwenze/excelkit/blob/master/README.md Implement the Validator interface to define custom validation rules for cells during Excel import. ```java public class UsernameValidator implements Validator { final List ERROR_USERNAME_LIST = Lists.newArrayList( "admin", "root", "master", "administrator", "sb" ); @Override public String valid(Object o) { String username = (String) o; if (username.length() > 12) { return "用户名不能超过12个字符。"; } if (ERROR_USERNAME_LIST.contains(username)) { return "用户名非法,不允许使用。"; } return null; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.