使用Python和熊猫将Excel工作表拆分为单独的工作表

时间:2019-01-03 13:59:30

标签: python pandas dataframe

我需要一个脚本来将主工作表(包含超过5万行)拆分为单独的工作表,该工作表仅包含40行且没有标题

经过一番研究,我设法创建了一个脚本,用于拆分主工作表。但是,每个工作表都包含原始标题,并且每个工作表中的行都不会分成40行。

我相信,当您使用带有数据帧的panda拆分工作表时,它们将始终包含标题吗?关于如何修改我的python脚本来实现我所需要的任何建议,或者有没有更简单的方法来实现这一目标而无需使用熊猫和数据框?

这里是一个链接:https://github.com/lblake/sample-data到一些示例数据

path = input('Enter file path to workbook name and extension, 
e.g. example.xlsx: ')
chunksize = int (input('Enter the row number you want to split the excel sheet at: ') )
destination = input('Enter folder path to where you want the split files stored. Press Enter to save in current location: ')

i = 0
df = pd.read_excel(path)
for chunk in np.array_split(df, len(df) // chunksize):
    chunk.to_excel(destination + 
'file_{:02d}.xlsx'.format(i), index=True)
i += 1 

2 个答案:

答案 0 :(得分:1)

您可以使用groupby并进行迭代。要忽略标题,请在写入header=False对象时指定pd.ExcelWriter。下面的示例将10行的数据帧分成2行的块。

df = pd.DataFrame(np.arange(100).reshape((10, 10)))

writer = pd.ExcelWriter('file.xlsx')

for key, grp in df.groupby(df.index // 2):
    grp.to_excel(writer, f'sheet_{key}', header=False)

writer.save()

答案 1 :(得分:0)

我只是复制了您的代码并添加了header=False

path = input('Enter file path to workbook name and extension, 
e.g. example.xlsx: ')
chunksize = int (input('Enter the row number you want to split the excel sheet at: ') )
destination = input('Enter folder path to where you want the split files stored. Press Enter to save in current location: ')

i = 0
df = pd.read_excel(path)
for chunk in np.array_split(df, len(df) // chunksize):
    chunk.to_excel(destination + 
'file_{:02d}.xlsx'.format(i), index=True, header=False)
i += 1 

对我有用。