使用Python Openpyxl和For循环连接Excel中的两个单元格

2024-10-03 21:28:02 发布

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

我想使用openpyxl在excel中连接两个单元格。但我正在努力使代码正确地进入“for循环”,因为我必须迭代和浓缩单元格

import openpyxl
wk=openpyxl.load_workbook(r"C:\\Users\\hp\\Desktop\\Uarch\\ConcatDemo.xlsx")
sh=wk['Sheet1']
rows=sh.max_row
columns=sh.max_column
for row_num in range(1,rows+1):
    sh['C{}'.format(row_num)] = '=CONCATENATE(A{},",",B{})'.format(row_num)


wk.save(r"C:\\Users\\hp\\Desktop\\Uarch\\ConcatDemo.xlsx")

我越来越

IndexError: tuple index out of range

Erro屏幕截图:

enter image description here

不确定哪一部分出错了,或者我的逻辑错误了

输入:

enter image description here

预期产出:

enter image description here

期待在这方面得到帮助


Tags: forshrangexlsxusersnummaxrows
1条回答
网友
1楼 · 发布于 2024-10-03 21:28:02

问题是,本节中的字符串格式在串联函数中需要2个值,而不是1个值

'=CONCATENATE(A{},",",B{})'.format(row_num)

我可以用这个达到你想要的行为

import openpyxl
wk=openpyxl.load_workbook("path_to_file.xlsx")
sh=wk['Sheet1']
rows=sh.max_row
columns=sh.max_column
for row_num in range(1,rows+1):
    sh['C{}'.format(row_num)] = '=CONCATENATE(A{},",",B{})'.format(row_num,row_num)
wk.save('file_output.xlsx')

隔离错误

'A{}B{}'.format(1)
#IndexError       

'A{}B{}'.format(1, 1)
'A1B1'

这也可以通过熊猫来实现

import pandas as pd
file = pd.read_excel("path_to_file.xlsx", header=None, sheet_name="Sheet1")
file[3] = file[0] + ',' + file[1]
file.to_excel("output_file2.xlsx", index=False, header=False)

相关问题 更多 >