JAVA-based CSV file exporting method, system and equipment and medium

By using annotation mechanisms and utility classes to unify the CSV generation logic, and combining reflection and the factory pattern, the problems of format reliability and scalability in Java CSV export solutions are solved, resulting in an efficient, flexible, and easy-to-use CSV file export method suitable for Java Web projects.

CN120874755APending Publication Date: 2025-10-31SHANDONG LANGCHAO YUNTOU INFORMATION TECH CO LTD
View PDF 0 Cites 1 Cited by

Patent Information

Application Number
CN202510857121.6
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-06-25
Publication Date
2025-10-31

AI Technical Summary

Technical Problem

Existing Java CSV export solutions suffer from low format reliability, high development costs, poor scalability, and are prone to errors when manually concatenating data. Third-party tool libraries are complex to configure, and custom tool classes lack standardization and stability.

Method used

The field export format is defined through annotation mechanism, the CSV generation logic is uniformly processed by utility classes, and multi-data type adaptation and automatic format conversion are achieved by combining reflection and factory pattern. An efficient stream processing mechanism and predefined array mapping are adopted to provide a default format processing mechanism.

Benefits of technology

It enables efficient, flexible, and easy-to-use CSV file export, avoids formatting errors, improves export efficiency and reliability, reduces development costs and code coupling, and is suitable for various Java Web projects.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120874755A_ABST
    Figure CN120874755A_ABST
Patent Text Reader

Abstract

The invention provides a CSV file exporting method, system and device based on JAVA and a medium, and belongs to the technical field of computers. The method comprises the steps that a Java entity class is combined with an annotation to specify a field export format, request mapping is set in a Web project, and a basic array separation header and a field name are analyzed through a tool class; after header data containing UTF-8BOM is written into the output stream, field values are obtained or Map key values are traversed through a reflection mechanism according to object types, data formats are converted according to annotation or default rules in combination with formatting processing factory types, special character escape is completed, and the output stream is written. According to the method, automatic and efficient export from the structured data to the CSV file is realized through data format definition driven by annotation, general export logic packaged by a tool class and a multi-type adaptation mechanism of reflection and a factory mode, and the method is suitable for data export scenes of various Java projects.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of computer technology, and more specifically relates to a method, system, device and medium for exporting CSV files based on JAVA. Background Technology

[0002] In modern information systems, the CSV format is widely used for data exchange and report export due to its simple structure and versatility. However, existing solutions for handling CSV export requirements have significant shortcomings, particularly in Java, a mainstream language for enterprise development.

[0003] Manually concatenating strings is the most basic approach, requiring developers to handle field delimiters, newline character control, and special character escaping themselves. This method is not only inefficient but also prone to formatting errors, especially when dealing with large amounts of data or complex data types, where performance issues become more pronounced. Furthermore, the code has poor maintainability and struggles to adapt to changing business requirements.

[0004] Third-party libraries such as Apache CommonsCSV offer relatively comprehensive CSV processing capabilities, but their configuration is complex and the learning curve is steep. Developers need to understand a large number of API interfaces and configuration parameters to use these libraries correctly. Moreover, there is a contradiction between the general applicability of third-party libraries and their adaptability to business scenarios; over-reliance on library functionality can lead to excessive coupling between code and business logic, increasing the difficulty of subsequent expansion.

[0005] While framework-based custom utility classes can quickly implement export functionality in specific projects, they lack unified design standards and interface specifications. Different utility classes differ in data mapping rules, format configuration methods, and exception handling strategies, resulting in poor reusability. Furthermore, the lack of standardized error handling and performance optimization mechanisms can easily lead to stability issues when facing high-concurrency or large-volume data export tasks.

[0006] In summary, existing JavaCSV export solutions have shortcomings in terms of format reliability, development cost, and engineering adaptability. Manual concatenation is inefficient and error-prone; third-party utility libraries are complex to configure and have poor extensibility; and custom utility classes lack standardization and have low reusability. Therefore, developing an automated, efficient, flexible, and standardized CSV export method is of significant practical importance. Summary of the Invention

[0007] To address the above problems, the present invention aims to provide a CSV file export method, system, device, and medium based on JAVA. By defining the field export format through annotation mechanism, unifying the CSV generation logic through utility classes, and realizing multi-data type adaptation and automated format conversion through reflection and factory pattern, the invention achieves CSV file export with clear structure, high efficiency, reliability, flexibility, and ease of use, effectively solving problems such as error-prone manual splicing, complex configuration of third-party libraries, and poor reusability of custom utility classes.

[0008] To achieve the above objectives, the present invention employs the following technical solution: In a first aspect, embodiments of this application provide a CSV file export method based on JAVA, including: Define product entity classes using the Java language and use annotations to specify the export format for specific fields; In a web project, set up a request mapping to export CSV files, construct an HTTP response to obtain the output stream, define a basic array containing table headers and field names, call a service layer method to obtain a list of data to be exported, and use a utility class to parse and write the data. The utility class receives the base array, initializes the header array and field name array, iterates through the base array to separate the header elements and field name elements and stores them into the corresponding arrays, and then stores the header array and field name array as key-value pairs into the map and returns it. Use utility class methods to concatenate the header elements into a string, write UTF-8 BOM bytes and header string bytes to the output stream, and add a newline character; Based on the object type, the corresponding method is called in the writeRow method of the utility class to assemble the data. If it is a regular JavaBean, the getter method and field value are obtained through reflection, formatted according to annotations, escaped, and then concatenated and written to the output stream. Define a formatting factory class that returns the corresponding formatting processor instance based on EscapeType, performs format conversion on different data types in a specified way, and calls specific methods to format columns without annotations; When the exported object is a Map, the field names are obtained from the Map by iterating through the array of field names in the composeRowDataMap method, formatted, and then concatenated and written to the output stream.

