python xlrd - 循环遍历excel单元格以查找数据范围

问题描述 投票:0回答:1

我正试图找到一种从excel文件列表中提取数据的方法,我已经能够加载工作簿,选择工作表并从某个单元格中提取,但我遇到了问题,因为文件不是格式化数据库,更像是重复描述的实例,事情是,我需要找到一种方法来获取实例的重复次数,以便在每个像这样的东西中提取某个单元格:

enter image description here

一些文件有一个实例,其他5或6,我尝试了一个while循环,但它似乎没有工作:

import xlrd
from os import listdir, chdir

dir = chdir"r"/home/fcr/anaconda3/envs/Arch/calam")

lista = []

for arc in listdir(dir):
    x = xlrd.open_workbook(arc)
    sh = x.sheet_by_index(0)
    for r in range(4, 500, 18):
        v = sh.cell(r, 10).value
        while v != " "
            lista.append(v)

print(lista)

现在我正在尝试一个if语句,其中我将总行除以单元格之间的间隔(18,找到重复的数量,但似乎我遗漏了一些东西

import xlrd
from os import listdir, chdir

dir = chdir"r"/home/fcr/anaconda3/envs/Arch/calam")

lista = []

for arc in listdir(dir):
    x = xlrd.open_workbook(arc)
    sh = x.sheet_by_index(0)
    tram = int(sh.rows/17)
    c3 = []
    if tram > 1 and tram < 2:
        v = sh.cell(4, 10).value
        c3.append(v)
    if tram > 2 and tram < 3:
        v = sh.cell(4, 10).value
        j = sh.cell(22, 10).value
        c3.append(v)
        c3.append(j)
    if tram > 3 and tram < 4:
        v = sh.cell(4, 10).value
        j = sh.cell(22, 10).value
        h = sh.cell(40, 10).value
        c3.append(v)
        c3.append(j)
        c3.append(h)
    else:
        print("x")
    print(c3)

谢谢

python excel xlrd
1个回答
0
投票

我找到了一种方法,如果它对任何人都有用,根据工作表行循环,然后将其写入excel文件:

import xlrd
from os import listdir, chdir
from openpyxl import Workbook


dir = chdir(r"/home/fcr/anaconda3/envs/002/Arch/cal")

lista = []

for arc in listdir(dir):
    x = xlrd.open_workbook(arc)
    sh = x.sheet_by_index(0)
    ntram = sh.nrows
    for r in range(4, ntram, 18):
        call = []
        v = sh.cell(r, 10).value
        tram = sh.cell(r-1, 0).value
        cini = sh.cell(r-1, 1).value
        cterm = sh.cell(r-1, 2).value
        npist = sh.cell(r-1, 5).value
        call.append(arc.strip(".xlsx"))
        call.append(v)
        call.append(tram)
        call.append(cini)
        call.append(cterm)
        call.append(npist)
        lista.append(call)


print(lista)

columns = ["CALLE",  "IND_SERV", "TRAMO", "CALL_INI", "CALL_TER",     "NUM_PIST"]

book = Workbook()
sheet = book.active

sheet.append(columns)

for pe in lista:
    sheet.append(pe)

book.save(r"/home/fcr/anaconda3/envs/002/Arch/LisCal.xlsx")
© www.soinside.com 2019 - 2024. All rights reserved.