首页 > 解决方案 > 从 .xlsx 文件中提取第一列(所有行)的内容并将其替换为从每列中提取的信息

问题描述

我必须用从每列本身提取的信息替换第一整列(所有行)。我的代码每列都缺少最后一位数字。

我已经编码,但必须将输出保存到不同的文件。我无法弄清楚如何替换现有文件本身的第一列。我只需要一个具有所需输出的文件。

fname = 'output.xlsx'

wb = openpyxl.load_workbook(fname)

sheet = wb.active

print('The sheet title is: ', sheet.title)

row_a = sheet['A']

d = []

for cell in row_a:

    a = cell.value
    d.append(a)
print(d)

s = []

for i in d:

    i = i[-1:-8]
    s.append(i)
print('The list of account numbers is: ', s)

wc = xlwt.Workbook()

ws = wc.add_sheet('Sheet1')


row=0

col=0

list_d = s

for item in list_d:

    ws.write(row, col, item)

    row+=1

wc.save('FINAL.xls')

在此处输入图像描述

标签: excelpython-3.xcsvparsing

解决方案


我建议使用python的内置string.split方法:

import openpyxl


fname = 'output.xlsx'
wb = openpyxl.load_workbook(fname)
sheet = wb.active

d = [cell.value for cell in sheet['A']]  # List comprehension to replace your for loop

# str.split splits the 'Name' column data into an array of strings
# selecting [-1] selects only the account number
s = [i.split('.')[-1] for i in d]
s[0] = 'Account'  # replace 'Name' with 'Account' for column header

row = 1
col = 1

for item in s:
    sheet.cell(row, col).value = item
    row += 1

wb.save(fname)

我还添加了list comprehensions,这是在许多情况下从数据创建数组的更 Pythonic 的方式。


推荐阅读