[0009] In an optional implementation, the step of defining product entity classes using the Java language and specifying export formats for specific fields using annotations includes: The product entity class is defined using Java, and the @Data annotation simplifies the writing of getter and setter methods. Private variables are set for product attributes, and the @ExportColumn annotation is used to specify the name, type, and format of the exported attributes that require special processing.

[0010] In an optional implementation, the step of receiving a base array in the utility class, initializing a header array and a field name array, separating the header elements and field name elements by traversing the base array and storing them in the corresponding arrays, and then storing the header array and field name array as key-value pairs in a map and returning it includes: The export utility class CsvExportUtil receives the basic array, initializes the header array and field name array, identifies the header elements and field name elements by traversing the basic array, separates the elements with the # character, and stores the header and field names into the corresponding arrays respectively. Store the header array and field name array as keys in a map and return it.

[0011] In an optional implementation, the step of using a utility class method to concatenate the header elements into a string, writing UTF-8 BOM bytes and header string bytes to the output stream, and adding a newline character includes: The CsvExportUtil class is used to separate the header elements in the header array with commas and concatenate them into a string to generate header data. Write the UTF-8 BOM bytes, header data, and newline character to the output stream in sequence.

[0012] In an optional implementation, the step of assembling data by calling the corresponding method in the `writeRow` method of the utility class according to the object type, and if it is a regular JavaBean, obtaining the getter methods and field values ​​through reflection, formatting and escaping them according to annotations, and then concatenating and writing them to the output stream, includes: Based on the object type, the corresponding composeRowData method is called in the writeRow method of the utility class to assemble the data to be exported; the object types include JavaBean and Map. If the object type is JavaBean, the field values ​​are obtained through reflection. The getter methods of each field are obtained through the reflection mechanism, the methods are called to get the field values, and the formatter is obtained based on the annotation type of the field values ​​for formatting. If the data to be exported has no annotations, the default method will be called to process it; For formatted values, special characters are escaped and concatenated into a line of data string, which is then written to the output stream.

[0013] In an optional implementation, the defined formatting factory class returns a corresponding formatter instance based on EscapeType, performs format conversion on different data types in a specified manner, and calls specific methods to format unannotated columns, including: Define a formatting factory class that returns the corresponding formatting processor instance based on the EscapeType type; Convert date, number, and text data to a specified format; For column data without annotations, the formatColumnValue method is called to process it, and date types are formatted using the passed dateFormat parameter; other data types are converted to strings and processed for special characters.

[0014] In an optional implementation, when the exported object is a Map, the step of retrieving field names from the Map by iterating through the field name array in the composeRowDataMap method, formatting them, and then concatenating them before writing them to the output stream includes: For Map type objects, the composeRowDataMap method iterates through the array of field names, retrieves the corresponding values ​​from the Map, formats the values ​​to remove special characters, concatenates them into a row of data strings, and writes them to the output stream.

[0015] Secondly, embodiments of this application also provide a JAVA-based CSV file export system, including: The entity class definition module is used to define product entity classes using the Java language and to specify the export format for specific fields using annotations. The Export Request Settings module is used to set the request mapping for exporting CSV files in a web project, construct an HTTP response to obtain the output stream, define a basic array containing table headers and field names, call service layer methods to obtain the list of data to be exported, and parse and write the data with the help of utility classes; The header and field name parsing module is used to receive a basic array in the utility class, initialize the header array and field name array, separate the header elements and field name elements by traversing the basic array and store them into the corresponding arrays, and then store the header array and field name array as key-value pairs into a map and return it. The header data writing module is used to concatenate header elements into a string using utility class methods, write UTF-8 BOM bytes and header string bytes to the output stream, and add a newline character. The main data writing module is used to call the corresponding method in the writeRow method of the utility class to assemble data according to the object type. If it is a regular JavaBean, the getter method and field value are obtained through reflection, formatted according to annotations, escaped and then concatenated and written to the output stream. The formatting module is used to define formatting factory classes, return corresponding formatting processor instances based on EscapeType, perform format conversion on different data types in a specified way, and call specific methods to format columns without annotations. A special data writing module is used when the exported object is a Map. In the composeRowDataMap method, it iterates through the array of field names to obtain the field names from the Map, formats them, and then concatenates them to write them to the output stream.

[0016] Thirdly, embodiments of this application also provide an electronic device, including a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the processor executes the program to implement the steps of the JAVA-based CSV file export method described in any of the above descriptions.

[0017] Fourthly, embodiments of this application also provide a storage medium storing a computer program thereon, which, when executed by a processor, implements the steps of the JAVA-based CSV file export method described in any of the above embodiments.

[0018] As can be seen from the above technical solutions, the present invention has the following advantages: This application provides a Java-based CSV file export method that uses annotations to specify the export format for entity class fields, decoupling data from format and improving code maintainability. A utility class is used to uniformly handle the CSV export logic, avoiding formatting errors and performance issues caused by manual string concatenation, thus improving export efficiency and reliability. Through reflection and the factory pattern, it supports the export of various data types such as JavaBeans and Maps, and can automatically perform data formatting and special character escaping based on annotations, enhancing the method's versatility and flexibility. Furthermore, this method provides a default formatting mechanism, which can also handle unannotated fields appropriately, further lowering the barrier to entry. Overall, this method effectively solves the problems existing in current CSV export solutions and can be widely applied in various Java Web projects.

[0019] This application uses annotations to specify the export format for entity class fields, and combines reflection and the factory pattern to achieve automatic mapping of data objects to CSV format. It supports multiple data types such as JavaBean and Map, and can flexibly adapt to different business scenarios.

[0020] This application uses a unified utility class to handle CSV export logic, automatically handling format details such as field separators, line breaks, and special character escaping, avoiding format errors caused by manual concatenation and effectively ensuring the accuracy of exported data.

