JAVA基于注解导入导出Excel
新人小白,在此记录一下.用到的包是poi
excel导入导出工具类
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.guohe.framework.util.excel.ExcelExporter;
import org.junit.Assert;
/**
* excel导入导出工具类 (基于注解)
*
* @author jiaxingHuang
* @version 1.0 2014-08-20
* @since 1.0
*/
public class ExcelNoteUtil<T> implements Serializable {
private static final long serialVersionUID = 551970754610248636L;
private Class<T> clazz;
public ExcelNoteUtil(Class<T> clazz) {
this.clazz = clazz;
}
private static final String EXTENSION_XLS = "xls";
private static final String EXTENSION_XLSX = "xlsx";
public static final short TITLE_BG = IndexedColors.WHITE.getIndex();
public static final short TITLE_FG = IndexedColors.BLACK.getIndex();
/***
* <pre>
* 取得Workbook对象(xls和xlsx对象不同,不过都是Workbook的实现类)
* xls:HSSFWorkbook
* xlsx:XSSFWorkbook
* @param filePath
* @return
* @throws IOException
* </pre>
*/
private Workbook getWorkbook(String filePath) throws IOException {
Workbook workbook = null;
InputStream is = new FileInputStream(filePath);
// System.out.println(filePath.endsWith(EXTENSION_XLS));
// System.out.println(filePath.endsWith(EXTENSION_XLSX));
if (filePath.endsWith(EXTENSION_XLS)) {
workbook = new HSSFWorkbook(is);
} else if (filePath.endsWith(EXTENSION_XLSX)) {
workbook = new XSSFWorkbook(is);
}
return workbook;
}
/**
* 将excel表单数据源的数据导入到list
*
* @param sheetName
* 工作表的名称
* @param input
* java输入流
*/
public List<T> getExcelToList(String sheetName, InputStream input) throws Exception {
List<T> list = new ArrayList<T>();
try {
HSSFWorkbook book = new HSSFWorkbook(input);
HSSFSheet sheet = null;
// 如果指定sheet名,则取指定sheet中的内容.
if (StringUtils.isNotBlank(sheetName)) {
sheet = book.getSheet(sheetName);
}
// 如果传入的sheet名不存在则默认指向第1个sheet.
if (sheet == null) {
sheet = book.getSheetAt(0);
}
// 得到数据的行数
int rows = sheet.getPhysicalNumberOfRows();
// 有数据时才处理
if (rows > 0) {
// 得到类的所有field
Field[] allFields = clazz.getDeclaredFields();
// 定义一个map用于存放列的序号和field
Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
for (int i = 0, index = 0; i < allFields.length; i++) {
Field field = allFields[i];
// 将有注解的field存放到map中
if (field.isAnnotationPresent(ExcelNote.class)) {
// 设置类的私有字段属性可访问
field.setAccessible(true);
fieldsMap.put(index, field);
index++;
}
}
// 从第2行开始取数据,默认第一行是表头
for (int i = 1, len = rows; i < len; i++) {
// 得到一行中的所有单元格对象.
HSSFRow row = sheet.getRow(i);
Iterator<Cell> cells = row.cellIterator();
T entity = null;
int index = 0;
while (cells.hasNext()) {
// 单元格中的内容.
String c = cells.next().getStringCellValue();
//空单元格 如果为空则continue的话,读到空单元格会把空单元格后面的数据 写入到当前单元格所映射的对象,所以为空的话,不做判断,后面会直接把空插入到对象
// if (!StringUtils.isNotBlank(c)) {
// continue;
// }
if (c.indexOf("合计:") != -1) {
continue;
}
// 如果不存在实例则新建
entity = (entity == null ? clazz.newInstance() : entity);
// 从map中得到对应列的field
Field field = fieldsMap.get(index);
if (field == null) {
continue;
}
// 取得类型,并根据对象类型设置值.
Class<?> fieldType = field.getType();
SimpleDateFormat sdf = new SimpleDateFormat();
//对空单元格的处理
if (String.class == fieldType) {
field.set(entity, String.valueOf(c));
}else if ((Integer.TYPE == fieldType)
|| (Integer.class == fieldType)) {
field.set(entity, Integer.parseInt(c));
} else if ((Long.TYPE == fieldType)
|| (Long.class == fieldType)) {
field.set(entity, Long.valueOf(c));
} else if ((Float.TYPE == fieldType)
|| (Float.class == fieldType)) {
field.set(entity, Float.valueOf(c));
} else if ((Short.TYPE == fieldType)
|| (Short.class == fieldType)) {
field.set(entity, Short.valueOf(c));
} else if ((Double.TYPE == fieldType)
|| (Double.class == fieldType)) {
field.set(entity, Double.valueOf(c));
} else if (Character.TYPE == fieldType) {
if ((c != null) && (c.length() > 0)) {
field.set(entity, Character.valueOf(c.charAt(0)));
}
}else{
field.set(entity, String.valueOf(c));
}
index++;
}
if (entity != null) {
list.add(entity);
}
}
}
} catch (Exception e) {
throw new Exception("将excel表单数据源的数据导入到list异常!", e);
}
return list;
}
/**
* 将list数据源的数据导入到excel表单
*
* @param list
* 数据源
* @param sheetName
* 工作表的名称
* @param output
* java输出流
*/
public Workbook getListToExcel(List<T> list, String sheetName, OutputStream output) throws Exception {
try {
// excel中每个sheet中最多有65536行
int sheetSize = 65536;
// 得到所有定义字段
Field[] allFields = clazz.getDeclaredFields();
List<Field> fields = new ArrayList<Field>();
// 得到所有field并存放到一个list中
for (Field field : allFields) {
if (field.isAnnotationPresent(ExcelNote.class)) {
fields.add(field);
}
}
// 产生工作薄对象
HSSFWorkbook workbook = new HSSFWorkbook();
// header 样式
CellStyle headerCellStyle = getHeaderCellStyle(workbook);
// 内容样式
CellStyle createValueStyle = createValueStyle(workbook, CellStyle.ALIGN_LEFT);
// 取出一共有多少个sheet
int listSize = 0;
if (list != null && list.size() >= 0) {
listSize = list.size();
}
double sheetNo = Math.ceil(listSize / sheetSize);
for (int index = 0; index <= sheetNo; index++) {
// 产生工作表对象
HSSFSheet sheet = workbook.createSheet();
// 设置工作表的名称.
workbook.setSheetName(index, sheetName + index);
HSSFRow row;
HSSFCell cell;// 产生单元格
row = sheet.createRow(0);// 产生一行
/* *********普通列样式********* */
HSSFFont font = workbook.createFont();
for (int i = 0; i < fields.size(); i++) {
Field field = fields.get(i);
ExcelNote excel = field.getAnnotation(ExcelNote.class);
int col = i;
// 根据指定的顺序获得列号
if (StringUtils.isNotBlank(excel.column())) {
col = getExcelCol(excel.column());
}
// 创建列
cell = row.createCell(col);
cell.setCellStyle(headerCellStyle);
//设置列宽
// sheet.setColumnWidth(i, (int) ((excel.name().getBytes().length <= 4 ? 6 : excel.name().getBytes().length) * 1.5 * 256));
// 设置列中写入内容为String类型
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
// 写入列名
cell.setCellValue(excel.name());
// 如果设置了提示信息则鼠标放上去提示.
// if (StringUtils.isNotBlank(excel.prompt())) {
// setHSSFPrompt(sheet, "", excel.prompt(), 1, 100, col, col);
// }
// // 如果设置了combo属性则本列只能选择不能输入
// if (excel.combo().length > 0) {
// setHSSFValidation(sheet, excel.combo(), 1, 100, col, col);
// }
}
/* *************创建内容列*************** */
font = workbook.createFont();
// cellStyle = workbook.createCellStyle();
int startNo = index * sheetSize;
int endNo = Math.min(startNo + sheetSize, listSize);
// 写入各条记录,每条记录对应excel表中的一行
for (int i = startNo; i < endNo; i++) {
row = sheet.createRow(i + 1 - startNo);
T vo = (T) list.get(i); // 得到导出对象.
for (int j = 0; j < fields.size(); j++) {
// 获得field
Field field = fields.get(j);
// 设置实体类私有属性可访问
field.setAccessible(true);
ExcelNote excel = field.getAnnotation(ExcelNote.class);
int col = j;
// 根据指定的顺序获得列号
if (StringUtils.isNotBlank(excel.column())) {
col = getExcelCol(excel.column());
}
// 根据ExcelVOAttribute中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
if (excel.isExport()) {
// 创建cell
cell = row.createCell(col);
cell.setCellStyle(createValueStyle);
// 如果数据存在就填入,不存在填入空格
Class<?> classType = (Class<?>) field.getType();
String value = null;
cell.setCellValue(field.get(vo) == null ? "" : value == null ? String.valueOf(field.get(vo)) : value);
}
}
}
/* *************创建合计列*************** */
HSSFRow lastRow = sheet.createRow((short) (sheet.getLastRowNum() + 1));
for (int i = 0; i < fields.size(); i++) {
Field field = fields.get(i);
ExcelNote excel = field.getAnnotation(ExcelNote.class);
if (excel.isSum()) {
int col = i;
// 根据指定的顺序获得列号
if (StringUtils.isNotBlank(excel.column())) {
col = getExcelCol(excel.column());
}
BigDecimal totalNumber = BigDecimal.ZERO;
for (int j = 1, len = (sheet.getLastRowNum() - 1); j < len; j++) {
HSSFRow hssfRow = sheet.getRow(j);
if (hssfRow != null) {
HSSFCell hssfCell = hssfRow.getCell(col);
if (hssfCell != null && hssfCell.getCellType() == HSSFCell.CELL_TYPE_STRING
&& isFloat(hssfCell.getStringCellValue())) {
totalNumber = add(totalNumber,
BigDecimal.valueOf(Double.valueOf(hssfCell.getStringCellValue())));
}
}
}
HSSFCell sumCell = lastRow.createCell(col);
sumCell.setCellValue(new HSSFRichTextString("合计:" + totalNumber));
}
}
}
output.flush();
workbook.write(output);
output.close();
return workbook;
} catch (Exception e) {
throw new Exception("将list数据源的数据导入到excel表单异常!", e);
}
}
/**
* 将EXCEL中A,B,C,D,E列映射成0,1,2,3
*
* @param col
*/
public static int getExcelCol(String col) {
col = col.toUpperCase();
// 从-1开始计算,字母重1开始运算。这种总数下来算数正好相同。
int count = -1;
char[] cs = col.toCharArray();
for (int i = 0; i < cs.length; i++) {
count += (cs[i] - 64) * Math.pow(26, cs.length - 1 - i);
}
return count;
}
/**
* 设置单元格上提示
*
* @param sheet
* 要设置的sheet.
* @param promptTitle
* 标题
* @param promptContent
* 内容
* @param firstRow
* 开始行
* @param endRow
* 结束行
* @param firstCol
* 开始列
* @param endCol
* 结束列
* @return 设置好的sheet.
*/
public static HSSFSheet setHSSFPrompt(HSSFSheet sheet, String promptTitle, String promptContent, int firstRow, int endRow,
int firstCol, int endCol) {
// 构造constraint对象
DVConstraint constraint = DVConstraint.createCustomFormulaConstraint("DD1");
// 四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
// 数据有效性对象
HSSFDataValidation data_validation_view = new HSSFDataValidation(regions, constraint);
data_validation_view.createPromptBox(promptTitle, promptContent);
sheet.addValidationData(data_validation_view);
return sheet;
}
/**
* 设置某些列的值只能输入预制的数据,显示下拉框.
*
* @param sheet
* 要设置的sheet.
* @param textlist
* 下拉框显示的内容
* @param firstRow
* 开始行
* @param endRow
* 结束行
* @param firstCol
* 开始列
* @param endCol
* 结束列
* @return 设置好的sheet.
*/
public static HSSFSheet setHSSFValidation(HSSFSheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) {
// 加载下拉列表内容
DVConstraint constraint = DVConstraint.createExplicitListConstraint(textlist);
// 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
// 数据有效性对象
HSSFDataValidation data_validation_list = new HSSFDataValidation(regions, constraint);
sheet.addValidationData(data_validation_list);
return sheet;
}
/**
* 字符串转换
* @param str
* @return
*/
public static boolean isEmpty(String str)
{
if ((str == null) || (str.trim().equals("")) || (str.equals("null"))) {
return true;
}
return false;
}
public static String toUpperFirst(String src)
{
char l = Character.toUpperCase(src.charAt(0));
return src.replaceFirst(String.valueOf(src.charAt(0)), String.valueOf(l));
}
public static boolean isNotEmpty(String str)
{
return !isEmpty(str);
}
//类型转换
public static boolean isFloat(String numStr) {
if(numStr==null){
return false;
}
if(numStr==""){
return false;
}
if(numStr.contains("")){//验证是否是float型
if(numStr.indexOf('.')==numStr.lastIndexOf('.')){
StringTokenizer st=new StringTokenizer(numStr, "");
while(st.hasMoreElements()){
String splitStr= st.nextToken();
for(int i=splitStr.length();--i>=0;){
if(!Character.isDigit(splitStr.charAt(i))){
return false;
}
}
}
}
}
return true;
}
/**
* Date时间类型转换String
* Created on 2014-6-6
* 时间格式yyyy-MM-dd HH:mm
* @param date
* @param pattern
* @return String
*/
public static String formatDate(Date date, String pattern) {
if (date == null) {
date = new Date(System.currentTimeMillis());
}
if (pattern == null) {
pattern = "yyyy-MM-dd HH:mm:ss";
}
return DateFormatUtils.format(date, pattern);
}
public static String formatDate(){
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
/**
* date传null获取当前时间
* 时间格式yyyy-MM-dd HH:mm
* Created on 2014-6-6
* @param date
* @return String
*/
public static String defaultFormat(Date date) {
return formatDate(date, null);
}
public static Date now()
{
return new Date();
}
public static String formartDate(Date date, String formatStr)
{
if (date == null) {
date = now();
}
if (isEmpty(formatStr)) {
formatStr = "MM/dd/yyyy";
}
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
return sdf.format(date);
}
/**
* 提供精确加法计算的add方法
* @param value1 被加数
* @param value2 加数
* @return 两个参数的和
*/
public static double add(double value1,double value2){
BigDecimal b1 = new BigDecimal(Double.valueOf(value1));
BigDecimal b2 = new BigDecimal(Double.valueOf(value2));
return b1.add(b2).doubleValue();
}
/**
* 提供精确加法计算的add方法
* @param value1 被加数
* @param value2 加数
* @return 两个参数的和
*/
public static BigDecimal add(BigDecimal value1,BigDecimal value2){
Assert.assertNotNull(value1);
Assert.assertNotNull(value2);
return value2.add(value2);
}
/**
* 提供精确加法计算的add方法,确认精确度
* @param value1 被加数
* @param value2 加数
* @param scale 小数点后保留几位
* @return 两个参数求和之后,按精度四舍五入的结果
*/
public static double add(double value1, double value2, int scale){
return round(add(value1, value2), scale);
}
/**
* 提供精确加法计算的add方法,确认精确度
* @param value1 被加数
* @param value2 加数
* @param scale 小数点后保留几位
* @return 两个参数求和之后,按精度四舍五入的结果
*/
public static BigDecimal add(BigDecimal value1, BigDecimal value2, int scale){
return round(add(value1, value2), scale);
}
/**
* 提供精确的小数位四舍五入处理。
* @param v 需要四舍五入的数字
* @param scale 小数点后保留几位
* @return 四舍五入后的结果
*/
public static double round(double v, int scale) {
Assert.assertEquals(scale < 0,"精确度不能小于0");
BigDecimal b = new BigDecimal(Double.toString(v));
BigDecimal one = new BigDecimal("1");
return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 提供精确的小数位四舍五入处理。
* @param value 需要四舍五入的数字
* @param scale 小数点后保留几位
* @return 四舍五入后的结果
*/
public static BigDecimal round(BigDecimal value, int scale) {
Assert.assertNotNull(value);
Assert.assertEquals(scale < 0,"精确度不能小于0");
BigDecimal one = new BigDecimal("1");
return value.divide(one, scale, BigDecimal.ROUND_HALF_UP);
}
/**
* List<Map>转List<Object>
* @param listMap
* @param T
* @return
* @throws Exception
*/
public static <T> List<T> ListMapToListBean(List<Map<String,Object>> listMap, Class T) throws Exception {
List<T> beanList = new ArrayList<T>();
for(int i=0, n=listMap.size(); i<n; i++){
Map<String,Object> map = listMap.get(i);
T bean = mapToBean(map,T);
beanList.add(bean);
}
return beanList;
}
/**
* Map转bean
* @param map
* @param T
* @return
* @throws Exception
*/
public static <T> T mapToBean(Map map, Class T) throws Exception {
if(map==null || map.size()==0){
return null;
}
BeanInfo beanInfo = Introspector.getBeanInfo(T);
T bean = (T)T.newInstance();
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (int i = 0, n = propertyDescriptors.length; i <n ; i++) {
PropertyDescriptor descriptor = propertyDescriptors[i];
String propertyName = descriptor.getName();
String upperPropertyName = propertyName.toUpperCase();
if (map.containsKey(upperPropertyName)) {
Object value = map.get(upperPropertyName);
//这个方法不会报参数类型不匹配的错误。
BeanUtils.copyProperty(bean, propertyName, value);
}
}
return bean;
}
/**
* 标题样式
* @param wb
* @return
*/
public static CellStyle getHeaderCellStyle(
org.apache.poi.ss.usermodel.Workbook wb) {
CellStyle style = wb.createCellStyle();
// 对齐方式
style.setAlignment(CellStyle.ALIGN_CENTER);
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
// 边框颜色
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBottomBorderColor(IndexedColors.GREY_80_PERCENT.getIndex());
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setLeftBorderColor(IndexedColors.GREY_80_PERCENT.getIndex());
style.setBorderRight(CellStyle.BORDER_THIN);
style.setRightBorderColor(IndexedColors.GREY_80_PERCENT.getIndex());
style.setBorderTop(CellStyle.BORDER_THIN);
style.setTopBorderColor(IndexedColors.GREY_80_PERCENT.getIndex());
style.setFillBackgroundColor(IndexedColors.GREY_80_PERCENT.getIndex());
// 背景颜色
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
// 字体
Font font = wb.createFont();
font.setColor(TITLE_FG);
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
style.setFont(font);
return style;
}
/**
* 内容样式
* @param wb
* @param align
* @return
*/
protected static CellStyle createValueStyle(org.apache.poi.ss.usermodel.Workbook wb,
Short align) {
CellStyle style = wb.createCellStyle();
if(align == null) {
align = CellStyle.ALIGN_CENTER;
} else {
if (!align.equals(CellStyle.ALIGN_LEFT)
&& !align.equals(CellStyle.ALIGN_CENTER)
&& !align.equals(CellStyle.ALIGN_RIGHT) ) {
align = CellStyle.ALIGN_LEFT;
}
}
style.setAlignment(align);
// 边框颜色
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBottomBorderColor(IndexedColors.GREY_80_PERCENT.getIndex());
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setLeftBorderColor(IndexedColors.GREY_80_PERCENT.getIndex());
style.setBorderRight(CellStyle.BORDER_THIN);
style.setRightBorderColor(IndexedColors.GREY_80_PERCENT.getIndex());
style.setBorderTop(CellStyle.BORDER_THIN);
style.setTopBorderColor(IndexedColors.GREY_80_PERCENT.getIndex());
style.setFillBackgroundColor(IndexedColors.GREY_80_PERCENT.getIndex());
return style;
}
}
自定义excel注解
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ java.lang.annotation.ElementType.FIELD })
public @interface ExcelNote {
/**
* Excel中的列名
*
* @return
*/
public abstract String name();
/**
* 列名对应的A,B,C,D...,不指定按照默认顺序排序
*
* @return
*/
public abstract String column() default "";
/**
* 提示信息
*
* @return
*/
public abstract String prompt() default "";
/**
* 设置只能选择不能输入的列内容
*
* @return
*/
public abstract String[] combo() default {};
/**
* 是否导出数据
*
* @return
*/
public abstract boolean isExport() default true;
/**
* 是否为重要字段(整列标红,着重显示)
*
* @return
*/
public abstract boolean isMark() default false;
/**
* 是否合计当前列
*
* @return
*/
public abstract boolean isSum() default false;
}
excel实体类
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestModel {
@@ExcelNote(name = "ID")
private Long id;
@@ExcelNote(name = "姓名", isMark = true)
private String name;
@@ExcelNote(name = "年龄", isMark = true)
private Integer age;
@@ExcelNote(name = "生日")
private String birthday;
@@ExcelNote(name = "备注")
private String mark;
public TestModel() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getMark() {
return mark;
}
public void setMark(String mark) {
this.mark = mark;
}
public static void main(String[] args) {
Date date = new Date(); //获取当前时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = sdf.format("2018-08-31 11:06:13"); //将Date类型转换成String类型
System.out.println(format.getClass().getName());//打印format数据类型
System.out.println(format);//打印当前时间
}
}
main方法测试
导出
List<TestModel> list = new ArrayList<TestModel>();
for (int i = 0; i < 25; i++) {
TestModel testModel = new TestModel();
testModel.setId(Long.valueOf(i + 1));
testModel.setName("黄佳兴" + (i + 1));
testModel.setAge(Random.class.newInstance().nextInt(100));
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
testModel.setBirthday(sdf.format(date));
testModel.setMark("黄佳兴test" + Random.class.newInstance().nextInt(100));
list.add(testModel);
}
FileOutputStream out = new FileOutputStream("D:\\test2.xls");
ExcelNoteUtil<TestModel> util1 = new ExcelNoteUtil<TestModel>(TestModel.class);
util1.getListToExcel(list, "test信息", out);
System.out.println("----执行完毕----");
导入
FileInputStream fis = new FileInputStream("D:\\test2.xls");
ExcelNoteUtil<TestModel> util1 = new ExcelNoteUtil<TestModel>(TestModel.class);
List<TestModel> testModels = util1.getExcelToList("test信息0", fis);
System.out.println("*****************"+testModels.size());
for (TestModel testModel : testModels) {
System.out.println();
System.out.println(testModel.getId()+"\t"+testModel.getName()+"\t"+testModel.getAge()+"\t"+testModel.getBirthday()+"\t"+testModel.getMark());
}
System.out.println("----执行完毕----");
参考链接: https://blog.csdn.net/hd20086996/article/details/90519179?biz_id=102&utm_term=java%E5%9F%BA%E4%BA%8E%E6%B3%A8%E8%A7%A3%E5%AF%BC%E5%85%A5%E5%AF%BC%E5%87%BA&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduweb~default-2-90519179&spm=1018.2118.3001.4187
因为是新手小白他的一些包我没找到,所以从别的地方完善了一下excel工具类,里面包含List<Map<string,object>>转List<object .>的方法.其他地方根据自己需求更改.