狂自私

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

大型xlsx文件内容快速读取

openpyxl的性能还是不够用,我经常会导出很多的xlsx文件获取里面的数据来分析操作。

下面的代码可以直接将xlsx的文本内容直接转为二维列表返回使用:

复制代码
def 获取数据形成二维列表_原封不动版_V2(path:str)->list:
    zip_file= zipfile.ZipFile(path)
    monitor_typeName = os.path.basename(path).split('-')[0]
    # zip_list = zip_file.namelist() # 得到压缩包里所有文件
    #将被压缩的字符串找到
    字段值列表=[]
    filepath = zip_file.extract('xl/sharedStrings.xml')
    with open(filepath,'r',encoding='utf-8') as in_fd:
        lines = in_fd.readlines()
    line=lines[1]
    #妈的,wps会不记录为空的单元格。
    #这里不能如此粗暴,因为一个si下面可能有多个t标签,我被坑到了。
    #    字段值列表 = re.findall('(?<=<t>).+?(?=</t>)',line)
    si_list = re.findall('(?<=<si>).+?(?=</si>)',line)
    for si in si_list:
        temp_list = re.findall('(?<=<t>).+?(?=</t>)',si)
        字段值列表.append(''.join(temp_list))
    os.remove(filepath)
    #汇聚数据
    filepath = zip_file.extract('xl/worksheets/sheet1.xml')
    lines=None
    with open(filepath,'r',encoding='utf-8') as in_fd:
        lines = in_fd.readlines()
    合并为一行之后的字符串 = ''
    for line in lines:
        合并为一行之后的字符串+=line
    sheetData = re.findall(r'<sheetData>.+</sheetData>',合并为一行之后的字符串)[0]
    rows = re.findall(r'<row.+?</row>',sheetData)
    行列表=[]
    for row in rows:
        cells =re.findall(r'<c.+?</c>',row)
        values = re.findall(r'(?<=<v>)[\+\-\d\.]+?(?=</v>)',row)
        temp_list=[]
        for idx in range(len(cells)):
            if('t="s"' in cells[idx]):
                #字符串类型,需要被补足
                temp_list.append(字段值列表[int(values[idx])])
            elif('t="n"' in cells[idx]):
                #数值类型,不需要被补足
                temp_list.append(int(float(values[idx])))
            elif('t=' not in cells[idx]):
                #数值类型,不需要被补足
                temp_list.append(int(float(values[idx])))
            else:
                #其它类型,暂不考虑,但是需要输出,方便后续排查问题
                print(cells[idx])
        行列表.append(temp_list)
    os.remove(filepath)
    zip_file.close()
    return 行列表;
复制代码

 

posted on   狂自私  阅读(32)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2022-10-31 C#-根据word页面内容打印每一页为PDF
点击右上角即可分享
微信分享提示