当前位置:网站首页>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);
}
}
边栏推荐
- Tdsql | difficult employment? Tencent cloud database micro authentication to help you
- On April 17, 2022, the five heart matchmaker team received double good news
- Amazon cloud technology community builder application window opens
- Precautions for scalable contract solution based on openzeppelin
- RPA进阶(二)Uipath应用实践
- Tidb DM alarm DM_ sync_ process_ exists_ with_ Error troubleshooting
- 动态内存(进阶四)
- C#基于当前时间,获取唯一识别号(ID)的方法
- excel表格中选中单元格出现十字带阴影的选中效果
- 由粒子加速器产生的反中子形成的白洞
猜你喜欢

ESP32 Arduino 引入LVGL 碰到的一些问题

PLC-Recorder快速监控多个PLC位的技巧

HOW TO ADD P-VALUES TO GGPLOT FACETS

How to Create a Nice Box and Whisker Plot in R

How to Create a Nice Box and Whisker Plot in R

On April 17, 2022, the five heart matchmaker team received double good news

CentOS8之mysql基本用法

R HISTOGRAM EXAMPLE QUICK REFERENCE

VS2019代码中包含中文内容导致的编译错误和打印输出乱码问题

How to Add P-Values onto Horizontal GGPLOTS
随机推荐
可升级合约的原理-DelegateCall
MySQL linked list data storage query sorting problem
C#基于当前时间,获取唯一识别号(ID)的方法
Tdsql | difficult employment? Tencent cloud database micro authentication to help you
HOW TO CREATE A BEAUTIFUL INTERACTIVE HEATMAP IN R
亚马逊云科技 Community Builder 申请窗口开启
Cluster Analysis in R Simplified and Enhanced
YYGH-BUG-05
可昇級合約的原理-DelegateCall
Wechat applet uses Baidu API to achieve plant recognition
Never forget, there will be echoes | hanging mirror sincerely invites you to participate in the opensca user award research
Beautiful and intelligent, Haval H6 supreme+ makes Yuanxiao travel safer
行業的分析
QT获取某个日期是第几周
Take you ten days to easily finish the finale of go micro services (distributed transactions)
Liftover for genome coordinate conversion
Thesis translation: 2022_ PACDNN: A phase-aware composite deep neural network for speech enhancement
Analyse de l'industrie
HOW TO ADD P-VALUES ONTO A GROUPED GGPLOT USING THE GGPUBR R PACKAGE
How to Visualize Missing Data in R using a Heatmap