[0021] This application employs an efficient stream processing mechanism, combined with predefined basic arrays and mapping relationships, to reduce string concatenation overhead and improve processing efficiency when exporting large amounts of data.

[0022] This application adopts a separation of business logic and export logic, the utility class design follows a unified standard, supports the extension of new formatting strategies through annotations, reduces code coupling, and facilitates subsequent maintenance and feature iteration.

[0023] This application provides a default formatting mechanism that automatically adapts unannotated fields to common formats, lowering the barrier to entry. It also supports custom processors via EscapeType to meet personalized formatting needs, balancing ease of use and scalability. Attached Figure Description

[0024] To more clearly illustrate the technical solution of the present invention, the accompanying drawings used in the description will be briefly introduced below. Obviously, the accompanying drawings described below are only some embodiments of the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0025] Figure 1 A flowchart illustrating the JAVA-based CSV file export method provided in this application.

[0026] Figure 2 A flowchart illustrating another JAVA-based CSV file export method provided in this application.

[0027] Figure 3 A schematic diagram of the structure of the JAVA-based CSV file export system provided in this application.

[0028] Figure 4 A schematic diagram of the structure of the electronic device provided in this application. Detailed Implementation

[0029] The various embodiments of this disclosure will be described more fully in the detailed steps of the Java-based CSV file export method described below. This disclosure may have various embodiments, and adjustments and changes may be made therein. However, it should be understood that there is no intention to limit the various embodiments of this disclosure to the specific embodiments disclosed herein, but rather this disclosure should be understood to cover all adjustments, equivalents, and / or alternatives falling within the spirit and scope of the various embodiments of this disclosure.

[0030] In the following, the terms “comprising” or “may include”, which may be used in various embodiments of this disclosure, indicate the presence of the disclosed functions, operations, or elements, and do not limit the addition of one or more functions, operations, or elements. Furthermore, as used in various embodiments of this disclosure, the terms “comprising,” “having,” and their cognates are intended only to indicate a particular feature, number, step, operation, element, component, or combination of the foregoing, and should not be construed as primarily excluding the presence of one or more other features, numbers, steps, operations, elements, components, or combinations of the foregoing, or the possibility of adding one or more combinations of the foregoing.

[0031] The technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.

[0032] Please see Figure 1 The diagram shows a flowchart of a CSV file export method based on Java in a specific embodiment. The method includes: S1: Define product entity classes using the Java language and use annotations to specify the export format for specific fields.

[0033] In a specific implementation, product entity classes are defined using the Java language, and the @Data annotation simplifies the writing of getter and setter methods. Private variables are set for product attributes, and the @ExportColumn annotation is used to specify the name, type, and format of the exported attributes that require special processing, providing a foundation for subsequent reflection mechanisms to obtain data and perform formatting processing.

[0034] For example, define a product entity class using Java, such as the `Product` class. Use the `@Data` annotation to simplify getter and setter methods. Set private variables for product-related attributes such as `id`, `productName`, `price`, `productionAddress`, `createTime`, and `num`. For attributes requiring special handling, such as the unit price `price` and creation time `createTime`, use the `@ExportColumn` annotation to specify their exported name (`name` attribute), type (`type` attribute, e.g., `EscapeType.DIGIT` for numeric type, `EscapeType.DATE` for date type), and format (e.g., numeric format "#.00", date format "yyyy-MM-ddHH:mm:ss").

[0035] S2: In the Web project, set up the request mapping for exporting CSV files, construct the HTTP response to obtain the output stream, define the basic array containing the table headers and field names, call the service layer method to obtain the list of exported data, and use a utility class to parse and write the data.

[0036] In a specific implementation, a request mapping for exporting CSV files is set up in the Web project, an HTTP response is constructed, the response output stream is obtained, a basic array containing table headers and field names is defined, a service layer method is called to obtain product list data, and a utility class is used to parse the table headers and field names, and the table headers and product data are written to the output stream in sequence, thus realizing full-process control from request to data export.

[0037] For example, in a web project, set up a request mapping to export CSV files, such as defining an export interface using `@GetMapping(" / exportProducts")`. Construct an HTTP response, setting the response content type to text / csv, and enable attachment download by setting the Content-Disposition response header, specifying the download file name as products.csv. Obtain the output stream of the response.

[0038] Define an array `titleArr` containing header information and corresponding field names, in the format "header name#field name", such as "product name#productName". Call the service layer method to obtain the product list data to be exported, `productList`. Using the `CsvExportUtil` utility class, parse the header array `headerArr` and the field name array `fieldNameArr` from `titleArr`. First, write the header data to the output stream, then iterate through the product list, writing each product's data to the output stream in the specified format, and finally close the output stream.

[0039] S3: Receive the basic array in the utility class, initialize the header array and field name array, separate the header elements and field name elements by traversing the basic array and store them in the corresponding arrays, then store the header array and field name array as key-value pairs in the map and return it.

[0040] In a specific implementation, the export utility class receives the table header and field name arrays, initializes the table header array and field name array, iterates through the arrays with "#" separating the elements, stores the table header and field names into the corresponding arrays respectively, and stores them in the map in the form of key-value pairs, providing accurate field mapping for subsequent writing of table headers and assembly of data.

[0041] For example, in the CSV export utility class `CsvExportUtil`, it receives the `titleArr` array. It initializes the header array `headerArr` and the field name array `fieldNameArr`, with the same length as `titleArr`. It iterates through the `titleArr` array, separating each element with a "#" symbol. The first part of the separated element is stored as the header in `headerArr`, and the second part as the field name in `fieldNameArr`. `headerArr` and `fieldNameArr` are then stored as key-value pairs in a map and returned for later use in writing headers and assembling data.

