Java POI 对Excel合并单元格的数据处理
最近在项目开发过程中,有个一个导入Excel文件处理合并单元格数据的需求,就自己在网上找了一个模板,自己进行二次开发来开发需求。
Excel工具类
public class ExcelUtil {
/**
* 读取excel数据
*
*/
public ArrayList<Map<String, String>> readExcelToObj(InputStream inputStream) {
Workbook wb = null;
ArrayList<Map<String, String>> result = null;
try {
wb = WorkbookFactory.create(inputStream);
result = readExcel(wb, 0, 4, 0);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 读取excel文件
*
* @param wb
* @param sheetIndex sheet页下标:从0开始
* @param startReadLine 开始读取的行:从0开始
* @param tailLine 去除最后读取的行
*/
private ArrayList<Map<String, String>> readExcel(Workbook wb, int sheetIndex, int startReadLine, int tailLine) {
Sheet sheet = wb.getSheetAt(sheetIndex);
Row row = null;
ArrayList<Map<String, String>> result = new ArrayList<Map<String, String>>();
for (int i = startReadLine; i < sheet.getLastRowNum() - tailLine + 1; i++) {
row = sheet.getRow(i);
Map<String, String> map = new HashMap<String, String>();
for (Cell c : row) {
String returnStr = "";
boolean isMerge = isMergedRegion(sheet, i, c.getColumnIndex());
//判断是否具有合并单元格
if (isMerge) {
String rs = getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
returnStr = rs;
} else {
c.setCellType(CellType.STRING);
returnStr = c.getRichStringCellValue().getString();
}
if (c.getColumnIndex() == 0) {
map.put("MachineCode", returnStr);
} else if (c.getColumnIndex()