python-3.x - 新工作表的值
问题描述
我已经开始使用 openpyxl,而且我很喜欢它。
目标是在条件为真时将所有行复制到新工作表,我的代码可以工作,但不是根据条件将值复制到新工作表,而是将所有值复制到同一个工作表。
PS:请原谅我的英文
import openpyxl as excel
def trata_excel(nomeficheiro):
# variable declaration
livro = excel.load_workbook(nomeficheiro)
folha = livro['Folha1']
# it stores the headers and respective column
cabeçalhos = {}
alvos = []
# i'm retriving all the headers from the column
for coluna in range(1,folha.max_column +1):
celula = folha.cell(row=1, column=coluna)
# And add it to the dictionary
cabeçalhos.update({celula.value:coluna})
# checking if header "Alvo" in the dictionary
if "Alvo" in cabeçalhos:
# Getting the column number for the header Alvo
coluna_alvo = cabeçalhos["Alvo"]
# check all the rows to see
for linha in range(2,folha.max_row +1):
# How many Alvo
celula_alvo = folha.cell(linha,coluna_alvo)
# Check if the Alvo is not already in the list
if celula_alvo.value not in alvos:
#if not i'm adding it
alvos.append(celula_alvo.value)
else:
return "Não encontrei a coluna referente a 'Alvo"
#checking whats the "Tipo de Produto" column number
coluna_produto = cabeçalhos["Tipo de Produto"]
# i'm going to check for each Alvo
for alvo in alvos:
# Creating a new sheet with Alvo name
nova_folha = livro.create_sheet(str(alvo))
# for each alvo going to see each line
nova_linha = 1 # variable to add all the lines in consecutive line
for linha in range(2,folha.max_row+1):
produto = folha.cell(linha, coluna_produto)
# here i select the values that i want
if (alvo == celula_alvo.value and produto.value =="Voz" or
alvo == celula_alvo.value and produto.value == "SMS" or
alvo == celula_alvo.value and produto.value=="MMS"):
nova_linha += 1
for coluna in range(1, folha.max_column + 1):
valor = folha.cell(row=linha, column=coluna).value
livro[str(alvo)].cell(row=nova_linha,column=coluna, value= valor)
livro.save("novo.xlsx")
#print(cabeçalhos)
# just to control
print(alvos)
解决方案
推荐阅读
- sql - 如何在子查询中使用 SQL 中的 AND 案例
- javascript - Wasm: Uncaught (in promise) TypeError: Import #0 module="env" error: module is not an object or function Promise.then (async) (anonymous) @ (index):9
- amazon-web-services - DynamoDB 是否支持悲观锁定?
- html - 如何停止用户在 Angular 6 中使用 ngx-international-phone-number 在 html 页面中编辑国家代码
- python - 比较具有不同键的嵌套字典
- php - Laravel 从 2 个表中选择
- asp.net - 将文件从 Angular 5/6 上传到 WebApi c#
- android - 机器学习套件 - Android - 文本识别 - 文本方向
- php - Is it possible to replace a word before a phrase using regular expression in php?
- javascript - Javascript includes() is not a function