import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.List;
/**
* @author: gst
* @date: 2023/3/13 15:34
*/
public class MergeReadsExcelUtil {
/**
* 读取excel数据 支持xls格式
* @param sheetIndex sheet页下标:从0开始
* @param startReadLine 开始读取的行:从0开始
* @param tailLine 去除最后读取的行
*/
public static List<List<JSONObject>> readMergeExcel(MultipartFile file, int sheetIndex, int startReadLine, int tailLine) {
List<List<JSONObject>> results = new ArrayList<>();
Workbook wb = null;
String fileName = file.getOriginalFilename();//获取文件名
try {
if (!validateExcel(fileName)) {// 验证文件名是否合格
return null;
}
boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本
if (isExcel2007(fileName)) {
isExcel2003 = false;
}
if (isExcel2003) {// 当excel是2003时,创建excel2003
wb = new HSSFWorkbook(file.getInputStream());
} else {// 当excel是2007时,创建excel2007
wb = new XSSFWorkbook(file.getInputStream());
}
}catch (Exception e) {
e.printStackTrace();
}
try {
// wb = WorkbookFactory.create(new File(path));
Sheet sheet = wb.getSheetAt(sheetIndex);
Row row = null;
for (int i = startReadLine; i < sheet.getLastRowNum() - tailLine + 1; i++) {
row = sheet.getRow(i);
if (row == null)
continue;
List<JSONObject> result = new ArrayList<>();
for (Cell c : row) {
JSONObject values = new JSONObject();
boolean isMerge = isMergedRegion(sheet, i, c.getColumnIndex());
// values.put("isMerge",isMerge);
// 判断是否具有合并单元格
if (isMerge) {
JSONObject rs = getMergedRegionJsonValue(sheet, row.getRowNum(), c.getColumnIndex());
values.putAll(rs);
} else {
values.put("cellValue",getCellValue(c));
}
result.add(values);
}
results.add(result);
}
} catch (Exception e) {
e.printStackTrace();
}
return results;
}
/**
* 获取合并单元格的值
*/
public String getMergedRegionValue(Sheet sheet, int row, int column) {
int sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress ca = sheet.getMergedRegion(i);
int firstColumn = ca.getFirstColumn();
int lastColumn = ca.getLastColumn();
int firstRow = ca.getFirstRow();
int lastRow = ca.getLastRow();
if (row >= firstRow && row <= lastRow) {
if (column >= firstColumn && column <= lastColumn) {
Row fRow = sheet.getRow(firstRow);
Cell fCell = fRow.getCell(firstColumn);
return getCellValue(fCell);
}
}
}
return null;
}
public static JSONObject getMergedRegionJsonValue(Sheet sheet, int row, int column) {
JSONObject values = new JSONObject();
int sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress ca = sheet.getMergedRegion(i);
int firstColumn = ca.getFirstColumn();
int lastColumn = ca.getLastColumn();
int firstRow = ca.getFirstRow();
int lastRow = ca.getLastRow();
if (row >= firstRow && row <= lastRow) {
if (column >= firstColumn && column <= lastColumn) {
Row fRow = sheet.getRow(firstRow);
Cell fCell = fRow.getCell(firstColumn);
values.put("cellValue",getCellValue(fCell));
// values.put("firstColumn",firstColumn);
// values.put("lastColumn",lastColumn);
// values.put("firstRow",firstRow);
// values.put("lastRow",lastRow);
return values;
}
}
}
return values;
}
/**
* 判断合并了行
*/
private boolean isMergedRow(Sheet sheet, int row, int column) {
int sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress range = sheet.getMergedRegion(i);
int firstColumn = range.getFirstColumn();
int lastColumn = range.getLastColumn();
int firstRow = range.getFirstRow();
int lastRow = range.getLastRow();
if (row == firstRow && row == lastRow) {
if (column >= firstColumn && column <= lastColumn) {
return true;
}
}
}
return false;
}
/**
* 判断指定的单元格是否是合并单元格
* @param row 行下标
* @param column 列下标
*/
private static boolean isMergedRegion(Sheet sheet, int row, int column) {
int sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress range = sheet.getMergedRegion(i);
int firstColumn = range.getFirstColumn();
int lastColumn = range.getLastColumn();
int firstRow = range.getFirstRow();
int lastRow = range.getLastRow();
if (row >= firstRow && row <= lastRow) {
if (column >= firstColumn && column <= lastColumn) {
return true;
}
}
}
return false;
}
/**
* 判断sheet页中是否含有合并单元格
*/
private boolean hasMerged(Sheet sheet) {
return sheet.getNumMergedRegions() > 0 ? true : false;
}
/**
* 合并单元格
* @param firstRow 开始行
* @param lastRow 结束行
* @param firstCol 开始列
* @param lastCol 结束列
*/
private void mergeRegion(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {
sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
}
/**
* 获取单元格的值
*/
public static String getCellValue(Cell cell) {
if (cell == null) {return "";}
if (cell.getCellTypeEnum() == CellType.STRING) {
return cell.getStringCellValue();
}
if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
}
if (cell.getCellTypeEnum() == CellType.FORMULA) {
return cell.getCellFormula();
}
if (cell.getCellTypeEnum() == CellType.NUMERIC) {
return String.valueOf(cell.getNumericCellValue());
}
return "";
}
/**
* 验证EXCEL文件
*
* @param filePath
* @return
*/
//错误信息接收器
private static String errorMsg;
public static boolean validateExcel(String filePath) {
if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
errorMsg = "文件名不是excel格式";
return false;
}
return true;
}
// @描述:是否是2003的excel,返回true是2003
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
//@描述:是否是2007的excel,返回true是2007
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
}
JAVA导入合并单元格的Excel文件
于 2023-03-13 16:11:20 首次发布
该代码实现了一个Java工具类,用于读取MultipartFile类型的Excel文件(支持xls和xlsx格式),特别是处理合并单元格的情况。方法包括验证文件格式,读取特定页码的行,获取合并单元格的值,并将数据转换为JSONObject列表。
摘要由CSDN通过智能技术生成