[英]Splitting an Excel workbook's rows into multiple excel files through Python
[英]Python : Split 1 Excel File into multiple Excel files by rows
例如,您有 1 个 excel 文件,其中包含 10000 个数据。 稍后当我们在 pycharm 或 jupiter notebook 中导入 excel 文件时。 如果我运行该文件,我将获得一个索引范围,也称为行标签。 我的 python 代码应该能够读取那一万行标签,并且应该能够分离/拆分为 10 个不同的 excel 工作表文件,这些文件在 10 个单独的工作表中的每个工作表中都有 1000 个数据。 另一个例子是,如果 1 个工作表/文件中有 9999 个数据,那么我的 python 代码应该在 9 个工作表中划分 9000 个数据,在其他工作表中划分 999 个数据,没有任何错误。{这是重要的问题}
我问这个是因为在我的数据中,我的代码没有任何唯一值来拆分文件 using.unique
你可以使用 Pandas 来读取你的文件,分块然后重写它:
import pandas as pd
df = pd.read_excel("/path/to/excels/file.xlsx")
n_partitions = 3
for i in range(n_partitions):
sub_df = df.iloc[(i*n_paritions):((i+1)*n_paritions)]
sub_df.to_excel(f"/output/path/to/test-{i}.xlsx", sheet_name="a")
编辑:或者如果您希望设置每个 xls 文件的行数:
import pandas as pd
df = pd.read_excel("/path/to/excels/file.xlsx")
rows_per_file = 4
n_chunks = len(df) // rows_per_file
for i in range(n_chunks):
start = i*rows_per_file
stop = (i+1) * rows_per_file
sub_df = df.iloc[start:stop]
sub_df.to_excel(f"/output/path/to/test-{i}.xlsx", sheet_name="a")
if stop < len(df):
sub_df = df.iloc[stop:]
sub_df.to_excel(f"/output/path/to/test-{i}.xlsx", sheet_name="a")
你需要openpyxl
来读/写 Excel 个文件
以下代码片段对我来说工作正常
import pandas as pd
import openpyxl
import math
data = pd.read_excel(r"path_to_excel_file.xlsx")
_row_range = 200
_block = math.ceil(len(data)/_row_range )
for x in range(_block,_row_range ):
startRow = x*_row_range
endRow = (x+1)*_row_range
_data = data.iloc[startRow:endRow]
_data.to_excel(f"file_name_{x}.xlsx",sheet_name="Sheet1",index=False)
这也可以完成工作。 假设 Excel 文件每个文件有 19000 行。 编辑它以适合您的场景
import pandas as pd
import math
data = pd.read_excel(filename)
count = len(data)
rows_per_file = 19000
no_of_files = math.ciel(count/rows_per_file)
start_row = 0
end_row = rows_per_file
for x in range(no_of_files):
new_data = data.iloc(start_row:end_row)
newdata.to_excel(f"filename_{x}.xlsx")
start_row end_row + 1
end_row = end_row + rows_per_file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.