首页 > 解决方案 > 将循环中的数据框写入多个 Excel 文件

问题描述

我有 500 个 excel 文件,从每个文件中我必须跳过开始的 4 行并选择几列。我可以为每个具有特定列的文件创建新的 excel 文件,或者我可以在 SQL Server 中推送数据。

我需要创建一个可以读取所有文件并执行所需过程并以 excel 或 SQL 格式给我输出的函数。

标签: pythonexcelpandas

解决方案


使用os库来处理文件系统很方便。
该函数clean_one来自您的代码,并进行了少量更改。该函数clean_all适用clean_one于目录中的所有文件root(在我的代码'os.getcwd` [当前工作目录] 中):

import os
import pandas as pd

def clean_one(path, n):
    df = pd.read_excel(path, skiprows = 4)
    col_list = ['Emp Code', 'Emp Name', 'Net Salary', 'Gross Earnings', 'Provident Fund',
                'Provident Fund_A', 'Profession Tax', 'ESIC Deduction', 'ESIC Deduction_A',
                'Gross Deductions', 'Net Salary','Salary Bank', 'Salary Account No',
                'IFSC Code', 'PAN', 'Location', 'PF_Membership_No', 'State For PT']
    df.to_excel('File_%d.xlsx' % n, columns = col_list)

def clean_all(root):
    for n, filepath in enumerate(os.listdir(root)):
        path = os.path.join(root, filepath)
        clean_one(path, n)

if __name__ == "__main__":
    root = os.getcwd() # Replace it with necessary directory
    clean_all(root)

推荐阅读