方法一:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
实体类
@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value="Tea对象", description="")
@AllArgsConstructor
public class Tea implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "tid", type = IdType.AUTO)
private Integer tid;
private String name;
}
package com.example.try_test.entity;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author : kkk
* @since : 2022/7/14
*/
public class Excel {
private static final Logger LOGGER = LoggerFactory.getLogger(Excel.class);
//模拟数据
public static List<Tea> getTea() {
Tea tea = new Tea(1, "qweqwe");
Tea tea2 = new Tea(1, "qweqwe2");
Tea tea3 = new Tea(1, "qweqwe3");
Tea tea4 = new Tea(1, "qweqwe4");
Tea tea5 = new Tea(1, "qweqwe5");
Tea tea6 = new Tea(1, "qweqwe");
Tea tea7 = new Tea(1, "qweqwe7");
Tea tea8 = new Tea(1, "qweqwe8");
List<Tea> list = new ArrayList<>();
list.add(tea);
list.add(tea2);
list.add(tea3);
list.add(tea4);
list.add(tea5);
list.add(tea6);
list.add(tea7);
list.add(tea8);
return list;
}
public static void main(String[] args) {
FileOutputStream outputStream = null;
try {
//创建一个工作本
Workbook wb = new XSSFWorkbook();
//为文本创建文本样式
CellStyle style = wb.createCellStyle();
XSSFFont font = new XSSFFont();
font.setBold(true);
font.setColor(Font.COLOR_RED);
style.setFont(font);
style.setAlignment(HorizontalAlignment.CENTER);
Sheet sheet = wb.createSheet("qweqwe11");
//创建一行
Row row = sheet.createRow(0);
//为首行设置标题和样式
Cell cell = row.createCell(0);
cell.setCellValue("教师编号");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellStyle(style);
cell.setCellValue("教师名称");
//获取列表内容
List<Tea> tea = getTea();
int len = tea.size();
for (int i = 0; i < len; i++) {
//循环为每一行设置信息
Tea tea1 = tea.get(i);
row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(tea1.getTid());
row.createCell(1).setCellValue(tea1.getName());
}
LOGGER.info("输出结束");
outputStream = new FileOutputStream("D:\\excel\\qweqwe.xlsx");
wb.write(outputStream);
} catch (IOException e) {
LOGGER.error("出错了!!!");
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
结果:
方法二:AOP(不严谨,请问观看)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Cat {
private Integer catId;
private Double weigth;
private Double height;
private Integer age;
private String color;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CatCopy {
@ExcelResource(value = "宠物猫编号")
private Integer catId;
@ExcelResource(value = "宠物猫重量")
private Double weigth;
@ExcelResource(value = "宠物猫高度")
private Double height;
@ExcelResource(value = "宠物猫颜色")
private String color;
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelResource {
String value() default "";
}
@Getter
public enum ExcelTypeEnum {
CAT(12,"小猫")
;
private Integer code;
private String desc;
ExcelTypeEnum(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
}
@Service
public class CatService {
private static final Logger LOGGER= LoggerFactory.getLogger(CatService.class);
public static List<Cat> getCat()
{
List<Cat> list=new ArrayList<>();
Cat cat = new Cat(1, 12.0, 20.0, 5, "红色");
Cat cat2 = new Cat(2, 12.0, 20.0, 5, "红色");
Cat cat3 = new Cat(3, 12.0, 20.0, 5, "红色");
Cat cat4 = new Cat(4, 12.0, 20.0, 5, "黑色");
Cat cat5 = new Cat(5, 12.0, 20.0, 5, "白色");
Cat cat6 = new Cat(6, 12.0, 20.0, 5, "黑白色");
list.add(cat6);
list.add(cat);
list.add(cat2);
list.add(cat3);
list.add(cat4);
list.add(cat5);
return list;
}
public static <T> String outPutExcel(String path,ExcelTypeEnum type,String fileName)
{
//创建一个工作簿,在这里,工作簿有下表的,比如一个excel可能有几个文件
XSSFWorkbook workbook = new XSSFWorkbook();
//这里就是excel中的一个文件
XSSFSheet sheet = workbook.createSheet("宠物信息表");
//设置工作簿小格样式
XSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
XSSFFont font = workbook.createFont();
//设置字体样式
font.setBold(true);
font.setFontName("黑体");
font.setFontHeightInPoints((short) 12);
style.setFont(font);
XSSFRow row = sheet.createRow(0);
//通过自定义注解获取注解的信息
List<String> values = getNameAndValue(getObject(type));
int len=values.size();
//设置标题和其样式
XSSFCell cell=null;
for(int i=0;i<len;i++)
{
cell = row.createCell(i);
cell.setCellStyle(style);
cell.setCellValue(values.get(i));
}
//具体内容的样式重新创建
XSSFCellStyle dataStyle = workbook.createCellStyle();
dataStyle.setAlignment(HorizontalAlignment.CENTER);
List<Cat> cat = getCat();
List list = changeObject(cat, type);
int catLen=list.size();
for(int i=0;i<catLen;i++)
{
row=sheet.createRow(i+1);
CatCopy catCopy = (CatCopy) list.get(i);
row.createCell(0).setCellValue(catCopy.getCatId());
row.createCell(1).setCellValue(catCopy.getWeigth());
row.createCell(2).setCellValue(catCopy.getHeight());
row.createCell(3).setCellValue(catCopy.getColor());
}
FileOutputStream fileOutputStream=null;
try {
String name=path+ "\\"+fileName;
fileOutputStream=new FileOutputStream(name);
workbook.write(fileOutputStream);
}catch (IOException e) {
}finally {
if(fileOutputStream!=null){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static<T> List changeObject(List<T> list,ExcelTypeEnum type)
{
switch (type){
case CAT:
{
int len=list.size();
List<CatCopy> list1=new ArrayList<>();
for(int i=0;i<len;i++){
CatCopy catCopy = new CatCopy();
BeanUtils.copyProperties(list.get(i),catCopy);
list1.add(catCopy);
}
return list1;
}
default: return null;
}
}
/**
* 通过切面,获取注解的内容
* 使用LinkedList 保证了数据的顺序性
* @param o
* @return
*/
private static List<String> getNameAndValue(Object o)
{
List<String> list=new ArrayList<>();
//获取属性名称
Field[] fields = o.getClass().getDeclaredFields();
if(fields!=null){
for(Field field:fields)
{
ExcelResource annotation = field.getAnnotation(ExcelResource.class);
if(annotation.value()!=null&&!annotation.value().equals("")) {
list.add(annotation.value());
}
}
}else {
LOGGER.error("不存在成员变量");
return null;
}
return list;
}
public static void main(String[] args) {
outPutExcel("D:\\excel",ExcelTypeEnum.CAT,"ty.xlsx");
}
/**
* 通过枚举类获取实体类信息
* @param type
* @return
*/
public static Object getObject(ExcelTypeEnum type)
{
switch (type){
case CAT: return new CatCopy();
default:
return null;
}
}
}
结果: