来自CSDN-Mr熊

https://blog.csdn.net/qq_41030861/article/details/80515984

谁能告诉我前面这一堆都是什么啊。。。

python读取Excel中关联表格的数据(只要是同Excel中)---可以解决无限次同一个Excel中跨sheet或同sheet中表格关联--

1.读取关联表格代码(再import openpyxl库的前提下)

#######################################################
#coding=utf-8
import os
import random
import string
import openpyxl
from openpyxl import *
from openpyxl.reader.excel import load_workbook
from openpyxl.compat import range
from openpyxl.cell.read_only import EMPTY_CELL
import win32com.client
from openpyxl import Workbook
from openpyxl.utils import get_column_letter
from openpyxl.utils import column_index_from_string
import sys
reload(sys)
sys.setdefaultencoding( "GBK" )
def Rir_sheet(wb,sheet_name,rc):
    sheet = wb[sheet_name]
    sheetdata = wb[sheet_name]
    url = str(rc)
    chrvalue = ""
    for i in url:
        if "a" <= i and i <= "z" or i >= 'A' and i <= 'Z':
            chrvalue = chrvalue + i
    cellvalue = sheetdata.cell(row=int(url.strip(chrvalue)), column=column_index_from_string(chrvalue)).value.decode(
        'GBK')
    if "!" in cellvalue and cellvalue[0] == "=":
        sheetvalue = cellvalue.split("!")[0].strip("=")
        return Rir_sheet(wb, sheetvalue, cellvalue.split("!")[1])
    elif "!" not in cellvalue and cellvalue[0] == "=":
        return Rir_cell(wb, sheet_name, cellvalue.strip('='))
    else:
        return cellvalue
def Rir_cell(wb,sheet_name,rc):
    ws=wb[sheet_name]
    url = str(rc)
    chrvalue = ""
    for i in url:
        if "a" <= i and i <= "z" or i >= 'A' and i <= 'Z':
            chrvalue = chrvalue + i
    cellvalue = ws.cell(row=int(url.strip(chrvalue)), column=column_index_from_string(chrvalue)).value.decode('GBK')
    if "!" in cellvalue and cellvalue[0] == "=":
        sheetvalue = cellvalue.split("!")[0].strip("=")
        return Rir_sheet(wb, sheetvalue, cellvalue.split("!")[1])
    elif "!" not in cellvalue and cellvalue[0] == "=":
        return Rir_cell(wb,sheet_name,cellvalue.strip('='))
    else:
        return cellvalue
if __name__ == '__main__':
    wb = openpyxl.load_workbook(u'C://Users/Administrator//Desktop//测试文档.xlsx')
    print Rir_cell(wb,'Sheet2',"D2")
#######################################################
2.实际项目中的代码如下
#######################################################
#coding=utf-8
import os
import random
import string
import openpyxl
from openpyxl.reader.excel import load_workbook
from openpyxl.compat import range
from openpyxl.cell.read_only import EMPTY_CELL
from openpyxl.utils import column_index_from_string
import win32com.client
import sys
reload(sys)
sys.setdefaultencoding( "UTF-8" )
#获取Excel中数据
# 返回值形如:
# =[{A1:A2,B1:B2,C3:C2,...},{A1:A3,B1:B3,C3:C3,...},{A1:A4,B1:B4,C3:C4,...},....]
def GetSheetData( file_path, sheet_name):
    wb = openpyxl.load_workbook(file_path)
    # 获取workbook中所有的表格
    sheets = wb.sheetnames
    # 按照指定sheet_name去查询
    sheet = wb[sheet_name]
    # 统计第一行中字段多少,一遍后面使用
    column_names = []
    for r in range(1, sheet.max_column + 1):
        column_names.append(str(sheet.cell(row=1, column=r).value))
    column_num = len(column_names)
    list = []
    if sheet_name in sheets:
        sheet = wb[sheet_name]
        for r in range(2, sheet.max_row + 1):
            dict = {}
            for c in range(1, sheet.max_column + 1):
                if str(sheet.cell(row=r, column=c).value) == "None":
                    dict[column_names[c - 1].decode('UTF-8')] = ""
                else:
                    cellvalue = str(sheet.cell(row=r, column=c).value).decode('UTF-8')
                    if "!" in cellvalue and cellvalue[0] == "=":  # 判断数据是否是关联不同sheet页单元格数据,是就是下面方式处理
                        sheetvalue = cellvalue.split("!")[0].strip("=")
                        if sheetvalue in sheets:  # 判断获取的sheet页是否在本Excel中是否存字,存在就调用Rir_sheet(wb,sheet_name,rc)方法
                            dict[column_names[c - 1].decode('UTF-8')] = Rir_sheet(wb, sheetvalue,
                                                                                  cellvalue.split("!")[1])
                        else:
                            dict[column_names[c - 1].decode('UTF-8')] = cellvalue
                    elif "!" not in cellvalue and cellvalue[0] == "=":  # 判断数据是否是关联不同sheet页单元格数据,是就是下面方式处理
                        dict[column_names[c - 1].decode('UTF-8')] = Rir_cell(wb, sheet_name, cellvalue.strip('='))
                    else:  # 如果无关联就直接存字
                        dict[column_names[c - 1].decode('UTF-8')] = cellvalue
                num = 0
                for i in dict.values():
                    if len(i.replace(" ", '')) == 0:
                        num = num + 1
                if num != column_num:
                    list.append(dict)
        return list
    else:
        print 'your input not in sheets'

#######同一个Excel中,不同sheet页的单元格之间的关联值获取########
def Rir_sheet( wb, sheet_name, rc):
    sheet = wb[sheet_name]
    sheetdata = wb[sheet_name]
    url = str(rc)
    chrvalue = ""
    for i in url:
        if "a" <= i and i <= "z" or i >= 'A' and i <= 'Z':
            chrvalue = chrvalue + i
    cellvalue = sheetdata.cell(row=int(url.strip(chrvalue)), column=column_index_from_string(chrvalue)).value.decode(
        'UTF-8')
    if "!" in cellvalue and cellvalue[0] == "=":
        sheetvalue = cellvalue.split("!")[0].strip("=")
        return Rir_sheet(wb, sheetvalue, cellvalue.split("!")[1])
    elif "!" not in cellvalue and cellvalue[0] == "=":
        return Rir_cell(wb, sheet_name, cellvalue.strip('='))
    else:
        return cellvalue

#######同一个Excel中,相同sheet页的单元格之间的关联值获取########
def Rir_cell( wb, sheet_name, rc):
    ws = wb[sheet_name]
    url = str(rc)
    chrvalue = ""
    for i in url:
        if "a" <= i and i <= "z" or i >= 'A' and i <= 'Z':
            chrvalue = chrvalue + i
    cellvalue = ws.cell(row=int(url.strip(chrvalue)), column=column_index_from_string(chrvalue)).value.decode('UTF-8')
    if "!" in cellvalue and cellvalue[0] == "=":
        sheetvalue = cellvalue.split("!")[0].strip("=")
        return Rir_sheet(wb, sheetvalue, cellvalue.split("!")[1])
    elif "!" not in cellvalue and cellvalue[0] == "=":
        return Rir_cell(wb, sheet_name, cellvalue.strip('='))
    else:
        return cellvalue
if __name__ == '__main__':
    a=GetSheetData(u'C://Users/Administrator//Desktop//测试文档.xlsx','Sheet2')
    print a[0]['colum6']
    print a[0]['colum2']
    print a[0]['colum3']
    print a[0]['colum4']
--------------------- 
作者:Mr熊 
来源:CSDN 
原文:https://blog.csdn.net/qq_41030861/article/details/80515984 
版权声明:本文为博主原创文章,转载请附上博文链接!

