Annotations are an advanced feature of Java, and Spring has developed a set of “annotation-driven programming” based on annotations.

That sounds lofty, but it’s a framework thing. Can we also use good annotations?

Indeed, we rarely have the opportunity to write our own annotations, so we don’t know what annotations are, let alone use them well.

In this case, we start from the specific work, the development of an Excel export function. I’m sure that after you understand this example, you will understand how annotations are used.

Excel export – Requirements disassembly

In the background management system, it is often necessary to export data to Excel.

For example, after the Double 11, the sales department should input the commodity order into Excel, and the financial department should input the payment order into Excel, and then each department will summarize and analyze, and finally find a time to discuss how to improve the company’s service.

You see, there are tens of thousands of orders for Double Eleven. It takes at least three or four days to input them manually, and it is very easy to make mistakes. So, you have to develop Excel export capabilities.

So, how do you do that?

As we mentioned last time, annotations need to be defined, used, and read in order to work. This time, we will use the three features of annotations to achieve Excel export function, the design process is like this.

The first step is to create different Excel models. After The Double 11, the sales department needs the order data, and the financial department needs the payment data. The Excel sheets of the two departments must be different, so we have to help each department create different Excel models, so that they can get the data they want.

Step two, we are going to export the Excel table based on the Excel model.

This should give you an idea of the design process for Excel exports. Next, we will implement this function step by step.

Creating an Excel model

Creating an Excel model involves the definition and use of the three elements of annotations.

First, define Excel annotations, and let’s go straight to the key code.

@target ({elementtype.field}) @Retention(retentionPolicy.runtime) public @interface ExcelField {/** * export header */ String title(); */ int sort() default 0; /** * align (0: automatic; 1. Keep to the left. 2: center. */ int align() default 0; }Copy the code

There are two meta-annotations here: @retention and @target. @target indicates that this annotation can only be placed on member variables; @retention means that the annotation will be loaded into JVM memory and we can use reflection to read the annotation.

In addition, the annotation also has three member variables, respectively corresponding to Excel field title, field sorting, alignment, so that you can fine tune the table. At this point, you’re done defining Excel annotations.

Next, with annotations, we’ll look directly at the code.

Public class OrderModel {@excelField (title = "orderNo ", align = 2, sort = 20) private String orderNo; @excelfield (title = "amount ", align = 2, sort = 20) private String amount; Private Date createTime; // omit getter/setter methods}Copy the code

The order model has 3 fields: order number, amount, and creation time, but here the annotation is only added to order number and amount to indicate that these two fields are exported to Excel, and the creation time is ignored. You can see the picture here.

At this point, we have defined annotations, used annotations, and have an Excel model. But in order to achieve the export function, you must also generate Excel tables based on this model.

Reading Excel model

Reading an Excel model involves reading one of the three elements of annotation. We need to read the annotations to generate the Excel sheet, which is divided into three main steps: initialize the Excel sheet object – > write data to the Excel sheet object – > output file.

The first step is to initialize the Excel table object. In this step, we will generate an Excel table object based on the Excel model. We will create these things: title, table header, style, and so on. Let’s look at the code.

public class ExcelExporter { // ... Omit countless code / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * initializes the Excel table object * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / / constructor * @ param title title form, the "null", Public ExcelExporter(String title, Class<? > CLS) {list Field[] fs = cls.getDeclaredFields(); for (Field f : fs) { ExcelField ef = f.getAnnotation(ExcelField.class); if (ef ! = null) { annotationList.add(new Object[]{ef, f}); } } annotationList.sort(comparing(o -> ((ExcelField) o[0]).sort())); List<String> headerList = new ArrayList<>(); for (Object[] os : annotationList) { String t = ((ExcelField) os[0]).title(); headerList.add(t); } // Initialize excel tables: create excel tables, add table titles, create table headers, etc. Initialize (title, headerList); }}Copy the code

At initialization, we read the annotations from the Excel model object and get a list of annotations. Then, from the annotation list, read the title- field title; Finally, initialize the Excel table object, including creating the Excel table object, adding the table title, creating the table header, and adding the style.

Second, write the data to the Excel table object. In this step, we write the Java list data to the Excel table object, so that the data can become the Excel table row information. Let’s look at the code.

Public class ExcelExporter {/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * initializes the Excel table object * * * * * * * * * * * * * * * * * * * * * * * * * * * * / / /... Omit countless code / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * writing data to Excel table object * * * * * * * * * * * * * * * * * * * * * * * * * * * * / / write data * * * * @ * / return list data list Public <E> excelsetdatalist (List<E> List) {for (E dataObj: List) {// addRow Row = this.addrow (); // Get data and write to cell int cellNo = 0; For (Object[] OS: annotationList) {// Get Object value = null; try { value = Reflections.invokeGetter(dataObj, ((Field) os[1]).getName()); } catch (Exception ex) { log.info(ex.toString()); value = ""; } if (value == null) { value = ""; } // Write cell ExcelField ef = (ExcelField) OS [0]; this.addCell(row, cellNo++, value, ef.align()); } } return this; }}Copy the code

We pass in a dataList list and loop through the dataList. In this loop, we write data into the Excel object by creating a blank row, using annotations to fetch values from member variables, and finally writing them into the Excel cell.

The third step is to export the file. In this step, the Excel object becomes a file. Let’s look at the final code.

Public class ExcelExporter {/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * initializes the Excel table object * * * * * * * * * * * * * * * * * * * * * * * * * * * * / / /... Omit the countless code / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * writing data to Excel table objects * * * * * * * * * * * * * * * * * * * * * * * * * * * * / / /... Omit countless code / * * * * * * * * * * * * * * * * * * * * * * * * * * * * * output related * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / / output to the output file name, file * @ param fileName Add the absolute path */ public ExcelExporter writeFile(String fileName) throws IOException {FileOutputStream OS = new FileOutputStream(fileName); this.write(os); return this; }}Copy the code

Output file is nothing to say, just specify the name of the file, and then output the file to the specified location.

At this point, I’m done reading my Excel model.

Of course, reading the Excel model involves reading annotations, which is the hardest part of annotations to understand because reading annotations uses another advanced Java feature, reflection. Also, annotations are generally used to simplify the business, and it is difficult to use annotations well without deep understanding of the business.

Limited to space, I only talked about the most core code, the complete code of the project in the end of the link, you can have a good look.

Write in the last

For annotations to work, there are three elements: define, use, and read. This article uses the three elements of annotations to achieve Excel export function.

This is a two-step process. The first step is to create an Excel model, which involves the definition and use of annotations in the three elements. The second step is to read the Excel model, which involves reading the annotations in the three elements.

In summary, annotations are generally used to simplify the business, and to use annotations well, you must not only be proficient in high-level Java usage, but also have a deep understanding of the business.

Source: www.tuicool.com/articles/Ez…