文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

Java树形结构数据生成导出excel文件方法记录

2024-04-02 19:55

关注

什么是树形结构数据

效果

用法


String jsonStr = "{\"name\":\"aaa\",\"children\":[{\"name\":\"bbb\",\"children\":[{\"name\":\"eee\"},{\"name\":\"fff\",\"children\":[{\"name\":\"iii\"},{\"name\":\"jjj\",\"children\":[{\"name\":\"qqq\"},{\"name\":\"ttt\"}]}]},{\"name\":\"www\"}]},{\"name\":\"ccc\",\"children\":[{\"name\":\"ggg\"},{\"name\":\"hhh\",\"children\":[{\"name\":\"kkk\",\"children\":[{\"name\":\"ttt\"},{\"name\":\"mmm\"}]},{\"name\":\"uuu\"}]},{\"name\":\"ooo\"}]},{\"name\":\"ddd\",\"children\":[{\"name\":\"ggg\"},{\"name\":\"hhh\",\"children\":[{\"name\":\"kkk\"},{\"name\":\"uuu\"}]}]}]}";
Map tree = JSONObject.parseObject(jsonStr, Map.class);
tree2Excel(tree, "E:\\" + System.currentTimeMillis() + ".xls", "name", "children");

源码


package pers.xxx.demo.tree2excel;
 
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
 