python读取Excel中关联表格的数据(只要是同Excel中相关推荐

  1. python读取Excel中关联表格的数据(只要是同Excel中)---可以解决无限次同一个Excel中跨sheet或同sheet中表格关联--

    1.读取关联表格代码(再import openpyxl库的前提下)####################################################### #coding=utf ...

  2. 将Excel中一个表格的数据关联到另一个表格

    将Excel中一个表格的数据关联到另一个表格 1.表1样例,表1和表2有关联字段工号 2.表2样例 3.表1中选中B2单元格---公式---函数---查找与引用---VLOOKUP---确定 4.lo ...

  3. 使用Python批量筛选上千个Excel文件中的某一行数据并另存为新Excel文件(下篇)

    点击上方"Python爬虫与数据挖掘",进行关注 回复"书籍"即可获赠Python从入门到进阶共10本电子书 今 日 鸡 汤 野火烧不尽,春风吹又生. 大家好, ...

  4. python读取word文档表格里的数据

    首先需要安装相应的支持库: 直接在命令行执行pip install python-docx 示例代码如下: import docx from docx import Document #导入库path ...

  5. 最优控制电池储能模型 蓄电池储能模型的最优控制python源代码 包含五个python脚本,它从data .csv读取价格、负载和温度数据。 然后用本文中描述的决策变量、目标和约束构造一个pyomo抽

    最优控制电池储能模型 蓄电池储能模型的最优控制python源代码,代码按照高水平文章复现 包含五个python脚本,它从data .csv读取价格.负载和温度数据. 然后用本文中描述的决策变量.目标和 ...

  6. python读取文件某一行-使用python读取.text文件特定行的数据方法

    如何用python循环读取下面.txt文件中,用红括号标出来的数据呢? 首先,观察数据可知,不同行的第一个数据元素不一样,所以考虑直接用正则表达式. 再加上,对读和写文件的操作,就行了 注:我用的是p ...

  7. python读取文件多行内容-使用python读取.text文件特定行的数据方法

    如何用python循环读取下面.txt文件中,用红括号标出来的数据呢? 首先,观察数据可知,不同行的第一个数据元素不一样,所以考虑直接用正则表达式. 再加上,对读和写文件的操作,就行了 注:我用的是p ...

  8. 计算机表格怎么排金额,excel表格的数据怎样计算总额-excel表格、如何自动计算、金额...

    excel下把表格的数据如何汇总,合计 excel怎么快速计算相同名字的数据总和,全部列出来 1.利用sum函数(求和函来进行计算,同理先打开要编辑的Excel,选一个计算总分的单元格,如图所示. 2 ...

  9. 数组x中数据复制到数组y中,重复的数据只存储一次,最后输出y;计算x中数据的平均值ave及大于平均值的元素个数n。c++实现

    题目描述 编程序,实现如下功能: (1)定义两个一维数组x,y,不超过50个元素. (2)从键盘输入k个整数到数组x中. (3)计算x中数据的平均值ave及大于平均值的元素个数n并输出. (4)将数组 ...

最新文章

  1. vue中利用scss实现整体换肤和字体大小设置
  2. 【bzoj5016】[Snoi2017]一个简单的询问 莫队算法
  3. python分词代码_中文分词--最大正向匹配算法python实现
  4. SSH Secure Shell Client中文乱码的解决办法
  5. 第二天linux,yum源配置和ftp部分设置
  6. 基于XMLHttpRequest封装Ajax请求
  7. c++ 应输入表达式_【C语言编程入门系列】—— 第五章,C语言基本运算和表达式(一)...
  8. CentOS7:Ruby安装
  9. Captura录屏没有声音解决方法
  10. Oracle的overlaps函数转换其他数据库语法
  11. 修改form表单action路径
  12. 外贸怎么开发客户?这些你不一定知道
  13. [转]windows 7 professional 64 bit SP1 change system language(sucess)
  14. 内网直播局域网直播校园直播播控系统如何建设
  15. 阿里云块存储团队卓越工程实践
  16. vop破芙工艺-注意事项
  17. MYSQL/ORACLE/SQL SERVER的默认端口号
  18. 大数据架构之--Kappa架构
  19. 阿里java面试复盘 | 三面解说(已通过)
  20. Jitsi Meet视频通话Ubuntu环境搭建全过程

热门文章

  1. ios支付宝支付--看我就够了
  2. awd——waf部署
  3. 解决win10升级补丁后共享打印机0x0000011b报错问题最简单解决方法,不需要卸载补丁
  4. 解决sublime无法下载插件问题
  5. 动环监控串口,动环监控系统接口
  6. 来看一个费解而有趣的c++现象
  7. 虚拟机Linux上网ping百度跳过的坑,亲测有效
  8. C语言小游戏————贪吃蛇.c
  9. Twitter Storm: DRPC学习
  10. js调用(前/后)摄像头,截取照片,关闭摄像头