我有一个源excel文件,它在一个单元格中包含多行数据
表1
Product| Classification/Name
---------------------------
A0001 Seasonal Fruits
MANGO
ORANGE
Exotic Fruits
Dragon Fruit
Strawberry
B0001 Vegetables
ONIONS
Tomato
我想有以下格式的数据
表2
Product| Classification| Name
-----------------------------
A0001 Seasonal Fruits MANGO
A0001 Seasonal Fruits ORANGE
A0001 Exotic Fruits Dragon Fruit
A0001 Exotic Fruits Strawberry
B0001 Vegetables ONIONS
B0001 Vegetables Tomato
我不确定这是否可以通过python实现,但我想尝试一下我所知道的函数。下面是我的代码,我可以加载数据并按新行拆分数据
import openpyxl as pxl
src_path=r"C:\\Users\\TEST\\Documents\\test_new.xlsx"
wb=pxl.load_workbook(src_path)
ws=wb["Sheet1"]
row=ws.max_row
col=ws.max_column
for i in range(1,row):
i=i+1
mline=ws.cell(i,2).value
splitdata= mline.split('\n') #Split multiline data by "\n" new line.
拆分的输出作为列表生成
[‘时令水果’、‘芒果’、‘橘子’、‘异国水果’、‘龙果’、‘草莓’]
我需要浏览每行数据的输出列表,并按照上面的预期格式将其粘贴到另一张表中(表2)
for listseq in splitdata: # code will navigate through each element in the list.
我不知道如何将每个项目逐个粘贴到excel列中。因为如果我使用循环计数器,它将增加1,并且所有的项都会在一个单元格中被覆盖。我只是被困在这里,我找不到任何解决这种情况的办法
非常感谢您的专家意见
-----------修订代码-----------------仅以一行为例
import openpyxl as pxl
import pandas as pd
src_path=r"C:\\Users\\TEST\\Documents\\test_new.xlsx"
wb=pxl.load_workbook(src_path)
ws=wb["Sheet1"]
row=ws.max_row
col=ws.max_column
dest_path=r"C:\\Users\\TEST\\Documents\\FINAL.xlsx"
finalwb=pxl.load_workbook(dest_path)
finalws=finalwb["Sheet1"]
src_data=pd.read_excel(src_path)
df=pd.DataFrame(src_data)
first_col=(df.iloc[0,0])
second_col=(df.iloc[0,1])
final=(second_col.split('\n')) #split string by new line
listindex=0 #set list index to zero
wscell=1 #set worksheet cell value
for j in final:
wscell=wscell+1
verify=final[listindex]
finalws.cell(wscell,1).value=first_col
if(len(verify)>=8):
finalws.cell(wscell,2).value=verify
else:
finalws.cell(wscell,3).value=verify
listindex=listindex+1
finalwb.save(dest_path)
输出
场景不可复制,没有可用于重新生成此场景的有用文档
相关问题 更多 >
编程相关推荐