当前位置:网站首页>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);
}
}
边栏推荐
猜你喜欢
The position of the first underline selected by the vant tabs component is abnormal
微信小程序利用百度api达成植物识别
Is the Ren domain name valuable? Is it worth investing? What is the application scope of Ren domain name?
Pyqt5+opencv project practice: microcirculator pictures, video recording and manual comparison software (with source code)
CentOS8之mysql基本用法
ESP32 Arduino 引入LVGL 碰到的一些问题
多文件程序X32dbg动态调试
基于Hardhat和Openzeppelin开发可升级合约(一)
Never forget, there will be echoes | hanging mirror sincerely invites you to participate in the opensca user award research
2022年遭“挤爆”的三款透明LED显示屏
随机推荐
II Stm32f407 chip GPIO programming, register operation, library function operation and bit segment operation
HOW TO EASILY CREATE BARPLOTS WITH ERROR BARS IN R
HOW TO ADD P-VALUES TO GGPLOT FACETS
Resources reads 2D texture and converts it to PNG format
liftOver进行基因组坐标转换
Power Spectral Density Estimates Using FFT---MATLAB
对毕业季即将踏入职场的年轻人的一点建议
HOW TO CREATE A BEAUTIFUL INTERACTIVE HEATMAP IN R
Attribute acquisition method and operation notes of C # multidimensional array
MySQL basic statement
php 二维、多维 数组打乱顺序,PHP_php打乱数组二维数组多维数组的简单实例,php中的shuffle函数只能打乱一维
从ros1到ros2配置的一些东西
Is it safe to open a stock account through the QR code of the securities manager? Or is it safe to open an account in a securities company?
原生方法合并word
BEAUTIFUL GGPLOT VENN DIAGRAM WITH R
ESP32 Arduino 引入LVGL 碰到的一些问题
Summary of flutter problems
Is the Ren domain name valuable? Is it worth investing? What is the application scope of Ren domain name?
[visual studio 2019] create and import cmake project
JS——每次调用从数组里面随机取一个数,且不能与上一次为同一个