1、简单的Excel地址导入与树状结构生成

article/2025/8/21 23:17:11

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

一、地区表结构

DROP TABLE IF EXISTS `pro_area`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pro_area` (`area_id` bigint(30) NOT NULL AUTO_INCREMENT COMMENT '主键ID',`area_code` varchar(64) NOT NULL COMMENT '地区编号',`parent_code` varchar(64) NOT NULL COMMENT '父分类编号 一级地区父地区编号=-1',`area_name` varchar(100) NOT NULL COMMENT '地区名称',`area_state` int(2) DEFAULT NULL COMMENT '状态:1:未启用 2:已启用 9:删除',`create_time` timestamp NULL DEFAULT NULL COMMENT '创建时间',`update_time` timestamp NULL DEFAULT NULL COMMENT '修改时间',PRIMARY KEY (`area_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3424 DEFAULT CHARSET=utf8 COMMENT='地区表';

二、导入的excel表结构

211102_SSCd_3551274.png

三、导入本地数据到库

public class MyBatisTest {public SqlSessionFactory getSqlSessionFactory() throws IOException {  String resource = "mybatis-config.xml";  InputStream inputStream = Resources.getResourceAsStream(resource);  return new SqlSessionFactoryBuilder().build(inputStream);  } /*** 3、导入区县* @throws Exception*/@Testpublic void insertCountyBatch()throws Exception{SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();  SqlSession openSession = sqlSessionFactory.openSession();InputStream inp = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\地址1.xlsx"));Workbook workbook=new XSSFWorkbook(inp);Sheet sheet = workbook.getSheetAt(0);Map<String,String> currentMap = new HashMap<>();for(int i=sheet.getFirstRowNum();i<=sheet.getLastRowNum();i++) {Row currRow = sheet.getRow(i);Cell currentCell = currRow.getCell(2);Cell parentCell = currRow.getCell(1);Cell ancestorCell = currRow.getCell(0);if(currentCell.getCellType()!=Cell.CELL_TYPE_BLANK) {currentMap.put(ancestorCell.getStringCellValue()+"_"+parentCell.getStringCellValue()+"-"+currentCell.getStringCellValue(), currentCell.getStringCellValue());}}List<ProArea> list = new ArrayList<>();Iterator it = currentMap.entrySet().iterator();ProArea proArea = null;while(it.hasNext()) {Map.Entry<String, String> node = (Entry<String, String>) it.next();proArea = new ProArea();proArea.setAreaCode(UUID.randomUUID().toString());proArea.setAreaName(node.getValue());proArea.setAreaState(2);proArea.setCreateTime(new Date(System.currentTimeMillis()));//查询parentCodeMap<String,String> params = new HashMap<>();String ancestorName = node.getKey().substring(0, node.getKey().indexOf("_"));String parantName = node.getKey().substring(node.getKey().indexOf("_")+1, node.getKey().indexOf("-"));params.put("parentName", parantName);params.put("ancestorName", ancestorName);String parentCode = openSession.selectOne("com.lee.poi.AreaMapper.selectAreaCodeByPNameAndAName",params);proArea.setParentCode(parentCode);list.add(proArea);}Integer insertCountyRes = openSession.insert("com.lee.poi.AreaMapper.insertAreaBatch", list);//关闭连接openSession.commit();openSession.close();}/*** 2、导入市*/@Testpublic void insertCityBatch()throws Exception {SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();  SqlSession openSession = sqlSessionFactory.openSession();InputStream inp = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\地址1.xlsx"));Workbook workbook=new XSSFWorkbook(inp);Sheet sheet = workbook.getSheetAt(0);Map<String,String> currentMap = new HashMap<>();for(int i=sheet.getFirstRowNum();i<=sheet.getLastRowNum();i++) {Row currRow = sheet.getRow(i);Cell currentCell = currRow.getCell(1);Cell parentCell = currRow.getCell(0);if(currentCell.getCellType()!=Cell.CELL_TYPE_BLANK) {currentMap.put(parentCell.getStringCellValue()+"-"+currentCell.getStringCellValue(), currentCell.getStringCellValue());}}List<ProArea> list = new ArrayList<>();Iterator it = currentMap.entrySet().iterator();ProArea proArea = null;while(it.hasNext()) {Map.Entry<String, String> node = (Entry<String, String>) it.next();proArea = new ProArea();proArea.setAreaCode(UUID.randomUUID().toString());proArea.setAreaName(node.getValue());proArea.setAreaState(2);proArea.setCreateTime(new Date(System.currentTimeMillis()));//查询parentCodeString parentCode = openSession.selectOne("com.lee.poi.AreaMapper.selectAreaCodeByName",node.getKey().substring(0, node.getKey().indexOf("-")));proArea.setParentCode(parentCode);list.add(proArea);}Integer insertCityRes = openSession.insert("com.lee.poi.AreaMapper.insertAreaBatch", list);//关闭连接openSession.commit();openSession.close();}/*** 1、导入省*/@Testpublic void insertProvinceBatch()throws Exception {SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();  SqlSession openSession = sqlSessionFactory.openSession();InputStream inp = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\地址1.xlsx"));Workbook workbook=new XSSFWorkbook(inp);Sheet sheet = workbook.getSheetAt(0);Map<String,String> currentMap = new HashMap<>();for(int i=sheet.getFirstRowNum();i<=sheet.getLastRowNum();i++) {Row currRow = sheet.getRow(i);Cell currentCell = currRow.getCell(0);if(currentCell.getCellType()!=Cell.CELL_TYPE_BLANK) {currentMap.put(currentCell.getStringCellValue(), currentCell.getStringCellValue());}}List<ProArea> list = new ArrayList<>();Iterator it = currentMap.entrySet().iterator();ProArea proArea = null;while(it.hasNext()) {Map.Entry<String, String> node = (Entry<String, String>) it.next();proArea = new ProArea();proArea.setAreaCode(UUID.randomUUID().toString());proArea.setAreaName(node.getValue());proArea.setAreaState(2);proArea.setCreateTime(new Date(System.currentTimeMillis()));proArea.setParentCode("-1");list.add(proArea);}Integer insertProvinceRes = openSession.insert("com.lee.poi.AreaMapper.insertAreaBatch", list);//关闭连接openSession.commit();openSession.close();}}

四、对应的mapper文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  <mapper namespace="com.lee.poi.AreaMapper">  <select id="selectAreaByParentCode" parameterType="java.lang.String" resultType="com.lee.poi.ProArea">select * from pro_area where parent_code = #{parentCode}</select><!-- 根据父级名称查询code --><select id="selectAreaCodeByName" parameterType="java.lang.String" resultType="java.lang.String">select area_code from pro_area where area_name = #{areaName}</select><!-- 根据父级名称 和  父级的父级名称查询code --><select id="selectAreaCodeByPNameAndAName" parameterType="java.util.Map" resultType="java.lang.String">select p1.area_code from pro_area p1inner join pro_area p2 on p1.parent_code = p2.area_codewhere p1.area_name=#{parentName} and p2.area_name=#{ancestorName}</select><select id="selectProAreaTree" parameterType="java.util.Map" resultType="com.lee.poi.ProAreaTree">select area_code as value,parent_code as parentCode,area_name as text    	from pro_area where parent_code = #{parentCode}order by convert(text using gbk) asc</select><insert id="insertAreaBatch" parameterType="java.util.List" useGeneratedKeys="true" keyProperty="areaId">insert into pro_area(area_code,parent_code,area_name,area_state,create_time)values<foreach collection="list" item="proArea" index="index" separator=",">(#{proArea.areaCode},#{proArea.parentCode},#{proArea.areaName},#{proArea.areaState},#{proArea.createTime})</foreach></insert></mapper> 

 

 

五、导入后的表内容

211248_GMdZ_3551274.png

六、生成树结构

public class MyBatisTest2 {public SqlSessionFactory getSqlSessionFactory() throws IOException {  String resource = "mybatis-config.xml";  InputStream inputStream = Resources.getResourceAsStream(resource);  return new SqlSessionFactoryBuilder().build(inputStream);  } /*** 4、地址树状结构*/@Testpublic void findProAreaTree()throws Exception {SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();  SqlSession openSession = sqlSessionFactory.openSession();Map<String,Object> params = new HashMap<>();params.put("parentCode", "-1");List<ProAreaTree> nodes = openSession.selectList("com.lee.poi.AreaMapper.selectProAreaTree", params);findTree(nodes,openSession);System.out.println(JSON.toJSONString(nodes));//关闭连接openSession.commit();openSession.close();}private void findTree(List<ProAreaTree> parentNodes,SqlSession openSession) {if(parentNodes!=null && parentNodes.size()>0) {List<ProAreaTree> nodes = new ArrayList<>();Map<String,Object> params = null;for(int i=0;i<parentNodes.size();i++) {params = new HashMap<>();params.put("parentCode", parentNodes.get(i).getValue());nodes = openSession.selectList("com.lee.poi.AreaMapper.selectProAreaTree", params);parentNodes.get(i).setChildren(nodes);findTree(nodes,openSession);}}}}

七、生成的树结构

211610_pIem_3551274.png211655_VSvJ_3551274.png

 

 

转载于:https://my.oschina.net/u/3551274/blog/1634836


http://chatgpt.dhexx.cn/article/DSuIpr4p.shtml

相关文章

树状结构导出到excel表格

/**获取导出实例 */async getAllInstances(SlotId) {//SlotId 数据库词槽idlet result:any [] //导出的数据模块const allData await this.getSimpleInstance(SlotId)//allData根据数据库词槽ID查询到的树状结构数据let count 1//fn 是递归的函数let fn (data, objc,count)…

Excel树状数据绘制导出

//存放数据的二维集合&#xff0c;twoDimensional 中每个List是树状结构的一个分支的所有数据List<List<JSONObject>> twoDimensional new ArrayList<>();//创建对象XSSFWorkbook xwb new XSSFWorkbook();//创建工作表Sheet sheet xwb.createSheet("…

将excel树形结构的数据导入数据库

因为工作需要&#xff0c;用户需要将产品分类通过excel表格导入到数据库中&#xff0c;而产品分类又有一、二、三、四、五级分类。最终通过各种尝试终于实现了数据导入。因此记录下来。 一、excel模板数据结构和数据库表结构介绍 1、 待导入excel模板数据&#xff1a; 2、数据…

关于excel多层级(树形)数据结构,提取成树形结构数据并导出到数据库

在开发中遇到一个问题&#xff0c;就是有一张excel表中的数据时多层级的&#xff0c;不是普通一行一行的&#xff0c;而是&#xff0c;一行对应多行&#xff0c;多行之中的每一行在对应多行数据。形成树形结构&#xff1a; 如上图所示&#xff1a;我遇到的excel表的结构&#x…

使用excel插件treeplan构建决策树

Treeplan是一种构建决策树的很轻巧的excel插件&#xff0c;可以做出比较规范的决策树&#xff0c;并可以自动计算结果。下面以excel2003为例&#xff08;07也可正常使用&#xff09;介绍其使用方法。 一&#xff0e;加载treeplan插件 工具&#xff08;菜单&#xff09;——加载…

EXCEL(VBA)画树程序

看了好多Python写的画树&#xff0c;想看看在Excel里画个树行不行&#xff0c;于是乎花了点时间用VBA写了个&#xff0c;效果还不错&#xff0c;截个图给大家看看。 绿色固定配色版效果&#xff1a; 随机颜色版效果&#xff1a; 附上主代码 Sub test() 画树主程序 作者&#…

Java 树形结构数据生成导出excel文件

效果 用法 String jsonStr "{\"name\":\"aaa\",\"children\":[{\"name\":\"bbb\",\"children\":[{\"name\":\"eee\"},{\"name\":\"fff\",\"children\"…

python 根据树型结构生成指定格式的excel数据

数据 tree {a: {a1: [(a1a, 1)],a2: [(a2a, 1),(a2b, 2),]},b: {b1: [(b1b, 1)],b2: [(b2b, 1)]} }excel 数据格式 代码实现 import xlrd from xlutils.copy import copyold_excel xlrd.open_workbook(1.xls) new_excel copy(old_excel) ws new_excel.get_sheet(0)def wr…

人工智能-高等数学之导数篇

高等数学之导数篇 线性代数的学习基本就先告一个段落了&#xff0c;接着学最重要的微积分&#xff0c;高等数学里的重中之重&#xff0c;也是近代科学的发展利器&#xff0c;微积分主要包括包括极限、微分学、积分学及其应用&#xff0c;而微分学包括求导数的运算&#xff0c;…

机器学习之数学基础 一 .导数

简单的说,导数是曲线的斜率,是曲线变化快慢的反应. 2阶导数是斜率变化快慢的反应,反应曲线的凸凹性 例如:加速度的方向总是指向轨迹曲线凹的一侧. 导数(Derivative)是微积分学中重要的基础概念.一个函数在某一点的导数描述了这个函数在这一点附近的变化率.导数的本质是通过极…

【数值优化之范数与导数】

本文参考书籍《最优化计算方法》 这一部分会介绍一些最优化需要用到的基本数学概念。 目录 1 范数 1.1 向量范数 1.2 矩阵范数 1.3 矩阵内积 2 导数 2.1 梯度与海瑟矩阵 2.2 矩阵变量函数的导数 1 范数 1.1 向量范数 范数相当于是从向量空间到实数域的映射&#xff…

微积分——什么是导数

目录 1. “导数(derivative)”名称的由来 1.1 “derivative”的词源 1.2 “derivative”的数学意义来源 1.3 “derivative”中文翻译为“导数” 2. “导数(derivative)”的数学意义 1. “导数(derivative)”名称的由来 1.1 “derivative”的词源 作为名词&#xff0c;始于…

一阶导数

本文引用与百度百科。 简介 导数&#xff08;英语&#xff1a;Derivative&#xff09;是微积分学中重要的基础概念。一个函数在某一点的导数描述了这个函数在这一点附近的变化率。导数的本质是通过极限的概念对函数进行局部的线性逼近。当函数 f 的自变量在一点 x0 上产生一个…

AI笔记: 数学基础之方向导数的计算和梯度

方向导数 定理 若函数f(x,y,z)在点P(x,y,z)处可微&#xff0c;沿任意方向l的方向导数 ∂ f ∂ l ∂ f ∂ x c o s α ∂ f ∂ y c o s β ∂ f ∂ z c o s γ \frac{\partial f}{\partial l} \frac{\partial f}{\partial x} cos \alpha \frac{\partial f}{\partial y} c…

图像处理之_导数微分

1. 一阶导数应用&#xff1a;图像的梯度 1) 用途: 在图像处理中, 常用梯度求取图像的边缘, 这是一个很基础的应用. 下图为在OpenCV中使用cvSobel()函数的具体效果. 四张图分别为: 原图, 在x方向上的梯度, y方向上的梯度, xy方向上的梯度. 2) 二元函数 这里我们只讨论二元…

如何理解微分、差分、导数

先说差分和微分 自变量x的差分就是微分 即&#xff1a; Δxdx 因变量y的差分是函数y的变化量 即 Δyy(xΔx)-y(x) 因变量y的微分是指函数图像在某一点处的切线在横坐标取得增量Δx以后&#xff0c;纵坐标取得的增量dy。 dyf(x)dx 总结&#xff1a; 微分是差分的线…

神经网络学习之导数

在神经网络中&#xff0c;有一个常用的激活函数sigmoid函数&#xff0c;这个函数在高等数学中应该是有的&#xff0c;只是当时没有理会。函数图像如下&#xff0c;本文主要主要梳理下相应的数学知识&#xff0c;具体的应用在后续的文章中会涉及。 本文涉及到数学公式&#xff…

Matlat计算符号导数

MATLAB提供用于计算符号导数的diff命令。 如下&#xff1b;指定t为变量&#xff0c;输入一个函数表达式&#xff0c;使用diff(f)求其导数&#xff1b; 再计算一个&#xff1b; 输入一些常用函数&#xff0c;查看其导数&#xff1b;例如sin(x)的导数是cos(x)&#xff0c;cos(x…

R语言数值导数

文章目录 3 数值导数 3 数值导数 根据导数的定义&#xff0c;当函数的定义域不连续时&#xff0c;其不连续处显然是不存在导数的&#xff0c;但图形可以“欺骗”我们的眼睛。 > x seq(-1,1,0.1) > y sin(x) > y1 cos(x) > xEnd x0.1 > yEnd yy1*0.1 >…