@SuppressWarnings("ALL")
public class Tree2ExcelUtil {
 
    
    public static boolean tree2Excel(Map tree, String filePath) {
        return tree2Excel(tree, filePath, null, null);
    }
 
    
    public static boolean tree2Excel(Map tree, String filePath, String lableName, String childrenName) {
        if (isBlank(filePath)) {
            System.err.println("文件名称不能为空");
            return false;
        }
        try {
            doSame(tree, lableName, childrenName);
            createExcel(filePath, tree);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
 
    
    public static Workbook tree2Worbook(Map tree, String fileSuf) {
        return tree2Worbook(tree, fileSuf, null, null);
    }
 
    
    public static Workbook tree2Worbook(Map tree, String fileSuf, String lableName, String childrenName) {
        if (isBlank(fileSuf)) {
            System.err.println("必须指定文件后缀");
            return null;
        }
        try {
            doSame(tree, lableName, childrenName);
            return procesData(tree, fileSuf);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
 
    //具体实现
 
    
    private static int maxCol = 0;
    private static String lableName = "lable";
    private static String childrenName = "children";
    private static final String COL = "col";
    private static final String ROW = "row";
    private static final String ROW_OFT = "rowOft";
    private static final String ROW_SIZE = "rowSize";
 
 
    private static void doSame(Map tree, String lableName, String childrenName) {
        if (!isBlank(lableName)) {
            Tree2ExcelUtil.lableName = lableName;
        }
        if (!isBlank(childrenName)) {
            Tree2ExcelUtil.childrenName = childrenName;
        }
        coreAlgoCol(tree, 1);
        coreAlgoRow(tree);
    }
 
    
    private static void coreAlgoCol(Map tree, int col, Map... trees) {
        tree.put(COL, col);
        Object childrenObj = tree.get(childrenName);
        if (childrenObj != null) {
            List<Map> children = (List<Map>) childrenObj;
            if (children.size() > 0) {
                int size = children.size() * 2 - 1;
                tree.put(ROW_SIZE, size);
                int len = trees != null ? trees.length + 1 : 1;
                Map[] arrData = new Map[len];
 
                if (trees != null && trees.length > 0) {
                    for (int i = 0; i < trees.length; i++) {
                        Map tree1 = trees[i];
                        tree1.put(ROW_SIZE, toInt(tree1.get(ROW_SIZE), 1) + size - 1);
                        arrData[i] = tree1;
                    }
                }
                arrData[len - 1] = tree;
                for (Map tree1 : children) {
                    int newCol = col + 1;
                    if (newCol > maxCol) {
                        maxCol = newCol;
                    }
                    coreAlgoCol(tree1, newCol, arrData);
                }
            }
        }
    }
 
    
    private static void coreAlgoRow(Map tree) {
        if (toInt(tree.get(ROW)) == 0) {
            tree.put(ROW, Math.round(toInt(tree.get(ROW_SIZE), 1) / 2.0f));
        }
        Object childrenObj = tree.get(childrenName);
        if (childrenObj != null) {
            List<Map> children = (List<Map>) childrenObj;
            if (children.size() > 0) {
                int tempOft = toInt(tree.get(ROW_OFT));
                for (Map tree1 : children) {
                    int rowSize = toInt(tree1.get(ROW_SIZE), 1);
                    tree1.put(ROW_OFT, tempOft);
                    tree1.put(ROW, tempOft + Math.round(rowSize / 2.0f));
                    tempOft += rowSize + 1;
                    coreAlgoRow(tree1);
                }
            }
        }
    }
 
    
    private static void createExcel(String filePath, Map tree) throws IOException {
        File file = new File(filePath);
        boolean bfile = file.createNewFile();
        // 复制模板到新文件
        if (bfile) {
            Workbook wk = procesData(tree, filePath);
            if (wk != null) {
                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(file);
                    wk.write(fos);
 
                    fos.flush();
                } finally {
                    closeStream(fos);
                    wk.close();
                }
            }
        }
    }
 
 
    
    private static Workbook procesData(Map tree, String fileName) {
 
        Workbook wk = null;
        if (fileName.endsWith("xls")) {
            wk = new HSSFWorkbook();
        }
        if (fileName.endsWith("xlsx")) {
            wk = new XSSFWorkbook();
        }
        if (wk == null) {
            System.err.println("文件名称不正确");
            return null;
        }
 
        //创建一个sheet页
        Sheet sheet = wk.createSheet("Sheet1");
 
        int colSize = maxCol * 2 + 2;
        int rowSize = toInt(tree.get(ROW_SIZE), 1);
        for (int i = 0; i <= rowSize; i++) {
            Row row = sheet.createRow(i);
            for (int j = 0; j <= colSize; j++) {
                row.createCell(j);
            }
        }
        //配置单元格背景色
        CellStyle style1 = wk.createCellStyle();
        style1.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
        style1.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        CellStyle style2 = wk.createCellStyle();
        style2.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
        style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
 
        dealCell(sheet, tree, style1, style2);
 
        return wk;
    }
 
    
    private static void dealCell(Sheet sheet, Map tree, CellStyle style1, CellStyle style2) {
        Row row = sheet.getRow(toInt(tree.get(ROW)));
        int oftCol = (toInt(tree.get(COL)) - 1) * 2 + 1;
        Cell cell = row.getCell(oftCol);
        cell.setCellStyle(style1);
        cell.setCellValue(String.valueOf(tree.get(lableName)));
 
        sheet.setColumnWidth(oftCol, 256 * 20);
 
        Object childrenObj = tree.get(childrenName);
        if (childrenObj != null) {
            List<Map> children = (List<Map>) childrenObj;
            if (children.size() > 0) {
                int size = children.size();
 
                int startRow = toInt(children.get(0).get(ROW));
                int endRow = toInt(children.get(size - 1).get(ROW));
                int col = oftCol + 1;
                sheet.setColumnWidth(col, 256);
                for (; startRow <= endRow; startRow++) {
                    sheet.getRow(startRow).getCell(col).setCellStyle(style2);
                }
 
                for (Map child : children) {
                    dealCell(sheet, child, style1, style2);
                }
            }
        }
    }
 
    private static int toInt(Object val) {
        return toInt(val, 0);
    }
 
    private static int toInt(Object val, Integer defVal) {
        try {
            return Integer.parseInt(String.valueOf(val));
        } catch (NumberFormatException ignored) {
        }
        return defVal;
    }
 
    private static boolean isBlank(String str) {
        return str == null || str.trim().length() == 0;
    }
 
    
    public static void closeStream(Closeable... closeables) {
        for (Closeable closeable : closeables) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
}

总结

到此这篇关于Java树形结构数据生成导出excel文件的文章就介绍到这了,更多相关Java树形结构数据生成导出excel内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     807人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     351人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     314人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     433人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     221人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