POI如何读取树形结构的excel文件?并产生树形结构

主要代码

import java.io.File;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;

public class POIImportDemo {
/**
* 读取excel数据
* 
* @param path
*/
private void readExcelToObj(String path) {
Workbook wb = null;
    try {
        wb = WorkbookFactory.create(new File(path));
        readExcel(wb, 0, 0, 0);
    } catch (InvalidFormatException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
/**
 * 读取excel文件
 * 
 * @param wb
 * @param sheetIndex    sheet页下标:从0开始
 * @param startReadLine 开始读取的行:从0开始
 * @param tailLine      去除最后读取的行
 */
private void readExcel(Workbook wb, int sheetIndex, int startReadLine, int tailLine) {
    Sheet sheet = wb.getSheetAt(sheetIndex);
    Row row = null;

    for (int i = startReadLine; i < sheet.getLastRowNum() - tailLine + 1; i++) {
        row = sheet.getRow(i);
        for (Cell c : row) {
            boolean isMerge = isMergedRegion(sheet, i, c.getColumnIndex());
            // 判断是否具有合并单元格
            if (isMerge) {
                String rs = getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
                System.out.print(rs + "");
            } else {
                System.out.print(getCellValue(c) + "");
            }
        }
        System.out.println();

    }

}

/**
 * 获取合并单元格的值
 * 
 * @param sheet
 * @param row
 * @param column
 * @return
 */
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;
}

/**
 * 判断合并了行
 * 
 * @param sheet
 * @param row
 * @param column
 * @return
 */
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 sheet
 * @param row    行下标
 * @param column 列下标
 * @return
 */
private 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页中是否含有合并单元格
 * 
 * @param sheet
 * @return
 */
private boolean hasMerged(Sheet sheet) {
    return sheet.getNumMergedRegions() > 0 ? true : false;
}

/**
 * 合并单元格
 * 
 * @param sheet
 * @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));
}

/**
 * 获取单元格的值
 * 
 * @param cell
 * @return
 */
public String getCellValue(Cell cell) {

    if (cell == null)
        return "";

    if (cell.getCellType() == Cell.CELL_TYPE_STRING) {

        return cell.getStringCellValue();

    } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {

        return String.valueOf(cell.getBooleanCellValue());

    } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {

        return cell.getCellFormula();

    } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {

        return String.valueOf(cell.getNumericCellValue());

    }
    return "";
}


在这里插入图片描述
上图是运行出来的打印结果,如果要层级树的结构,就在读取第一行的时候,每个元素对应建立一个Map,map存储元素名称和插入数据库的id,然后读取下一行的时候与上一行的对位元素比对,建立层级关系.
这是一个层级关系树的例子方法,比对差异,缺点是不能有重复的名称

private Integer ImportEcxel(Integer id0, Integer indexSystemIdOld, Integer indexSystemId, String filePath) throws IOException {
        Workbook wb = null;
        List<Map<String, Object>> list = Lists.newArrayList();
        try {
            wb = WorkbookFactory.create(new File(filePath));

            Sheet sheet = wb.getSheetAt(0);
            Row row = null;

            for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
                row = sheet.getRow(i);
                for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
                    Map<String, Object> map = Maps.newHashMap();
                    Cell c = row.getCell(j);
                    boolean isMerge = isMergedRegion(sheet, i, c.getColumnIndex());
                    // 判断是否具有合并单元格
                    if (isMerge) {
                        String rs = getMergedRegionValue(sheet, row.getRowNum(), c.getColumnIndex());
                        if (j == 0 && i == 0) {
                            IndexSystem indexSystem = indexSystemService.selectByPrimaryKey(indexSystemIdOld);
                            indexSystem.setName(rs);
                            //改indexSystem的名称
                            indexSystemService.updateNameByPrimaryKey(indexSystem);
                            indexSystemId = indexSystem.getId();
                            //父节点
                            Index index = new Index();
                            index.setName(rs);
                            index.setParentId(null);
                            index.setCreatorId(id0);
                            index.setResponsorId(id0);
                            index.setIndexSystemId(indexSystemId);
                            indexService.insert(index);
                            //获取新增的index的id
                            Integer idNew = index.getId();
                            map.put("name", rs);
                            map.put("indexId", idNew);
                            list.add(j, map);
                        }
                        if (j >= 0) {
                            if (list.size() > j) {
                                String name = (String) list.get(j).get("name");
                                if (name.equals(rs)) {
                                    continue;
                                } else {
                                    Integer indexId = (Integer) list.get(j-1).get("indexId");
                                    //父节点
                                    Index index = new Index();
                                    index.setName(rs);
                                    index.setParentId(indexId);
                                    index.setCreatorId(id0);
                                    index.setResponsorId(id0);
                                    index.setIndexSystemId(indexSystemId);
                                    indexService.insert(index);
                                    //获取新增的index的id
                                    Integer idNew = index.getId();
                                    map.put("name", rs);
                                    map.put("indexId", idNew);
                                    list.add(j, map);
                                }
                            } else {
//                                    父节点
                                Integer indexId = (Integer) list.get(j-1).get("indexId");
                                Index index = new Index();
                                index.setName(rs);
                                index.setParentId(indexId);
                                index.setCreatorId(id0);
                                index.setResponsorId(id0);
                                index.setIndexSystemId(indexSystemId);
                                indexService.insert(index);
                                //获取新增的index的id
                                Integer idNew = index.getId();
                                map.put("name", rs);
                                map.put("indexId", idNew);
                                list.add(j, map);
                            }
                        }


                    } else {
                        if (!getCellValue(c).trim().equals("")) {
                            if (j >= 1) {
                                String name = (String) list.get(j - 1).get("name");
                                Integer indexId = (Integer) list.get(j - 1).get("indexId");
                                if (list.size() >= j) {
                                    //父节点
                                    Index index = new Index();
                                    index.setName(getCellValue(c));
                                    index.setParentId(indexId);
                                    index.setCreatorId(id0);
                                    index.setResponsorId(id0);
                                    index.setIndexSystemId(indexSystemId);
                                    indexService.insert(index);
                                    //获取新增的index的id
                                    Integer idNew = index.getId();
                                    map.put("name", getCellValue(c));
                                    map.put("indexId", idNew);
                                    list.add(j, map);
                                }

                            }
                        }


                    }
                }
            }
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        }
        return indexSystemId;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值