简体   繁体   中英

Concatenate Two Cells in Excel Using Python Openpyxl And For loop

I want to concatenate two cells in excel by using openpyxl . But i am struggling to get the code right in "for loop",as i have to iterate and concat the cells .Here's my code so far

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

I am getting

IndexError: tuple index out of range

Erro Screenshot:

在此处输入图片说明

Not sure which part is going wrong or i have put a wrong logic.

Input:

在此处输入图片说明

Intended Output:

在此处输入图片说明

Looking forward for help in this..

The issue is that your string formatting in in this section is expecting 2 values rather than 1 in the concatenate function.

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

I could achieve your desired behaviour with this

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

To isolate the error

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

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

This can also be done using Pandas

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM