Python/Excel自动化文本从2个单元格转换为1个单元格

2024-09-27 00:11:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python自动化使用excel工作表列表创建多个名称标记的过程

我的问题是我需要取'name'列和'enterprise'列的值​​把它们放在新文档的一个单元格里

像这样:

enter image description here

对此:

enter image description here

现在我正在使用openpyxl,虽然我设法转移了其中一个列,但不能同时使用这两个列。 下面的代码是我尝试过的东西之一

import openpyxl as xl

e = xl.load_workbook('etiquetas.xlsx')
eplan = e['Planilha1']

c = xl.load_workbook('Crachá Relação 15.10.19.xlsx')
cplan = c['Plan1']

maxlinhas = cplan.max_row

for i in range (2, maxlinhas+1):
    nome = cplan.cell(row = i, column = 1).value
    preenchernome = eplan.cell(row = i-1, column = 1)
    empresa = cplan.cell(row=i, column=2).value
    preencherempresa = eplan.cell(row=i - 1, column=1)
    preenchernome.value = nome, empresa
e.save('teste.xlsx')

但此代码返回以下错误:

ValueError: Cannot convert ('Gladisson Garcia Westphal', 'Agro Divel') to Excel


Tags: 代码valueloadcellcolumnxlsxrowworkbook
2条回答

根据文档preenchernome.value只能有一个值

试着用这个

preenchernome.value = '{}\n{}'.format(nome, empresa)

传递给目标单元格的值应该是单个字符串。因此:

wksTarget.cell(row = i, column = 1).value = '{}\n{}'.format(name, family)

应该没问题。这就是我的全部代码:

import openpyxl as xl
import os

wbSource = xl.load_workbook(os.path.dirname(os.path.realpath(__file__)) + '\myExcel.xlsx')
wksSourse = wbSource['Sheet1']

wbTarget = xl.load_workbook(os.path.dirname(os.path.realpath(__file__)) + '\Target.xlsx')
wksTarget = wbTarget['Sheet1']

for i in range (1, wksSourse.max_row+1):
    name = wksSourse.cell(row = i, column = 1).value
    family = wksSourse.cell(row = i, column = 2).value

    wksTarget.cell(row = i, column = 1).value = '{}\n{}'.format(name, family)

wbTarget.save(os.path.dirname(os.path.realpath(__file__)) + '\Target.xlsx')
wbTarget.close()

相关问题 更多 >

    热门问题