[0042] S4: Use utility class methods to concatenate the header elements into a string, write UTF-8 BOM bytes and header string bytes to the output stream, and add a newline character.

[0043] In a specific implementation, a utility class method is used to write header data into the output stream. The header array elements are concatenated into a string, and UTF-8 BOM bytes are written first to ensure encoding compatibility. Then, the header string and newline character are written to complete the standardized writing of the header row, setting a unified column identifier for the writing of subsequent data rows.

[0044] For example, we use methods from the CsvExportUtil utility class to write header data to the output stream. The header elements in the headerArr array are concatenated with commas to form the string headerString. Considering CSV file encoding and compatibility, we first write UTF-8 BOM bytes (-17, -69, -65) to the output stream, then write the headerString bytes, and finally add a newline character "\r\n" to complete writing the header row.

[0045] S5: Based on the object type, call the corresponding method in the writeRow method of the utility class to assemble the data. If it is a regular JavaBean, obtain the getter method and field values ​​through reflection, format them according to the annotations, escape them, and then concatenate them into the output stream.

[0046] In a specific implementation, based on the object type (JavaBean or Map), the corresponding `composeRowData` method is called in the `writeRow` method of the utility class to assemble the data. For JavaBeans, field values ​​are obtained via reflection, and a formatter is used to format the data based on the annotation type; otherwise, the default method is called. The formatted values ​​are then escaped for special characters, concatenated into a line of data, and written to the output stream, achieving universal export processing for different types of data objects.

[0047] For example, depending on the type of the passed object (JavaBean or Map), the `writeRow` method of `CsvExportUtil` calls the `composeRowDataBean` or `composeRowDataMap` method to assemble the data. If it's a regular JavaBean, it iterates through the array of field names `fieldNameArr`, uses reflection to obtain the getter method for each field, and calls the method to retrieve the field value. If the field has the `@ExportColumn` annotation, it retrieves the corresponding formatter (`EscapeFormatter`) based on the annotation type and formats the field value according to the format specified by the annotation; otherwise, it calls the default `formatColumnValue` method. The formatted value is then escaped for special characters (e.g., converting "" to """), enclosed in double quotes, concatenated into a single data string, and written to the output stream.

[0048] S6: Define a formatting factory class that returns the corresponding formatter instance based on EscapeType, performs format conversion on different data types in a specified manner, and calls specific methods to format unannotated columns.

[0049] In a specific implementation, a formatting factory class is defined, which returns the corresponding formatting processor instance based on the EscapeType type. Each formatting class converts data of date, number, and text types according to the specified format. Columns without annotations are processed using default methods. Dates are formatted using the passed parameters, and other types are converted to strings and special characters are handled, ensuring the uniformity and correctness of data formats in all aspects.

[0050] For example, a formatting factory class `EscapeFormatterFactory` is defined, which returns the corresponding formatter instance based on the `EscapeType` type. For the date type `EscapeType.DATE`, the corresponding `EscapeDateFormatter` class converts the Date object to a string according to the specified format (default "yyyy-MM-ddHH:mm:ss"); for the number type `EscapeType.DIGIT`, the `EscapeDigitsFormatter` class uses `DecimalFormat` to convert numbers according to the specified format; and for the text type `EscapeType.TEXT`, the `EscapeTextFormatter` class directly converts the object to a string. If the column is not annotated with `@ExportColumn`, the `formatColumnValue` method is called, formatting the date type with the passed `dateFormat` parameter, while other types are directly converted to strings and special character processing is performed.

[0051] S7: When the exported object is a Map, the field names are obtained from the Map by traversing the array of field names in the composeRowDataMap method, formatted, and then concatenated and written to the output stream.

[0052] In a specific implementation, for exported Map type objects, the composeRowDataMap method iterates through the array of field names, retrieves the corresponding values ​​from the Map, calls the formatting method to process them, and then concatenates them into a row of data strings and writes them to the output stream, thereby realizing convenient export of Map data structures and extending the utility class's support for different data structures.

[0053] For example, when the exported object is a Map, the `composeRowDataMap` method iterates through the array of field names `fieldNameArr`, retrieves the values ​​for the corresponding field names from the Map, calls the `formatColumnValue` method to format the values ​​and handle special characters, concatenates them into a single data string, and writes it to the output stream.

[0054] In this embodiment, annotations are used to flexibly specify the export format for entity class fields, decoupling data from format. A utility class unifies the CSV generation logic, avoiding formatting errors and performance degradation from manual concatenation. Reflection and the factory pattern support automated mapping of various data types, including JavaBeans and Maps. Predefined formatters and special character escaping strategies ensure the reliability of the exported data format. A default processing mechanism is provided to adapt to unannotated fields, lowering the barrier to entry and offering both extensibility and reusability. Overall, this method, through standardized design and automated processing, effectively addresses the shortcomings of existing solutions in terms of format accuracy, development cost, performance efficiency, and engineering adaptability. It achieves a clear, efficient, flexible, and easy-to-maintain CSV export function, suitable for data export scenarios in various Java projects.

