Java工具类02文件读写之Excel读写Excel4J

java

1.poi

poi用作读取Excel 需要自己封装读取方法,对excel表格循环读取。灵活但是代码量大,维护困难。

 1 <dependency>

2 <groupId>org.apache.poi</groupId>

3 <artifactId>poi</artifactId>

4 <version>3.17</version>

5 </dependency>

6 <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml 支持2007以上版本-->

7 <dependency>

8 <groupId>org.apache.poi</groupId>

9 <artifactId>poi-ooxml</artifactId>

10 <version>3.17</version>

11 </dependency>

简单介绍,poi可读取当前 workbook--sheet-row/cell,根据需要循环读取,这里不做赘述。

1 import org.apache.poi.hssf.usermodel.HSSFCell;

2 import org.apache.poi.hssf.usermodel.HSSFRow;

3 import org.apache.poi.hssf.usermodel.HSSFSheet;

4 import org.apache.poi.hssf.usermodel.HSSFWorkbook;//Read the Excel 2003

5 import org.apache.poi.xssf.usermodel.XSSFCell;

6 import org.apache.poi.xssf.usermodel.XSSFRow;

7 import org.apache.poi.xssf.usermodel.XSSFSheet;

8 import org.apache.poi.xssf.usermodel.XSSFWorkbook;//Read the Excel 2017 or 2010

2.Excel4J

3.0版本的支持Excel和Csv的读写,使用简单,功能强大,通过反射原理在class反射对象中找到每一个注解对应的属性,使用set方法将excel每一对应字段的值循环set给对应属性。

1  <dependencies>

2 <dependency>

3 <groupId>com.github.crab2died</groupId>

4 <artifactId>Excel4J</artifactId>

5 <version>3.0.0-Alpha</version>

6 </dependency>

2.1excel读取

通过ExcelUtils.getInstance().readExcel2Object(文件路径,clazz);常用方法读取excel和csv,返回对象集合

 

标注格式如下:

1 //注解格式

2 @ExcelField(title = "是否开启", readConverter = IsRunReadConvert.class)

3 private boolean run;

4 @ExcelField(title = "用例名称")

5 private String caseName;

读取,一行搞定:

 1 List<标注类>list = ExcelUtils.getInstance().readExcel2Object(文件路径,标注类的class); 

 2.2excel写入

根据标注写入

1 List list =new ArrayList<String>();

2 list.add(new ExcelWriteTest02("否", "test01", "hello", "www.taobao.com", 6));

3 ExcelUtils.getInstance().exportObjects2Excel(list, ExcelWriteTest02.class, filepath);

传入的是对象列表,class对象以及文件路径

根据标注写入时,可以自定义顺序:

 1 //按order顺序

2 @ExcelField(title = "是否开启",order = 4)

3 private String run;

4 @ExcelField(title = "用例名称",order = 3)

5 private String name;

6 @ExcelField(title = "类型",order = 2)

7 private String type;

8 @ExcelField(title = "地址",order = 1)

9 private String url;

10 @ExcelField(title = "顺序",order = 5)

11 private int order;

结果如下:

 

 2.3csv写入

也是一行搞定

1 ExcelUtils.getInstance().exportObjects2CSV(list, ExcelWriteTest02.class, filepath);

结果展示:

 

 

 

以上是 Java工具类02文件读写之Excel读写Excel4J 的全部内容, 来源链接: utcz.com/z/391922.html

回到顶部