import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @Description: excel工具类
* @Author: lxl
* @CreateDate: 2022/3/22 10:47
* @Version: 1.0
*/
@Slf4j
public class ExcelUtils {
private static NumberFormat numberInstance = NumberFormat.getNumberInstance();
{numberInstance.setGroupingUsed(false);}
/**
* @Description: excel导入
* @UpdateDate: 2019/5/10 13:52
* @Version: 1.0
*/
public static <T> List<T> excelToList(Class<T> clazz, InputStream is, String excelFileName) {
List<T> list = new ArrayList<>();
try {
//创建工作簿
Workbook workbook = createWorkbook(is, excelFileName);
System.out.println("workbook:"+workbook);
//创建工作表sheet
Sheet sheet = getSheet(workbook, 0);
//获取sheet中数据的行数
int rows = sheet.getPhysicalNumberOfRows();
//获取表头单元格个数
int cells = sheet.getRow(1).getPhysicalNumberOfCells();
//利用反射,给JavaBean的属性进行赋值
Field[] fields = clazz.getDeclaredFields();
for (int i = 1; i < rows; i++) {//第一行为标题栏,从第二行开始取数据
Row row = sheet.getRow(i);
int index = 0;
T object = clazz.getConstructor(new Class[]{}).newInstance(new Object[]{});
while (index <= cells) {
Cell cell = row.getCell(index);
if (null == cell) {
cell = row.createCell(index);
}
String value = null;
if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {
if (DateUtil.isCellDateFormatted(cell)) {
//用于转化为日期格式
Date d = cell.getDateCellValue();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd" );
value = df.format(d);
} else {
double numericCellValue = cell.getNumericCellValue();
String format = numberInstance.format(numericCellValue);
value = format.toString();
// cell.setCellType(Cell.CELL_TYPE_STRING);
// value = null == cell.getStringCellValue() ? "" : cell.getStringCellValue();
}
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
value = null == cell.getStringCellValue() ? "" : cell.getStringCellValue();
}
if(index < fields.length) {
Field field = fields[index];
String fieldName = field.getName();
String methodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
Method setMethod = clazz.getMethod(methodName, new Class[]{String.class});
setMethod.invoke(object, new Object[]{value});
}
index++;
}
if (isHasValues(object)) {
list.add(object);
}
}
} catch (Exception e) {
System.out.println("e:"+e);
System.out.println(e.getMessage());
} finally {
try {
is.close();//关闭流
} catch (Exception e2) {
System.out.println("e2:"+e2);
System.out.println(e2.getMessage());
}
}
return list;
}
}
临时的文章
最新推荐文章于 2024-07-14 22:26:46 发布