【问题标题】:Python / Excel Automation - Text from 2 cells into 1 cellPython / Excel 自动化 - 从 2 个单元格到 1 个单元格的文本
【发布时间】:2020-02-15 18:48:52
【问题描述】:

我正在使用 python 来自动化使用 Excel 工作表列表创建多个名称标签的过程。

我的问题是我需要把'name'列和'enterprise'列的值放在一个新文档的单个单元格中。

像这样:

到这里:

现在我正在使用 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:无法将('Gladisson Garcia Westphal'、'Agro Divel')转换为 Excel

【问题讨论】:

    标签: python excel automation


    【解决方案1】:

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

    尝试使用这个

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

    【讨论】:

      【解决方案2】:

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

      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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-02
        • 2020-09-19
        • 1970-01-01
        • 2014-04-09
        • 1970-01-01
        相关资源
        最近更新 更多