[0055] Furthermore, as a refinement and extension of the specific implementation methods described above, and to fully illustrate the specific implementation process in this embodiment, another JAVA-based method for exporting CSV files is provided, such as... Figure 2 As shown, the method specifically includes the following steps: Step 1: Define the product entity class. The specific script is as follows: @Data public class Product { private Long id; / / Product Name private String productName; / / unit price @ExportColumn(name="Unit Price",type=EscapeType.DIGIT,format="#.00") private BigDecimal price; / / Production location private String productionAddress; / / Creation time @ExportColumn(name="Creation Time",type= EscapeType.DATE,format="yyyy-MM-dd HH:mm:ss") private Date createTime; / / Inventory Quantity private int num; / / …other attributes } Step 2: Export a CSV file via a web request. The specific script is as follows: @GetMapping(" / exportProducts") public void exportProducts (HttpServletResponse response) throwsIOException { String[] titleArr = new String[]{"Product Name#productName", "Unit Price#price", "Production Location #productionAddress", "Creation Time #createTime"}; List <product>productList = productService.getAllProducts(); response.setContentType("text / csv"); response.setHeader("Content-Disposition", "attachment; filename=products.csv"); OutputStream out = response.getOutputStream(); Map<String, String[]>headerMap = CsvExportUtil.getHeaderField(titleArr); String[] headerArr = headerMap.get("headerArr"); String[] fieldNameArr = headerMap.get("fieldNameArr"); CsvExportUtil.writeCsvHeader(headerArr, out); if(!CollectionUtils.isEmpty(productList)){ for(Product product : productList){ CsvExportUtil.writeRow(product, fieldNameArr, "yyyy-MM-dd HH:mm:ss",out); } } out.flush(); out.close(); } Step 3: In the CSV export utility class CsvExportUtil, parse the table header from titleArr and export the columns. The specific script is as follows: public static Map<String, String[]>getHeaderField(String[] titleArr){ String[] headerArr = new String[titleArr.length]; String[] fieldNameArr = new String[titleArr.length]; for(int i=0; i<titleArr.length; i++){ String title = titleArr[i]; headerArr[i] = title.split("#")[0]; fieldNameArr[i] = title.split("#")[1]; } Map<String, String[]> map = new HashMap<>(); map.put("headerArr", headerArr); map.put("fieldNameArr", fieldNameArr); return map; } Step 4: Write the header data into the output stream. The specific script is as follows: public static void writeCsvHeader(String[] headerArr, OutputStream outputStream) { String headerString = String.join(",", headerArr); try { byte[] uft8Bom = new byte[]{-17, -69, -65}; outputStream.write(uft8Bom); outputStream.write(headerString.getBytes()); outputStream.write("\r\n".getBytes()); } catch (Exception e) { log.error("Failed to export the header", e); } } Step 5: Write each line of data to the output stream. When the passed object is a Map, call the `composeRowDataMap` method to assemble the data; when it is a regular JavaBean, call the `composeRowDataBean` method to assemble the data. The specific script is as follows: public static void writeRow(Object rowData, String[] fieldNameArr,String dateFormat, OutputStream outputStream) { String formattedRowData = ""; / / When the passed object is a Map if(rowData instanceof Map){ formattedRowData = composeRowDataMap(rowData, fieldNameArr,dateFormat); }else{ formattedRowData = composeRowDataBean(rowData, fieldNameArr,dateFormat); } try { outputStream.write(formattedRowData.getBytes()); outputStream.write("\r\n".getBytes()); } catch (IOException e) { log.error(e.getMessage()); } } Step 6: When the exported object is a regular JavaBean, assemble each row of exported data and format the data. The specific script is as follows: private static String composeRowDataBean(Object rowData, String[]fieldNameArr, String dateFormat) { StringBuilder rowValueBuilder = new StringBuilder(); for(String fieldName : fieldNameArr) { String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); Class<?>dataClass = rowData.getClass(); try { Method getMethod = dataClass.getMethod(getMethodName); Object columnValue = getMethod.invoke(rowData); if (null == columnValue) { columnValue = ""; } Field field = ReflectionUtils.findField(dataClass, fieldName); if (field != null) { ReflectionUtils.makeAccessible(field); ExportColumn exportColumn = field.getAnnotation(ExportColumn.class); if (Objects.nonNull(exportColumn)) { EscapeFormatter escapeFormatter = EscapeFormatterFactory.getInstance(exportColumn.type()); columnValue = escapeFormatter.format(columnValue, exportColumn.format()); String strValue = columnValue.toString(); if (StringUtils.isNotBlank(strValue)) { strValue = strValue.replaceAll("\"", "\"\""); } strValue = "\"" + strValue + "\""; rowValueBuilder.append(strValue).append(","); } else { rowValueBuilder.append(formatColumnValue(columnValue, dateFormat)).append(","); } }else{ rowValueBuilder.append(formatColumnValue(columnValue, dateFormat)).append(","); } } catch (Exception e) { log.error("获取导出列的值报错", e); } } if (rowValueBuilder.length()>0) { rowValueBuilder.deleteCharAt(rowValueBuilder.length() - 1); } return rowValueBuilder.toString(); } In this step, if the exported column is annotated with `@ExportColumn`, the annotation has a `type` attribute with three possible values: `EscapeType.DIGIT`, `EscapeType.TEXT`, and `EscapeType.DATE`, corresponding to number, text, and date types respectively. You can extend the value according to your needs. Each type has a formatting class for data formatting. For example, when the type is `EscapeType.DATE`, it indicates that the column is a date type, and you need to specify its conversion format, such as "yyyy-MM-dd". The formatting class `EscapeDateFormatter` will handle this. When the column does not have the `@ExportColumn` annotation, the program calls the `formatColumnValue` method for default processing.

