我有一个类:如何使用Apache POI导出到Excel树状层级?
class Node{
private Node parent;
private List<Node> children;
...
}
我怎样才能导出的项目的树使用Apache POI用于获取文件像这样练成(我只需要第一列在表中移):
A
B
C
D
E
F
G
我有一个类:如何使用Apache POI导出到Excel树状层级?
class Node{
private Node parent;
private List<Node> children;
...
}
我怎样才能导出的项目的树使用Apache POI用于获取文件像这样练成(我只需要第一列在表中移):
A
B
C
D
E
F
G
我的解决方案 - 合并。祝你今天愉快。谢谢。
是这样的: https://docs.oracle.com/cd/E36352_01/epm.1112/disclosure_mgmt_admin/new_files/image002.jpg
我与融合的解决方案:
private int createHierarchy(Sheet sheet, Node node, int currentRowIdx, int nodeLevel) {
if(node.getParent() == null){
sheet.setColumnWidth(8, 1000);
Row row = sheet.createRow(currentRowIdx);
row.createCell(nodeLevel).setCellValue(node.getName());
row.createCell(9).setCellValue(node.getValue());
sheet.addMergedRegion(new CellRangeAddress(currentRowIdx, currentRowIdx, nodeLevel, 8));
nodeLevel++;
}
for (Node node : node.getChildren()) {
Row row = sheet.createRow(++currentRowIdx);
row.createCell(nodeLevel).setCellValue(node.getName());
row.createCell(9).setCellValue(node.getValue());
sheet.addMergedRegion(new CellRangeAddress(currentRowIdx, currentRowIdx, nodeLevel, 8));
currentRowIdx = createHierarchy(sheet, node, currentRowIdx, nodeLevel+1);
}
return currentRowIdx;
}
哦,我明白了。对不起,我不太明白你在找什么,但我很高兴它的工作!也欢迎Stack Overflow!一定要接受最适合你的答案,这样其他人可以回答尚未解决的问题。 – Ishnark
一个简单的解决方案是创建一个NodeWriter
类,本质上是节点写入到一个Excel电子表格:
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class NodeWriter {
public void write(Node tree, String filePathName) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Tree");
writeHelp(0, 1, tree, sheet);
try (FileOutputStream outputStream = new FileOutputStream(filePathName)) {
workbook.write(outputStream);
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void writeHelp(int indent, int rowNum, Node tree, XSSFSheet sheet) {
if (sheet.getRow(rowNum) != null) {
writeHelp(indent, rowNum+1, tree, sheet);
} else {
Row row = sheet.createRow(rowNum);
Cell cell = row.createCell(indent);
cell.setCellValue(tree.getNodeName());
for (Node child : tree.getChildren()) {
writeHelp(indent + 1, rowNum + 1, child, sheet);
}
}
}
}
我做关于你的Node
类的一些假设。此解决方案可确保您创建一个新的行并且不会覆盖现有的行(如果您的if
环路在writeHelp
中不存在)。
但在这种情况下,我需要在同一列中的nodeName。而且我不知道如何根据节点级别修剪左边的部分。 –
当我看着我的excel文档时,我看到了与你建议的相同的树结构;它对你来说是什么样子/它应该是什么样子? – Ishnark
https://docs.oracle.com/cd/E36352_01/epm.1112/disclosure_mgmt_admin/new_files/image002.jpg –
我可能是错的,但该输出看起来像树的列表,而不是一个单一的树。 (我这样说是因为它看起来像A,C,D和E处于同一水平,但看起来不像他们有共同的父母)。树输出是否有根? – Ishnark
谢谢:)是的,父母是单身 –
你可以使用'XSSFSheet'和'XSSFWorkbook'类来获得帮助。看到我的回答 – Ishnark