我有一个 Excel 文件,我一直在尝试使用 openpyxl 将列(全名)拆分为两个单独的名字和姓氏列。
例如:我有
from openpyxl import Workbook, load_workbook
wb=load_workboo(path)
ws=wb['Sheet1']
全名:哈利·冲浪
我想改为:
名字: 哈利
姓氏: 冲浪
非常感谢您可以在 openpyxl 中执行此操作,因为我无法找到任何答案。
我就是这样做的。加载电子表格,得到Full name
列,迭代该列中的单元格,拆分单元格的值,并将这些值写入同一行但不同列的 2 个新单元格中。
from openpyxl import load_workbook
import os
filename = r"names.xlsx"
filename_new = r"names (split).xlsx"
wb = load_workbook(filename)
ws = wb.active
# Find the column letter of the "Full name" column, assuming row 1 are headers
for cell in ws[1]:
if cell.value == "Full name":
fullname_column = cell.column_letter
break
# Add the first and last name columns to the end
firstname_column = ws.max_column + 1
lastname_column = ws.max_column + 2
# Write the headers
ws.cell(row=1, column=firstname_column).value = "First Name"
ws.cell(row=1, column=lastname_column).value = "Last Name"
# Iterate over the fullname column, excluding the header row, read the cell's
# value, split it, and write the values to 2 new cells
for cell in ws[fullname_column][1:]:
fullname = cell.value.split(maxsplit=1)
try:
ws.cell(row=cell.row, column=firstname_column).value = fullname[0]
ws.cell(row=cell.row, column=lastname_column).value = fullname[1]
except IndexError:
pass
# Remove the "Full name" column
ws.delete_cols(cell.column)
# Save the spreadsheet to disk
wb.save(filename_new)
# Launch the new file
os.startfile(filename_new)
输入电子表格:
输出电子表格:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)