[0056] Step 7: Define the formatting factory class. The specific script is as follows: The classes for formatting processing include: public class EscapeFormatterFactory { public EscapeFormatterFactory() { } public static EscapeFormatter getInstance(EscapeType escapeType) { if(EscapeType.DATE == escapeType){ return new EscapeDateFormatter(); }else if(EscapeType.DATE == escapeType){ return new EscapeDigitsFormatter(); }else{ return new EscapeTextFormatter(); } } } Classes for formatting date types: public class EscapeDateFormatter extends EscapeFormatter { public EscapeDateFormatter() { } public Object format(Object fieldValueObj, String format) { if (Objects.isNull(fieldValueObj)) { return ""; } else { if (StringUtils.isBlank(format)) { format = "yyyy-MM-dd HH:mm:ss"; } return new SimpleDateFormat(format).format((Date)fieldValueObj); } } } Class for formatting numeric types: public class EscapeDigitsFormatter extends EscapeFormatter { public EscapeDigitsFormatter() { } public Object format(Object fieldValueObj, String format) { return Objects.isNull(fieldValueObj) || "".equals(fieldValueObj)? "" :new DecimalFormat(format).format(String.valueOf(fieldValueObj)); } } Class for formatting text types: public class EscapeTextFormatter extends EscapeFormatter { public EscapeTextFormatter() { } public Object format(Object fieldValueObj, String format) { return Objects.isNull(fieldValueObj)? "" : String.valueOf(fieldValueObj); } } Step 8: Use the `formatColumnValue` method to process data in columns that are not annotated with `ExportColumn`. If the data is in date format, the `dateFormat` parameter must be used for processing. The specific script is as follows: private static String formatColumnValue(Object columnValue, StringdateFormat) { String strValue = ""; if (columnValue instanceof Date) { Date date = (Date)columnValue; strValue = new SimpleDateFormat(dateFormat).format(date); } else { strValue = String.valueOf(columnValue); } if (StringUtils.isNotBlank(strValue)) { strValue = strValue.replaceAll("\"", "\"\""); } return "\"" + strValue + "\""; } Step 9: When the exported object is a Map, assemble each row of exported data.

