当前位置:网站首页>Easyexcel and Lombok annotations and commonly used swagger annotations
Easyexcel and Lombok annotations and commonly used swagger annotations
2022-07-02 11:49:00 【linsa_ pursuer】
One 、 introduce jar
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.8</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.8</version>
</dependency>
Two .swagger Commonly used annotations
1、 Annotations related to entities
@ApiModel: Used on entity classes , Annotate the entity class (value: character string , A short alias for the model , Make it easy to identify in the navigation of documents ;description: character string , Additional description of the model )
@ApiModelProperty: Used on attributes , Comment on attributes
2、 Interface related annotations
@Api: Use in controller On , Yes controller Annotate ;
@ApiOperation: Use in API On the way , For the API Make notes , explain API The role of ;
@ApiParam It works on interface methods , Describe single parameter information , Properties are basically the same as @ApiImplicitParam equally , But it can act on methods 、 Parameters 、 Attribute ;
@ApiImplicitParams: Used to contain API A set of parameter annotations , It can be simply understood as a set declaration of parameter annotations ;
@ApiImplicitParam: Use in @ApiImplicitParams In the annotations , It can also be used alone , Explain all aspects of a request parameter , The common options included in this annotation are :
paramType: Where the parameter is placed , contain query、header、path、body as well as form, The most commonly used are the first four .
name: Parameter name ;
dataType: Parameter type , It can be the underlying data type , It can also be a class;
required: Parameter must be passed ;
value: Comment on parameters , Explain the meaning of parameters ;
defaultValue: The default value of the parameter ;
@ApiResponses: Usually used to contain a set of response annotations for interfaces , It can be simply understood as a collection declaration in response to annotations ;
@ApiResponse: Use in @ApiResponses in , Generally used to express a wrong response information
code: namely httpCode, for example 400
message: Information , for example " The request parameter is not filled in "
A few notes :
In order to be in swagger-ui See the output on , At least two comments are required :@Api and @ApiOperation
Even if there is only one @ApiResponse, Also need to use @ApiResponses encase
about @ApiImplicitParam Of paramType:query、form Values in the field need to use @RequestParam obtain , header Values in the field need to use @RequestHeader To get ,path Values in the field need to use @PathVariable To get ,body Values in the field use @RequestBody To get , Otherwise, it may be wrong ; And if the paramType yes body,name It can't be body, Otherwise there is a problem , With... In official documents “If paramType is "body", the name should be "body" Not in conformity with .
3、 ... and .lombok Commonly used annotations
1.setter、getter Method
@Data
2. All parameter constructors
@AllArgsConstructor
3. Parameterless constructor
@NoArgsConstructor
4. rewrite toSting Method ( Calculate the attributes in the parent class to tostring in )
@ToString(callSuper = true)
5. rewrite equalsAndhashCode Method ( if true Calculate the attributes in the parent class to tostring in )
@EqualsAndHashCode(callSuper = false)
6. journal
@Slf4j : Annotation on class , Provide the class with a property named log Of log4j Log object for
@Log4j : Annotation on class , Provide the class with a property named log Of log4j Log object for
Four .easyExcel annotation
Class annotation
1. Heading styles
@HeadStyle
Parameters meaning
dataFormat Date format
hidden Set cells to hide with this style
locked Set cells to use this style to lock
quotePrefix Add... In front of the cell ` Symbol , Numbers or formulas will be displayed as strings
horizontalAlignment Set whether to center horizontally
wrapped Sets whether the text should wrap . Set this flag to true Make everything in a cell visible by displaying it on multiple lines
verticalAlignment Set whether to center vertically
rotation Set the rotation angle of the text in the cell .03 Version of Excel The rotation angle range is -90°90°,07 Version of Excel The rotation angle range is 0°180°
indent Set the number of spaces in the indented text in the cell
borderLeft Style the left border
borderRight Set the right border style
borderTop Style the top border
borderBottom Set the style of the bottom border
leftBorderColor Set the left border color
rightBorderColor Set the right border color
topBorderColor Set the top border color
bottomBorderColor Set the bottom border color
fillPatternType Set the fill type
fillBackgroundColor Set background color
fillForegroundColor Set the foreground
shrinkToFit Set auto cell auto size
2. Title height
@HeadRowHeight(value = 15)
3. Title font format
@HeadFontStyle
Parameters meaning
fontName Set font name
fontHeightInPoints Set font height
italic Set whether the font is italicized
strikeout Whether to set the delete line
color Set font color
typeOffset Set offset
underline Set underline
charset Set font encoding
bold Set whether the font is bold
4. Text style
@ContentStyle
Parameters meaning
dataFormat Date format
hidden Set cells to hide with this style
locked Set cells to use this style to lock
quotePrefix Add... In front of the cell ` Symbol , Numbers or formulas will be displayed as strings
horizontalAlignment Set whether to center horizontally
wrapped Sets whether the text should wrap . Set this flag to true Make everything in a cell visible by displaying it on multiple lines
verticalAlignment Set whether to center vertically
rotation Set the rotation angle of the text in the cell .03 Version of Excel The rotation angle range is -90°90°,07 Version of Excel The rotation angle range is 0°180°
indent Set the number of spaces in the indented text in the cell
borderLeft Style the left border
borderRight Set the right border style
borderTop Style the top border
borderBottom Set the style of the bottom border
leftBorderColor Set the left border color
rightBorderColor Set the right border color
topBorderColor Set the top border color
bottomBorderColor Set the bottom border color
fillPatternType Set the fill type
fillBackgroundColor Set background color
fillForegroundColor Set the foreground
shrinkToFit Set auto cell auto size
5. Text line height
@ContentRowHeight(value = 15)
6. Text font style
@ContentFontStyle
Parameters meaning
fontName Font name
fontHeightInPoints Font height
italic Is it italicized
strikeout Whether to set delete horizontal line
color The font color
typeOffset Offset
underline Underline
bold Is it bold
charset Coding format
7. Column width - Commonly used annotations
@ColumnWidth(30)
8. Ignore uncommented - Don't export
@ExcelIgnoreUnannotated
9. text merge
@OnceAbsoluteMerge
firstRowIndex // The initial line
lastRowIndex // The last line
firstColumnIndex // Initial column
lastColumnIndex // The last column
Attribute annotation
10. Setting per column - Commonly used annotations
@ExcelProperty
Parameters meaning
value Column name
index Column number (index Than order first )
order Column sorting
converter converter ( It's usually not necessary to set )
Such as :@ExcelProperty(value = " Gender ", order = 4, index = 0, converter = SexConverter.class) Gender converter needs to be customized , See the example in part IV below for details
11. Ignore item - Don't export
ExcelIgnore
12. Column width
@ColumnWidth(60)
13. text merge
@ContentLoopMerge
eachRow // Merger line
columnExtend // Merge Columns
5、 ... and . Examples demonstrate
1. Gender converter SexConverter( Optional needs )
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
public class SexConverter implements Converter<Integer> {
@Override
public Class supportJavaTypeKey() {
return Integer.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public Integer convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return " male ".equals(cellData.getStringValue()) ? 1 : 0;
}
@Override
public CellData convertToExcelData(Integer value, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return new CellData(value.equals(1) ? " male " : " Woman ");
}
}
2.PersonDTO
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.*;
import io.swagger.annotations.ApiModel;
import lombok.*;
@ApiModel(" Export business objects ")
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString(callSuper = true)
@HeadStyle(wrapped = false,fillForegroundColor = 13)
@HeadFontStyle(fontHeightInPoints = 10)
@ColumnWidth(30)
public class PersonDTO {
@ExcelProperty(value = " Job number ", order = 1) // Name , Column sorting - Commonly used annotations
String num;
@ExcelProperty(value = " full name ", order = 2)
String name;
@ExcelProperty(value = " Age ", order = 3)
int age;
@ExcelProperty(value = " Gender ", order = 4, index = 0, converter = SexConverter.class) // Name , Column sorting , Column number , Data conversion mode . If index and order All definitions , With index Subject to , It's usually not necessary to set converter
@ColumnWidth(60)
int sex;
@ExcelIgnore // Ignore item - Don't export
long id;
}
3.Excel Import listener ( Optional needs )
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import java.util.ArrayList;
import java.util.List;
public class ExcelListener extends AnalysisEventListener<PersonDTO> {
// Read data initialization value
private static final int BATCH_COUNT = 50;
List<PersonDTO> list = new ArrayList<PersonDTO>();
@Override
public void invoke(PersonDTO personDTO, AnalysisContext analysisContext) {
list.add(personDTO);
// achieve BATCH_COUNT 了 , Need to store the database once , Prevent tens of thousands of data in memory , Easy to OOM
if (list.size() >= BATCH_COUNT) {
saveData();
// Storage complete cleaning list
list.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
if (list.size() == 0) {
return;
}
saveData();
System.out.println(" All data analysis completed !");
}
/**
* Plus the storage database
*/
public void saveData() {
System.out.println(list);
}
}
4. Test class Test
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Slf4j
public class Test {
public static void main(String[] args) throws Exception {
System.out.println("test");
log.error("log-test");
List<PersonDTO> persons = new ArrayList<>();
PersonDTO personOne = new PersonDTO();
personOne.setAge(1);
personOne.setName("Linsa");
personOne.setNum("111");
personOne.setSex(1);
persons.add(personOne);
PersonDTO personTwo = new PersonDTO();
personTwo.setAge(18);
personTwo.setName("Rose");
personTwo.setNum("222");
personTwo.setSex(2);
persons.add(personTwo);
// Get the temporary directory
String tempdir = "D:\\tmp\\";
String fileNameOne = "One_ file .xlsx";
String fileNameTwo = "Two_ file .xlsx";
File writerFileOne = new File(tempdir, fileNameOne);
writerFileOne.createNewFile();
File writerFileTwo = new File(tempdir, fileNameTwo);
writerFileTwo.createNewFile();
// export Excel
EasyExcel.write(writerFileOne).head(PersonDTO.class).sheet("sheet1").doWrite(persons);
// Import Excel
EasyExcel.read(writerFileOne, PersonDTO.class, new ExcelListener()).sheet().doRead();
// export Excel
writeExcel(writerFileTwo, persons.get(0), persons);
// Import Excel
readExcel(writerFileTwo);
}
private static void writeExcel(File writerFile, PersonDTO person, List<PersonDTO> persons) {
ExcelWriter excelWriter = EasyExcel.write(writerFile).build();
WriteSheet sheet1 = EasyExcel.writerSheet(0, "sheet1")
.head(PersonDTO.class).build();
WriteSheet sheet2 = EasyExcel.writerSheet(1, "sheet2")
.head(PersonDTO.class).build();
excelWriter.write(Arrays.asList(person), sheet1);
excelWriter.write(persons, sheet2);
excelWriter.finish(); // Write excel end
}
private static void readExcel(File writerFile) {
String sheetName = EasyExcel.read(writerFile).build().excelExecutor().sheetList().get(0).getSheetName();
System.out.println("Excel name :" + sheetName);
// headRowNumber(1)-Excel Read from the first few lines
List<PersonDTO> listOne = EasyExcel.read(writerFile).head(PersonDTO.class).sheet(0).headRowNumber(1).doReadSync();
System.out.println("sheet1 data :" + listOne);
List<PersonDTO> listTwo = EasyExcel.read(writerFile).head(PersonDTO.class).sheet(1).headRowNumber(1).doReadSync();
System.out.println("sheet2 data :" + listTwo);
}
}
边栏推荐
- bedtools使用教程
- Tiktok overseas tiktok: finalizing the final data security agreement with Biden government
- to_ Bytes and from_ Bytes simple example
- 进入前六!博云在中国云管理软件市场销量排行持续上升
- 通讯录的实现(文件版本)
- [visual studio 2019] create MFC desktop program (install MFC development components | create MFC application | edit MFC application window | add click event for button | Modify button text | open appl
- Programmer growth Chapter 6: how to choose a company?
- Cluster Analysis in R Simplified and Enhanced
- HOW TO CREATE AN INTERACTIVE CORRELATION MATRIX HEATMAP IN R
- The position of the first underline selected by the vant tabs component is abnormal
猜你喜欢

II Stm32f407 chip GPIO programming, register operation, library function operation and bit segment operation

Tiktok overseas tiktok: finalizing the final data security agreement with Biden government

ESP32存储配网信息+LED显示配网状态+按键清除配网信息(附源码)

pgsql 字符串转数组关联其他表,匹配 拼接后原顺序展示

Tdsql | difficult employment? Tencent cloud database micro authentication to help you

excel表格中选中单元格出现十字带阴影的选中效果

揭露数据不一致的利器 —— 实时核对系统

数字化转型挂帅复产复工,线上线下全融合重建商业逻辑

电脑无缘无故黑屏,无法调节亮度。

HOW TO ADD P-VALUES ONTO A GROUPED GGPLOT USING THE GGPUBR R PACKAGE
随机推荐
Skills of PLC recorder in quickly monitoring multiple PLC bits
Tiktok overseas tiktok: finalizing the final data security agreement with Biden government
行業的分析
php 根据经纬度查询距离
pgsql 字符串转数组关联其他表,匹配 拼接后原顺序展示
C # method of obtaining a unique identification number (ID) based on the current time
BEAUTIFUL GGPLOT VENN DIAGRAM WITH R
GGHIGHLIGHT: EASY WAY TO HIGHLIGHT A GGPLOT IN R
HOW TO EASILY CREATE BARPLOTS WITH ERROR BARS IN R
Cmake cross compilation
GGPLOT: HOW TO DISPLAY THE LAST VALUE OF EACH LINE AS LABEL
【多线程】主线程等待子线程执行完毕在执行并获取执行结果的方式记录(有注解代码无坑)
YYGH-BUG-05
What is the relationship between digital transformation of manufacturing industry and lean production
Some problems encountered in introducing lvgl into esp32 Arduino
flutter 问题总结
PowerBI中导出数据方法汇总
QT获取某个日期是第几周
MySQL comparison operator in problem solving
PYQT5+openCV项目实战:微循环仪图片、视频记录和人工对比软件(附源码)