0

我需要每周将 excel 文件发送到指定的文件夹,但有时没有数据要发送。

在这种情况下,我仍然需要一个带有标题和所有内容的空文件,只是没有数据。

import pandas as pd


df = pd.DataFrame({
    'PolicyNumber':['Pol1','Pol2','Pol3','Pol4','Pol5'],
    'OfficeLocation':['San Diego', 'San Diego','San Diego','Vista','Vista'],
    'Premium':[800,300,650,200,700]
})


folder_list = ['San Diego', 'Vista']

for location, d in df.groupby('OfficeLocation'):
    for folder in folder_list:
        if folder == location:            
            d.to_excel(f'\\\\server\user\name\{folder}\{location}.xlsx',sheet_name=location, 
4

1 回答 1

0

我认为您应该枚举文件夹列表,因为 OfficeLocation 数据框已经固定。我以洛杉矶为例。

import os
import pandas as pd

df = pd.DataFrame({
    'PolicyNumber':['Pol1','Pol2','Pol3','Pol4','Pol5'],
    'OfficeLocation':['San Diego', 'San Diego','San Diego','Vista','Vista'],
    'Premium':[800,300,650,200,700]
})


folder_list = ['San Diego', 'Vista','Los Angeles']


desktop = os.path.join(os.path.join(os.environ["USERPROFILE"]), 'Desktop')
excel_name = "\\df" + "." + "xlsx"
writer = pd.ExcelWriter(desktop + str(excel_name), engine = "xlsxwriter")

try:
    for idx,foldername in enumerate(folder_list):
        subset = df[df['OfficeLocation'] == foldername]
        subset.to_excel(writer, sheet_name = str(foldername), index = False)

finally:
    writer.save() 
于 2019-10-30T21:59:23.113 回答