[0057] private static String composeRowDataMap(Object rowData, String[]fieldNameArr, String dateFormat) { StringBuilder rowValueBuilder = new StringBuilder(); Map<String, Object> map = (Map<String, Object> rowData; for(String fieldName : fieldNameArr) { Object fieldValue = map.get(fieldName); rowValueBuilder.append(formatColumnValue(fieldValue, dateFormat)).append(","); } if (rowValueBuilder.length()>0) { rowValueBuilder.deleteCharAt(rowValueBuilder.length() - 1); } return rowValueBuilder.toString(); } like Figure 3 As shown, the following are embodiments of the CSV file export system based on JAVA provided in this disclosure. This system and the CSV file export method based on JAVA in the above embodiments belong to the same inventive concept. For details not described in detail in the embodiments of the CSV file export system based on JAVA, please refer to the embodiments of the CSV file export method based on JAVA described above.

[0058] A Java-based CSV file export system, comprising: The entity class definition module is used to define product entity classes using the Java language and to specify the export format for specific fields using annotations.

[0059] The Export Request Settings module is used to set up the request mapping for exporting CSV files in a web project, construct an HTTP response to obtain the output stream, define a basic array containing table headers and field names, call service layer methods to obtain the list of data to be exported, and parse and write the data using utility classes.

[0060] The header and field name parsing module is used in the utility class to receive the basic array, initialize the header array and field name array, traverse the basic array to separate the header elements and field name elements and store them in the corresponding arrays, and then store the header array and field name array as key-value pairs in the map and return it.

[0061] The header data writing module is used to concatenate header elements into a string using utility class methods, write UTF-8 BOM bytes and header string bytes to the output stream, and add newline characters.

[0062] The main data writing module is used to call the corresponding method in the writeRow method of the utility class to assemble data according to the object type. If it is a regular JavaBean, the getter method and field value are obtained through reflection, formatted according to annotations, escaped and then concatenated and written to the output stream.

[0063] The formatting module defines a formatting factory class, returns a corresponding formatter instance based on EscapeType, performs format conversion on different data types in a specified manner, and calls specific methods to format columns without annotations.

[0064] A special data writing module is used when the exported object is a Map. In the composeRowDataMap method, it iterates through the array of field names to obtain the field names from the Map, formats them, and then concatenates them to write them to the output stream.

[0065] This embodiment provides a Java-based CSV file export system that achieves automated conversion from data objects to CSV format through annotation-driven field mapping, utility class-encapsulated streaming processing, and a collaborative mechanism of reflection and the factory pattern. Specifically, it separates the table header and field names using a predefined base array, automatically parses data types and applies formatting strategies based on annotation metadata, and provides a default processing mechanism compatible with unannotated fields. When handling complex data types, it uses reflection to call getter methods to obtain field values, and the processor generated by the factory class performs format conversion and special character escaping to ensure data accuracy. For Map type data, it uses dynamic mapping through an array of field names to improve flexibility. This standardized and automated design effectively avoids the inefficiency and error-proneness of manual concatenation, reduces the learning cost of third-party libraries, and enhances code reusability through a unified interface design, providing an efficient, reliable, and easily maintainable CSV export solution for enterprise applications.

[0066] Figure 4 A schematic diagram of the hardware structure of an electronic device for implementing various embodiments of the present invention.

[0067] The JAVA-based CSV file export method provided in this application can be applied to electronic devices. Those skilled in the art will understand that the electronic device structure involved in the embodiments of this invention does not constitute a limitation on the electronic device. An electronic device may include more or fewer components than illustrated, or combine certain components, or have different component arrangements. In the embodiments of this invention, the electronic device includes, but is not limited to, laptop computers, desktop computers, workstations, personal digital assistants, servers, blade servers, mainframe computers, and other suitable computers. The electronic device may also represent various forms of mobile devices, such as personal digital processors, cellular phones, smartphones, wearable devices, and other similar computing devices. The components shown herein, their connections and relationships, and their functions are merely examples and are not intended to limit the implementation of the embodiments of this application described and / or claimed herein.

[0068] Electronic devices may include processors, external memory interfaces, internal memory, universal serial bus (USB) interfaces, charging management modules, power management modules, batteries, wireless communication modules, audio modules, speakers, microphones, sensor modules, buttons, cameras, displays, and SIM card interfaces, etc.

[0069] A processor may include one or more processing units, such as: a central processing unit (CPU), an application processor (AP), a modem processor, a graphics processing unit (GPU), an image signal processor (ISP), a controller, memory, a video codec, a digital signal processor (DSP), a baseband processor, and / or a neural network processing unit (NPU). Different processing units may be independent devices or integrated into one or more processors.

[0070] The processor can serve as the nerve center and command center of an electronic device. The controller can generate operation control signals based on the instruction opcode and timing signals to control the fetching and execution of instructions.

[0071] The processor may also include memory for storing instructions and data. In some embodiments, the memory in the processor is a cache memory. This memory can store instructions or data that the processor has just used or that are used repeatedly. If the processor needs to use the instruction or data again, it can retrieve it directly from this memory. This avoids repeated accesses, reduces processor latency, and thus improves system efficiency.

[0072] An external storage interface (ESI) can be used to connect external memory cards, such as microSD cards, to expand the storage capacity of electronic devices. The external memory card communicates with the processor through the ESI to perform data storage functions, such as saving music and video files on the external memory card.

[0073] Internal memory can be used to store computer executable program code, which includes instructions. The processor executes various functional applications and data processing of electronic devices by running the instructions stored in internal memory. Internal memory can include a program storage area and a data storage area. Internal memory can include high-speed random access memory, and can also include non-volatile memory, such as at least one disk storage device, flash memory device, universal flash storage (UFS), etc.

[0074] Wireless communication functionality in electronic devices can be achieved through antennas, wireless communication modules, modem processors, and baseband processors.

[0075] Wireless communication modules can provide solutions for wireless communication applications in electronic devices, including wireless local area networks (WLANs) (such as wireless fidelity (Wi-Fi) networks), Bluetooth (BT), global navigation satellite system (GNSS), frequency modulation (FM), near field communication (NFC), and infrared (IR) technologies.

[0076] Electronic devices can implement audio functions through audio modules, speakers, receivers, microphones, headphone jacks, and application processors.

[0077] Electronic devices can achieve shooting functions through ISPs, cameras, video codecs, GPUs, displays, and application processors.

[0078] Electronic devices can achieve display functions through GPUs, displays, and application processors.

[0079] A GPU is a microprocessor for image processing, connected to the display screen and application processor. GPUs are used to perform mathematical and geometric calculations for graphics rendering. A processor may include one or more GPUs, which execute program instructions to generate or modify display information.

[0080] A display screen is used to display images, videos, etc. A display screen includes a display panel.

[0081] The aforementioned electronic device implements the CSV file export method based on JAVA of this application through annotation-driven field mapping, utility class-encapsulated streaming processing, and the collaborative mechanism of reflection and factory pattern. This achieves the beneficial effects of automatically adapting to multiple data types, ensuring format reliability, improving export efficiency, enhancing code reusability, and reducing development costs.

[0082] The storage medium provided in this application stores a program product capable of implementing a JAVA-based CSV file export method.

[0083] Java-based methods for exporting CSV files include: Define product entity classes using the Java language and use annotations to specify the export format for specific fields; In a web project, set up a request mapping to export CSV files, construct an HTTP response to obtain the output stream, define a basic array containing table headers and field names, call a service layer method to obtain a list of data to be exported, and use a utility class to parse and write the data. The utility class receives the base array, initializes the header array and field name array, iterates through the base array to separate the header elements and field name elements and stores them into the corresponding arrays, and then stores the header array and field name array as key-value pairs into the map and returns it. Use utility class methods to concatenate the header elements into a string, write UTF-8 BOM bytes and header string bytes to the output stream, and add a newline character; Based on the object type, the corresponding method is called in the writeRow method of the utility class to assemble the data. If it is a regular JavaBean, the getter method and field value are obtained through reflection, formatted according to annotations, escaped, and then concatenated and written to the output stream. Define a formatting factory class that returns the corresponding formatting processor instance based on EscapeType, performs format conversion on different data types in a specified way, and calls specific methods to format columns without annotations; When the exported object is a Map, the field names are obtained from the Map by iterating through the array of field names in the composeRowDataMap method, formatted, and then concatenated and written to the output stream. In some possible implementations, the JAVA-based CSV file export method of this disclosure can be implemented as a program product including program code that, when the program product is run on a terminal device, causes the terminal device to perform the steps described in the "Exemplary Methods" section of this specification according to various exemplary embodiments of this disclosure.

[0084] The storage medium disclosed herein may be any combination of one or more readable media. A readable medium may be a readable signal medium or a readable storage medium. A readable storage medium may be, for example, but not limited to, an electrical, magnetic, optical, electromagnetic, infrared, or semiconductor system, apparatus, or device, or any combination thereof. More specific examples (a non-exhaustive list) of readable storage media include: an electrical connection having one or more wires, a portable disk, a hard disk, random access memory (RAM), read-only memory (ROM), erasable programmable read-only memory (EPROM or flash memory), optical fiber, portable compact disk read-only memory (CD-ROM), optical storage device, magnetic storage device, or any suitable combination thereof.

[0085] The above description of the disclosed embodiments enables those skilled in the art to make or use the invention. Various modifications to these embodiments will be readily apparent to those skilled in the art, and the general principles defined herein may be implemented in other embodiments without departing from the spirit or scope of the invention. Therefore, the invention is not to be limited to the embodiments shown herein, but is to be accorded the widest scope consistent with the principles and novel features disclosed herein.< / product>

Claims

1. A method for exporting CSV files based on JAVA, characterized in that, include: Define product entity classes using the Java language and use annotations to specify the export format for specific fields; In a web project, set up a request mapping to export CSV files, construct an HTTP response to obtain the output stream, define a basic array containing table headers and field names, call a service layer method to obtain a list of data to be exported, and use a utility class to parse and write the data. The utility class receives the base array, initializes the header array and field name array, iterates through the base array to separate the header elements and field name elements and stores them into the corresponding arrays, and then stores the header array and field name array as key-value pairs into the map and returns it. Use utility class methods to concatenate the header elements into a string, write UTF-8 BOM bytes and header string bytes to the output stream, and add a newline character; Based on the object type, the corresponding method is called in the writeRow method of the utility class to assemble the data. If it is a regular JavaBean, the getter method and field value are obtained through reflection, formatted according to annotations, escaped, and then concatenated and written to the output stream. Define a formatting factory class that returns the corresponding formatting processor instance based on EscapeType, performs format conversion on different data types in a specified way, and calls specific methods to format columns without annotations; When the exported object is a Map, the field names are obtained from the Map by iterating through the array of field names in the composeRowDataMap method, formatted, and then concatenated and written to the output stream.

2. The CSV file export method based on JAVA according to claim 1, characterized in that, The method of defining product entity classes using the Java language and specifying export formats for specific fields using annotations includes: The product entity class is defined using Java, and the @Data annotation simplifies the writing of getter and setter methods. Private variables are set for product attributes, and the @ExportColumn annotation is used to specify the name, type, and format of the exported attributes that require special processing.

3. The CSV file export method based on JAVA according to claim 2, characterized in that, The process of receiving a base array in the utility class, initializing a header array and a field name array, iterating through the base array to separate the header elements and field name elements and storing them in the corresponding arrays, and then storing the header array and field name array as key-value pairs in a map and returning it includes: The export utility class CsvExportUtil receives the basic array, initializes the header array and field name array, identifies the header elements and field name elements by traversing the basic array, separates the elements with the # character, and stores the header and field names into the corresponding arrays respectively. Store the header array and field name array as keys in a map and return it.

4. The CSV file export method based on JAVA according to claim 3, characterized in that, The method of using utility classes to concatenate header elements into a string, writes UTF-8 BOM bytes and header string bytes to the output stream, and adds a newline character includes: The CsvExportUtil class is used to separate the header elements in the header array with commas and concatenate them into a string to generate header data. Write the UTF-8 BOM bytes, header data, and newline character to the output stream in sequence.

5. The CSV file export method based on JAVA according to claim 4, characterized in that, The process of assembling data by calling the corresponding method in the `writeRow` method of the utility class based on the object type, and for ordinary JavaBeans, obtaining getter methods and field values ​​through reflection, formatting and escaping them according to annotations, and then concatenating and writing them to the output stream, includes: Based on the object type, the corresponding composeRowData method is called in the writeRow method of the utility class to assemble the data to be exported; the object types include JavaBean and Map. If the object type is JavaBean, the field values ​​are obtained through reflection. The getter methods of each field are obtained through the reflection mechanism, the methods are called to get the field values, and the formatter is obtained according to the annotation type of the field values ​​for formatting. If the data to be exported has no annotations, the default method will be called to process it; For formatted values, special characters are escaped and concatenated into a line of data string, which is then written to the output stream.

6. The CSV file export method based on JAVA according to claim 5, characterized in that, The defined formatting factory class returns a corresponding formatter instance based on EscapeType, performs format conversion on different data types according to a specified method, and calls specific methods to format unannotated columns, including: Define a formatting factory class that returns the corresponding formatting processor instance based on the EscapeType type; Convert date, number, and text data to a specified format; For column data without annotations, the formatColumnValue method is called to process it, and date types are formatted using the passed dateFormat parameter; other data types are converted to strings and processed for special characters.

7. The CSV file export method based on JAVA according to claim 6, characterized in that, When the exported object is a Map, the `composeRowDataMap` method retrieves field names from the Map by iterating through the array of field names, formats them, and then concatenates them before writing them to the output stream. This includes: For Map type objects, the composeRowDataMap method iterates through the array of field names, retrieves the corresponding values ​​from the Map, formats the values ​​to remove special characters, concatenates them into a row of data strings, and writes them to the output stream.

8. A CSV file export system based on JAVA, characterized in that, The system employs the JAVA-based CSV file export method as described in any one of claims 1 to 7; The system includes: The entity class definition module is used to define product entity classes using the Java language and to specify the export format for specific fields using annotations. The Export Request Settings module is used to set the request mapping for exporting CSV files in a web project, construct an HTTP response to obtain the output stream, define a basic array containing table headers and field names, call service layer methods to obtain the list of data to be exported, and parse and write the data with the help of utility classes; The header and field name parsing module is used to receive a basic array in the utility class, initialize the header array and field name array, separate the header elements and field name elements by traversing the basic array and store them into the corresponding arrays, and then store the header array and field name array as key-value pairs into a map and return it. The header data writing module is used to concatenate header elements into a string using utility class methods, write UTF-8 BOM bytes and header string bytes to the output stream, and add a newline character. The main data writing module is used to call the corresponding method in the writeRow method of the utility class to assemble data according to the object type. If it is a regular JavaBean, the getter method and field value are obtained through reflection, formatted according to annotations, escaped and then concatenated and written to the output stream. The formatting module is used to define formatting factory classes, return corresponding formatting processor instances based on EscapeType, perform format conversion on different data types in a specified way, and call specific methods to format columns without annotations. A special data writing module is used when the exported object is a Map. In the composeRowDataMap method, it iterates through the array of field names to obtain the field names from the Map, formats them, and then concatenates them to write them to the output stream.

9. An electronic device comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, characterized in that, When the processor executes the program, it implements the steps of the JAVA-based CSV file export method as described in any one of claims 1 to 7.

10. A storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by a processor, it implements the steps of the JAVA-based CSV file export method as described in any one of claims 1 to 7.

Citation Information

Cited By

  • Format conversion method and device for heterogeneous data and medium

    CN121092506A