excel - 从 .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')
解决方案
我建议使用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 的方式。
推荐阅读
- javascript - Three.js - Webpack 5 和 FBXLoader 内联
- php - 如何在 laravel spatie 中分配多个角色和基于多个角色的权限?
- c# - c#中如何用数组替换字符串数组
- android - 如何在 Flutter 中集成 Agora 和 Banuba 功能?
- python - asyncio.exceptions.TimeoutError:等待 30 秒等待 OCPP 中的响应
- c# - 检测 Windows 关机中止
- axios - 在可穿戴设备的 HarmonyOS JS 框架中使用 Axios
- php - 如何在 PHP 中将 JSON Child 的位置更改为 Parent?
- spring-data-redis - 如何从客户端配置 Redis-server 的内存设置
- javascript - 如何将父容器的水平滚动位置移向其最近中心的子元素之一?