com.github.fanzezhen.common.util.ExcelUtil Maven / Gradle / Ivy
package com.github.fanzezhen.common.util;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import cn.stylefeng.roses.kernel.model.exception.enums.CoreExceptionEnum;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Excel操作工具类
*
* @author ChaiXY
*/
@Slf4j
public class ExcelUtil {
public static final String OFFICE_EXCEL_XLS = "xls";
public static final String OFFICE_EXCEL_XLSX = "xlsx";
/**
* 读取指定上传文件的内容
*/
public static List> readExcel(MultipartFile multipartFile) {
List> rowList = new ArrayList<>();
try {
Workbook workbook = getWorkbook(multipartFile);
Sheet sheet = workbook.getSheetAt(0);
int rowTotalNum = sheet.getPhysicalNumberOfRows();
for (int rowIdx = 0; rowIdx < rowTotalNum; rowIdx++) {
List colList = new ArrayList<>();
Row row = sheet.getRow(rowIdx);
int colTotalNum = row.getPhysicalNumberOfCells();
for (int colIdx = 0; colIdx < colTotalNum; colIdx++) {
Cell cell = row.getCell(colIdx);
if (cell == null) {
colList.add("");
colTotalNum++;
} else {
colList.add(cell.getStringCellValue());
}
}
rowList.add(colList);
}
} catch (IOException e) {
throw new ServiceException(CoreExceptionEnum.FILE_READING_ERROR);
}
return rowList;
}
/**
* 读取指定Sheet页的内容
*
* @param filepath filepath 文件全路径
* @param sheetNo sheet序号,从0开始,如果读取全文sheetNo设置null
*/
public static String readExcel(String filepath, Integer sheetNo) throws EncryptedDocumentException, IOException {
StringBuilder sb = new StringBuilder();
Workbook workbook = getWorkbook(filepath);
if (workbook != null) {
if (sheetNo == null) {
int numberOfSheets = workbook.getNumberOfSheets();
for (int i = 0; i < numberOfSheets; i++) {
Sheet sheet = workbook.getSheetAt(i);
if (sheet == null) {
continue;
}
sb.append(readExcelSheet(sheet));
}
} else {
Sheet sheet = workbook.getSheetAt(sheetNo);
if (sheet != null) {
sb.append(readExcelSheet(sheet));
}
}
}
return sb.toString();
}
/**
* 根据文件路径获取Workbook对象
*
* @param filepath 文件全路径
*/
public static Workbook getWorkbook(String filepath) throws EncryptedDocumentException, IOException {
InputStream is = null;
Workbook wb = null;
if (StringUtils.isBlank(filepath)) {
throw new IllegalArgumentException("文件路径不能为空");
} else {
String suffix = getSuffix(filepath);
if (StringUtils.isBlank(suffix)) {
throw new IllegalArgumentException("文件后缀不能为空");
}
if (OFFICE_EXCEL_XLS.equals(suffix) || OFFICE_EXCEL_XLSX.equals(suffix)) {
try {
is = new FileInputStream(filepath);
wb = WorkbookFactory.create(is);
} finally {
if (is != null) {
is.close();
}
if (wb != null) {
wb.close();
}
}
} else {
throw new IllegalArgumentException("该文件非Excel文件");
}
}
return wb;
}
/**
* 根据文件获取Workbook对象
*
* @param file 文件
*/
public static Workbook getWorkbook(File file) throws EncryptedDocumentException, IOException {
return getWorkbook(new FileInputStream(file));
}
/**
* 根据上传文件获取Workbook对象
*
* @param multipartFile 上传文件
*/
public static Workbook getWorkbook(MultipartFile multipartFile) throws EncryptedDocumentException, IOException {
return getWorkbook(FileUtil.multipartFileToFile(multipartFile));
}
/**
* 根据文件流获取Workbook对象
*
* @param fileInputStream 文件流
*/
public static Workbook getWorkbook(FileInputStream fileInputStream) throws EncryptedDocumentException, IOException {
Workbook wb = WorkbookFactory.create(fileInputStream);
fileInputStream.close();
if (wb != null) wb.close();
return wb;
}
/**
* 获取后缀
*
* @param filepath filepath 文件全路径
*/
private static String getSuffix(String filepath) {
if (StringUtils.isBlank(filepath)) {
return "";
}
int index = filepath.lastIndexOf(".");
if (index == -1) {
return "";
}
return filepath.substring(index + 1);
}
private static String readExcelSheet(Sheet sheet) {
StringBuilder sb = new StringBuilder();
if (sheet != null) {
int rowNos = sheet.getLastRowNum();// 得到excel的总记录条数
for (int i = 0; i <= rowNos; i++) {// 遍历行
Row row = sheet.getRow(i);
if (row != null) {
int colNos = row.getLastCellNum();// 表头总共的列数
for (int j = 0; j < colNos; j++) {
Cell cell = row.getCell(j);
if (cell != null) {
sb.append(cell.getStringCellValue()).append(" ");
}
}
}
}
}
return sb.toString();
}
/**
* 读取指定Sheet页的表头
*
* @param filepath filepath 文件全路径
* @param sheetNo sheet序号,从0开始,必填
*/
public static Row readTitle(String filepath, int sheetNo) throws IOException, EncryptedDocumentException {
Row returnRow = null;
Workbook workbook = getWorkbook(filepath);
if (workbook != null) {
Sheet sheet = workbook.getSheetAt(sheetNo);
returnRow = readTitle(sheet);
}
return returnRow;
}
/**
* 读取指定Sheet页的表头
*/
public static Row readTitle(Sheet sheet) {
Row returnRow = null;
int totalRow = sheet.getLastRowNum();// 得到excel的总记录条数
for (int i = 0; i < totalRow; i++) {// 遍历行
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
returnRow = sheet.getRow(0);
break;
}
return returnRow;
}
/**
* 创建Excel文件
*
* @param filepath filepath 文件全路径
* @param sheetName 新Sheet页的名字
* @param titles 表头
* @param values 每行的单元格
*/
public static boolean writeExcel(String filepath,
String sheetName,
List titles,
List