[英]Openpyxl & Python - Combining data from cells in two columns into a single column
I have a spreadsheet with data on people, in which first names are in cells in column L and last names are in the cells in column M. I need to combine these into variables that contain both the first and last name for each person.我有一个包含人员数据的电子表格,其中名字在 L 列的单元格中,姓氏在 M 列的单元格中。我需要将这些组合成包含每个人的名字和姓氏的变量。
import openpyxl
wb = openpyxl.load_workbook('/Users/userName/Desktop/sheetName.xlsx')
main = wb['Sheet1']
The following code will do this for a single row, but I need to make it iterate through every row containing data.以下代码将对单行执行此操作,但我需要使其遍历包含数据的每一行。
cell1 = main['L1'].value
cell2 = main['M1'].value
cell3 = cell1+cell2
print(cell3)
Here is what I'm trying, but I keep getting the error message name 'rows' is not defined这是我正在尝试的,但我不断收到错误消息名称“行”未定义
combined = []
for i in main.rows:
combined.append(i.value for i in row)
print(combined)
Thanks in advance for help with this puzzle!在此先感谢您对这个谜题的帮助!
This is what I got working:这就是我的工作:
import openpyxl
wb = openpyxl.load_workbook('/Users/userName/Desktop/testSheet.xlsx')
main = wb['Sheet1']
for row in range(2, main.max_row +1):
firstName = main["L" + str(row)].value
lastName = main["M" + str(row)].value
fullName = firstName + ' ' + lastName
print(fullName)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.