import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
public class ExcelToTree {
public static TreeNode createTreeFromExcel(File file) throws IOException, InvalidFormatException {
FileInputStream fis = new FileInputStream(file);
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0); // 获取第一个Sheet页
TreeNode root = new TreeNode("Root"); // 根节点
Stack stack = new Stack<>(); // 用栈来维护每一层节点的关系
stack.push(root); // 先把根节点压入栈中
int lastRowNum = sheet.getLastRowNum();
for (int i = 1; i <= lastRowNum; i++) {
Row row = sheet.getRow(i);
String name = row.getCell(0).getStringCellValue(); // 读取节点名
int level = (int) row.getCell(1).getNumericCellValue(); // 读取节点所在层数
TreeNode node = new TreeNode(name);
while (stack.size() > level) {
stack.pop(); // 把栈中深度大于当前层数的节点弹出
}
TreeNode parent = stack.peek();
parent.addChild(node); // 把当前节点添加到父节点的子节点列表中
stack.push(node); // 把当前节点压入栈中
}
return root; // 返回整个树形结构
}
static class TreeNode {
public String name; // 节点名
public List children = new ArrayList<>(); // 子节点列表
public TreeNode(String name) {
this.name = name;
}
public void addChild(TreeNode child) {
children.add(child);
}
}
public static void main(String[] args) throws IOException, InvalidFormatException {
File excelFile = new File("test.xlsx");
TreeNode root = createTreeFromExcel(excelFile);
printTree(root);
}
public static void printTree(TreeNode root) {
Queue queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
System.out.print(node.name + " ");
for (TreeNode child : node.children) {
queue.offer(child);
}
}
System.out.println();
}
}
}
Java 使用 Stack 将Excel数据转化为树形结构
最新推荐文章于 2024-04-28 15:30:41 发布