【发布时间】:2021-01-11 01:45:21
【问题描述】:
我有一个包含如下行的 excel 文件:
col1 | col2 | col3 | col4 | col5
anotherCol1 | anotherCol2 | anotherCol3 | anotherCol4 | anotherCol5
我需要复制每一行,使其看起来像这样:
col1 | col2 | col3 | col4 | col5
col1 | col2 | col3 | col4 | col5
anotherCol1 | anotherCol2 | anotherCol3 | anotherCol4 | anotherCol5
anotherCol1 | anotherCol2 | anotherCol3 | anotherCol4 | anotherCol5
这是我目前所拥有的,excel 文件是 .XLS 文件而不是 .XLSX 文件,所以我不能使用 openpyxl,除非有办法解决。
这是我目前所拥有的:
def DuplicateEachRow(self):
import pandas as pd
import pathlib
full_path = str(pathlib.Path().absolute()) + '\\' + new_loc
df = pd.read_excel(full_path, header=None, sheet_name=None)
# engine can be openpyxl if we need .xlsx ext
writer = pd.ExcelWriter(new_loc, engine='xlwt')
for key in df:
sheet = df[key]
sheet.to_excel(writer, key, index=False, header=False)
print(sheet)
# writer.save()
如何使用 dataframe 的“工作表”复制每一行?
编辑:我也试过这个......
def DuplicateEachRow(self):
import pandas as pd
import pathlib
full_path = str(pathlib.Path().absolute()) + '\\' + new_loc
df = pd.read_excel(full_path, header=None, sheet_name='GTL | GWL Disclosures')
print(df)
# duplicate the rows:
dup_df = pd.concat([df, df], ignore_index=True)
# using openpyxl
with pd.ExcelWriter('path_to_file.xlsx') as writer:
dup_df.to_excel(writer)
但这只会写回一张纸而不是原始工作簿
【问题讨论】:
标签: python python-3.x excel pandas openpyxl