package com.zuihuibao.chcshop.util;
import java.io.*;
import java.net.URL;
import java.util.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.util.CellRangeAddress;
public class ExcelMergeUtil {
private org.apache.poi.ss.usermodel.Workbook wb;
public ExcelMergeUtil(String filePath){
if(filePath==null || filePath.trim().length()==0){
return;
}
this.getWrokbook(filePath);
}
/**
* 读取excel数据
* @param sheetIndex sheet 索引,从0开始
* @param startReadLine 开始索引
* @param tailLine
* @return
*/
public List<Map<String, String>> readExcelToObjBySheetIndex(Integer sheetIndex,Integer startReadLine,Integer tailLine ) {
return readExcel(this.wb, sheetIndex, startReadLine, tailLine);
}
/**
* 读取excel数据
* @param sheetName sheet 名称
* @param startReadLine 开始索引
* @param tailLine
* @return
*/
public List<Map<String, String>> readExcelToObjBySheetName(String sheetName,Integer startReadLine,Integer tailLine ) {
return readExcel(this.wb, sheetName, startReadLine, tailLine);
}
/**
* 读取列名
* @param sheetIndex
* @param rowIndex
* @return
*/
public Map<String,String> readExcelColumnName(Integer sheetIndex,Integer rowIndex) {
return readExcelColumnName(this.wb, sheetIndex, rowIndex);
}
/**
* 读取列名
* @param sheetName sheet页的名称
* @param rowIndex 列名行的索引,从0开始
* @return
*/
public Map<String,String> readExcelColumnName(String sheetName,Integer rowIndex) {
return readExcelColumnName(this.wb, sheetName, rowIndex);
}
/**
* 读取列名
*
* @param wb
* @param sheetIndex sheet页下标:从0开始
* @param rowIndex 列名行的索引,从0开始
*/
private Map<String,String> readExcelColumnName(Workbook wb, int sheetIndex, int rowIndex) {
Sheet sheet = wb.getSheetAt(sheetIndex);
Row row = null;
Map<String,String> result = new HashMap<>();
row = sheet.getRow(rowIndex);
if (row == null) {
return result;
}
for(Short i=0;i< row.getLastCellNum();i++){
Cell c=row.getCell(i);
String returnStr = "";
boolean isMerge = isMergedRegion(sheet, rowIndex, c.getColumnIndex());
//判断是否具有合并单元格
if (isMerge) {
String rs = getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
returnStr = rs;
} else {
//设置单元格类型
c.setCellType(CellType.STRING);
returnStr = c.getRichStringCellValue().getString();
}
returnStr=returnStr.replaceAll("(\r\n|\n)", "");
result.put(i.toString(), returnStr);
}
return result;
}
/**
* 读取列名
*
* @param wb
* @param sheetName sheet页名称
* @param rowIndex 列名行的索引,从0开始
*/
private Map<String,String> readExcelColumnName(Workbook wb, String sheetName, int rowIndex) {
Sheet sheet = wb.getSheet(sheetName);
Row row = null;
Map<String,String> result = new HashMap<>();
row = sheet.getRow(rowIndex);
if (row == null) {
return result;
}
for(Short i=0;i< row.ge
读取含合并单元格的excel(java版)
于 2022-11-23 10:04:24 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)