@Slf4j
public class EasyPoiUtils {
/**
* 2003
*/
private static final String EXCEL_XLS = "xls";
/**
* 2007
*/
private static final String EXCEL_XLSX = "xlsx";
private EasyPoiUtils() {
}
/**
* 读入excel文件,解析后返回
* 多sheet页,
*
* @param file
* @return key:sheetName value:sheet内容
*/
public static Map<String, List<String[]>> readExcel(MultipartFile file) {
//检查文件
checkFile(file);
//获得Workbook工作薄对象
Workbook workbook = getWorkBook(file);
//创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
Map<String, List<String[]>> map = new HashMap<>(16);
List<String[]> list = new ArrayList<>();
if (workbook != null) {
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
//获得当前sheet工作表
Sheet sheet = workbook.getSheetAt(sheetNum);
String sheetName = workbook.getSheetName(sheetNum);
if (sheet == null) {
continue;
}
//获得当前sheet的开始行
int firstRowNum = sheet.getFirstRowNum();
//获得当前sheet的结束行
int lastRowNum = sheet.getLastRowNum();
//循环除了第一行的所有行
for (int rowNum = firstRowNum; rowNum <= lastRowNum; rowNum++) {
//获得当前行
Row row = sheet.getRow(rowNum);
if (row == null) {
continue;
}
//获得当前行的开始列
int firstCellNum = row.getFirstCellNum();
//获得当前行的列数
int lastCellNum = row.getPhysicalNumberOfCells();
String[] cells = new String[row.getPhysicalNumberOfCells()];
//循环当前行
for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
Cell cell = row.getCell(cellNum);
cells[cellNum] = getCellValue(cell);
}
list.add(cells);
}
map.put(sheetName, list);
}
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return map;
}
private static void checkFile(MultipartFile file) {
//判断文件是否存在
if (null == file) {
log.error("文件不存在!");
throw new BusinessException("文件不存在!");
}
//获得文件名
String fileName = file.getOriginalFilename();
//判断文件是否是excel文件
if (fileName != null && !fileName.endsWith(EXCEL_XLS) && !fileName.endsWith(EXCEL_XLSX)) {
log.error(fileName + "不是excel文件");
throw new BusinessException(fileName + "不是excel文件");
}
}
private static Workbook getWorkBook(MultipartFile file) {
//获得文件名
String fileName = file.getOriginalFilename();
//创建Workbook工作薄对象,表示整个excel
Workbook workbook = null;
try {
//获取excel文件的io流
InputStream is = file.getInputStream();
//根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
if (fileName != null && fileName.endsWith(EXCEL_XLS)) {
//2003
workbook = new HSSFWorkbook(is);
} else if (fileName != null && fileName.endsWith(EXCEL_XLSX)) {
//2007
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
log.info(e.getMessage());
}
return workbook;
}
private static String getCellValue(Cell cell) {
String cellValue = "";
if (cell == null) {
return cellValue;
}
//把数字当成String来读,避免出现1读成1.0的情况
if (cell.getCellType() == NUMERIC) {
cell.setCellType(CellType.STRING);
}
//判断数据的类型
switch (cell.getCellType()) {
//数字
case NUMERIC:
cellValue = String.valueOf(cell.getNumericCellValue());
break;
//字符串
case STRING:
cellValue = String.valueOf(cell.getStringCellValue());
break;
//Boolean
case BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
//公式
case FORMULA:
cellValue = String.valueOf(cell.getCellFormula());
break;
//空值
case BLANK:
cellValue = "";
break;
//故障
case ERROR:
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
}
/***
*导出Excel
* @param list 数据集合
* @param title 标题名
* @param sheetName sheet页名
* @param pojoClass 主体类
* @param fileName 文件名
* @param isCreateHeader 是否创建表头
* @param response
*/
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName,boolean isCreateHeader, HttpServletResponse response){
ExportParams exportParams = new ExportParams(title, sheetName);
exportParams.setCreateHeadRows(isCreateHeader);
defaultExport(list, pojoClass, fileName, response, exportParams);
}
/***
* 导出Excel
* @param list 数据集合
* @param title 标题名
* @param sheetName sheet页名
* @param pojoClass 主体类
* @param fileName 文件名
* @param response
*/
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response){
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
}
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response,ExcelType excelType){
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, excelType));
}
/**
* 不管数据量多少,直接用SXSSFWorkbook 导出数据到excel
* @param list
* @param title
* @param sheetName
* @param pojoClass
* @param fileName
* @param response
* @param excelType
*/
public static void commonExportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response,ExcelType excelType) {
ExportParams entity = new ExportParams(title, sheetName, excelType);
Workbook workbook = new SXSSFWorkbook(1000);
(new ExcelExportService()).createSheet(workbook, entity, pojoClass, list);
if (workbook != null){
downLoadExcel(fileName, response, workbook);
}
}
/***
* 导出Excel
* @param list 数据集合
* @param fileName 文件名
* @param response
*/
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
defaultExport(list, fileName, response);
}
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
if (workbook != null){
downLoadExcel(fileName, response, workbook);
}
}
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
workbook.write(response.getOutputStream());
} catch (IOException e) {
throw new BusinessException(e.getMessage());
}
}
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
if (workbook != null) {
;
}
downLoadExcel(fileName, response, workbook);
}
public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
if (StringUtils.isBlank(filePath)){
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
}catch (NoSuchElementException e){
throw new BusinessException("模板不能为空");
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException(e.getMessage());
}
return list;
}
/***
*
* @param file 文件
* @param titleRows 标题行
* @param headerRows 投行
* @param pojoClass class文件
* @param <T>
* @return
*/
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
if (file == null){
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
}catch (NoSuchElementException e){
e.printStackTrace();
throw new BusinessException("excel文件不能为空");
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException(e.getMessage());
}
return list;
}
}
poi包的工具类,导入功能实现:
List<PackageAgreementNewAluminumDto> packageAgreementList1 = EasyPoiUtils.importExcel(file, 0, 1, PackageAgreementNewAluminumDto.class);
PackageAgreementNewAluminumDto为导入dto。
通用导出:
EasyPoiUtils.exportExcel(list, "价格查询列表", "价格查询列表", PackagePriceExcelDto.class, "价格查询列表.xlsx", response, ExcelType.XSSF);
高效率大批量数据导出可以参考我前面写的博客。
链接:https://blog.csdn.net/qq_37713521/article/details/129660313