如何使用xlsxwriter写入不带数据框的excel文件

时间:2019-10-28 18:21:12

标签: python python-3.x pandas xlsxwriter

如果我的数据框为空,那么我只需要创建一个空的excel文件并将其写入"There is no data for selected timeframe "

folder_list = ['San Diego', 'Vista']
if not df.empty:
    # if daraframe is not empty then do this:
    for location, d in df.groupby('OfficeLocation'):
        for folder in folder_list:
            if folder == location: 
                writer=pd.ExcelWriter(f'\\\\my\username\Documents\Python\Split DataFrame by Multiple dataframes\{folder}\{location}.xlsx',engine='xlsxwriter')                  
            else: 
                print('df is empty')
            writer.save()
# if dataframe is empty I need to create empty excel file and wirte in cell A1 "There is no data for seleted timeframe"
else:
    for folder in folder_list:
        # this creates empty file with sheet name 'Sheet1'
        writer=pd.ExcelWriter(f'\\\\my\username\Documents\Python\Split DataFrame by Multiple dataframes\{folder}\{folder}.xlsx',engine='xlsxwriter') 
        wb = writer.book
        ws = writer.sheets['Sheet1'] # this gives me an error
        writer.save()

错误:

Traceback (most recent call last):
  File "\\my\username\Documents\Python\Split DataFrame by Multiple dataframes\tempCodeRunnerFile.py", line 41, in <module>
    ws = writer.sheets['Sheet1'] # this gives me an error
KeyError: 'Sheet1'

2 个答案:

答案 0 :(得分:2)

您应该改为添加一个新工作表:

for folder in folder_list:
    # this creates empty file with sheet name 'Sheet1'
    writer=pd.ExcelWriter(f'\\\\my\username\Documents\Python\Split DataFrame by Multiple dataframes\{folder}\{folder}.xlsx', engine='xlsxwriter') 
    wb = writer.book
    ws = wb.add_worksheet() # change to this
    writer.save()

在此处查看相关文档:https://xlsxwriter.readthedocs.io/workbook.html#add_worksheet

如果您要使用默认的openpyxl引擎,则相应的方法是:

ws = wb.create_sheet()

答案 1 :(得分:1)

为什么不像这样在同一循环中简单地创建它。

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

# if daraframe is not empty then do this:
for location, d in df.groupby('OfficeLocation'):
    for folder in folder_list:
        if folder == location:
           if not df.empty: 
                writer=pd.ExcelWriter(f'\\\\my\username\Documents\Python\Split DataFrame by Multiple dataframes\{folder}\{location}.xlsx',engine='xlsxwriter')                  
            else:
                writer=pd.ExcelWriter(f'\\\\my\username\Documents\Python\Split DataFrame by Multiple dataframes\{folder}\{folder}.xlsx',engine='xlsxwriter') 
                df_empty = pd.DataFrame({"There is no data for seleted timeframe" : []})
                df_empty.to_excel(writer, index=False)
                print('df is empty')
            writer.save()

但是使用您的方法,您每次都会创建一个新文件。