This is the 30th day of my participation in the More Text Challenge. For more details, see more text Challenge

Javaweb development data import and export is very common, each time we need to write a lot of code, so I want to write some general methods, have been on the Internet to sort out some general methods, recently saw a more brief introduction of a cow on the Internet, I took to sort out.Copy the code

The premise

  • Believe that a lot of friends just entered the field are flow water programming! Develop the requirements directly. But the result is code that is not easy to maintain. A slight change in demand may bring a disastrous recovery! Refactoring, as it’s called, is simply not maintaining your own code because it’s cluttered
  • Java provides a technique called annotations that can be used to categorize attributes or annotate methods! We then reverse the execution based on the annotations. Today we are through annotations to achieve our usual poI-based import and export functions
  • On the basis of POI, we can easily implement the import and export of data. But every time the most annoying is to export data fields and table header in the list of the corresponding relationship and the record of table header information, including import is the same need to maintain the mapping relationship between Excel and our data attributes! Can we maintain this level of mapping through annotations?

Configuration annotations

  • So far we’ve seen the use of Java annotations, and now we’re using them to simplify the cumbersome uploading and downloading of Excel in Java Web. Due to limited time today, I first implemented the Download of Excel (Excel export).

  • Above is a simplified diagram of our annotation class. The parameters specify the name of the table header + the width of the column in which the table header is used + whether the column is in plain text + how the column is encrypted + the format of the special text. And with that simple entity class, we’ve done the mapping. Internal is actually a Hash table maintenance!

Data entity class

  • With the above annotation our entity class is very simple, just add the annotation to the property fields of the javabeans we normally build.

  • The value of the property in the ExportConfig annotation can be left unset. The default value is not set. So once you’re done here, you start writing and exporting.

Excel export

  • Now how do we get our annotations? The previous article covered that. We need to get the fields of our Javabeans first.
for (Field field : _class.getDeclaredFields())
Copy the code
  • It may appear that our Javabean data is not fully accounted for. So here we have to see if this field has a value.
property = BeanUtils.getProperty(data.get(0), field.getName());
Copy the code
  • We are getting the annotation of the field if it is worthwhile.
ExportConfig config = field.getAnnotation(ExportConfig.class);
Copy the code
  • Finally we begin to look at the annotated information that exists in the information class Exportitem.java
items.add(new ExportItem.$Build()
                            .setField(field.getName())
                            .setDisplay(
                                    "field".equals(config.value()) ? field
                                            .getName() : config.value())
                            .setWidth(config.width())
                            .setIsExport(config.isExport())
                            .setContent(config.blankContent())
                            .setFieldTypeName(field.getClass().getSimpleName())
                            .setFormat(config.format())
                            .create());
Copy the code
  • The ExportItem class is also simple. A class that copied itself to implement the chain operation. There’s nothing to explain here. At this point our header display setup is complete. The next step of course is to iterate through the list collection data. Of course, set the header style before you iterate.
ExportItem exportItem = items.get(index); Cell Cell = headrow.createcell (index); Sheet.setcolumnwidth (index, (short) (exportitem.getwidth () * 35.7)); cell.setCellValue(exportItem.getDisplay()); CellStyle style = handler.getHeadCellStyle(wb); if (style ! = null) { cell.setCellStyle(style); }Copy the code
  • Before setting the body we need to check the annotation information class to get the style of the column (whether it is plain text or not).
if (exportItem.getIsExport())
Copy the code
  • After setting the content we need to set the style according to the cell format of the annotation
setStyleByType(wb,exportItem.getFormat());
Copy the code

Excel output

 fileName += getExcelSuffix(type);
                _response.setContentType(getContentType(type));
                _response.setHeader(
                        "Content-disposition",
                        "attachment; filename="
                                + new String(fileName.getBytes("gbk"), "iso8859-1"));

                if (out == null)
                {
                    out = _response.getOutputStream();
                }
                wb.write(out);
                out.flush();
                out.close();
Copy the code

The jar

Jar Log jar package servlet-api.jar The jar package poi-3.9.jar operation table jar package pi-ooxmL-3.12.jar XSSFWorkbook is not required in the Web project Handle excel 2007 and aboveCopy the code

The calling code

  • The rest is pretty simple. We also use annotations to simplify the repetition of our code! Through annotations can be repeated operations by the computer operation! This in our maintenance is also a lot more convenient!
List<ExcelUser> list = adminManageServiceI.getUsers(ConstantUtil.ADMIN_ID); $Brower(exceluser.class, response).toexcel (list, "user information ");Copy the code

The effect