0

I need to write specific data in two excel sheets, the first sheet will be filled by the first and last date, while the second sheet will contain the time difference between two specific rows(only calculate the time difference when df.iloc[i, 1] == '[1]->[0]' and df.iloc[i + 1, 1] == '[0]->[1]').

This is my code:

import xlsxwriter
import pandas as pd

df= pd.DataFrame({'Time':['2019/01/03 15:02:07', '2019/01/03 15:16:55', '2019/01/03 15:17:20', '2019/01/03 15:28:58','2019/01/03 15:32:28','2019/01/03 15:38:54'],
 'Payload':['[0]->[1]', '[1]->[0]','[0]->[1]','[0]->[1]','[1]->[0]','[0]->[1]']})


workbook = xlsxwriter.Workbook('Results.xlsx') 
ws = workbook.add_worksheet("Rapport détaillé")
#    wsNavco = workbook.add_worksheet("Délai reconnexion NAVCO")
ws.set_column(0, 1, 30)
ws.set_column(1, 2, 25)
# Add a format. Light yellow fill with dark red text.
format1 = workbook.add_format({'bg_color': '#fffcad',
                               'font_color': '#0a0a0a'})
# Add a format. Green fill with dark green text.
format2 = workbook.add_format({'bg_color': '#e7fabe',
                               'font_color': '#0a0a0a'})
# Write a conditional format over a range.
ws.conditional_format('A1:A24', {'type': 'cell',
                                     'criteria': '>=',
                                     'value': 50,
                                     'format': format1})
ws.conditional_format('B1:B24', {'type': 'cell',
                                     'criteria': '>=',
                                     'value': 50,
                                     'format': format2})


parametres = ( 
        ['Parametres', 'Valeurs'],
        ['1ere date  ', str(df['Time'].iloc[0])],
        ['Derniere date  ', str(df['Time'].iloc[len(df)-1])],

) 
# Start from the first cell. Rows and 
# columns are zero indexed. 
row = 0
col = 0

# Iterate over the data and write it out row by row. 
for name, parametres in (parametres): 
    ws.write(row, col, name) 
    ws.write(row, col + 1, parametres) 
    row += 1

workbook.close()


df= df.sort_values(by='Time')
df.Time = pd.to_datetime(df.Time, format='%Y/%m/%d %H:%M:%S')
print('df\n',df)
diff = []
for i in range(len(df) - 1):
    if df.iloc[i, 1] == '[1]->[0]' and df.iloc[i + 1, 1] == '[0]->[1]':
        time_diff = df.iloc[i + 1, 0] - df.iloc[i, 0]
    else:
        time_diff = 0
    diff.append(time_diff)

diff.append(0) # to fill the last value
df['Difference'] = diff
print(df['Difference'])
print('df1\n',df)

workbook = xlsxwriter.Workbook('Results.xlsx') 
wsNavco = workbook.add_worksheet('Délai reconnexion NAVCO')
#    wsNavco = wb.worksheets[1]
wsNavco.set_column(0, 1, 25)
wsNavco.set_column(1, 2, 55)
# Add a format. Light yellow fill with dark red text.
format1 = workbook.add_format({'bg_color': '#fffcad',
                               'font_color': '#0a0a0a'})
# Add a format. Green fill with dark green text.
format2 = workbook.add_format({'bg_color': '#e7fabe',
                               'font_color': '#0a0a0a'})
# Write a conditional format over a range.
wsNavco.conditional_format('A1:A24', {'type': 'cell',
                                     'criteria': '>=',
                                     'value': 50,
                                     'format': format1})
wsNavco.conditional_format('B1:B24', {'type': 'cell',
                                     'criteria': '>=',
                                     'value': 50,
                                     'format': format2})


for i in range (len(df)-1):
    wsNavco.set_column(1, 1, 15)
    wsNavco.write('A'+str(3),'Payload')
    wsNavco.write('A'+str(i+4), str((df.iloc[i,1])))

    wsNavco.write('B'+str(3),'Délai reconnexion NAVCO')
    wsNavco.write('B'+str(i+4), str((df.iloc[i,2])))


workbook.close()

The problem is that it creates the first sheet and name and fill it, but then it overwrites the first sheet by the second sheet.

My question is: how can I save both sheets.

newbie
  • 646
  • 8
  • 27

1 Answers1

3

You cannot append to an existing workbook with Xlsxwriter, you need to perform all the writes before closing the workbook. In your case this should be fine, just remove the lines that close and reopen the book between 'Rapport détaillé' and 'Délai reconnexion NAVCO'

If you prepare you data into DataFrames before hand it becomes very simple.

import pandas as pd


# Create some Pandas dataframes from some data.
df1 = pd.DataFrame({'Data': [11, 12, 13, 14]})
df2 = pd.DataFrame({'Data': [21, 22, 23, 24]})
df3 = pd.DataFrame({'Data': [31, 32, 33, 34]})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_multiple.xlsx', engine='xlsxwriter')
workbook = writer.book

# Write each dataframe to a different worksheet.
df1.to_excel(writer, sheet_name='Sheet1')
df2.to_excel(writer, sheet_name='Sheet2')
df3.to_excel(writer, sheet_name='Sheet3')

# Define formats.
format1 = workbook.add_format({'bg_color': '#fffcad',
                           'font_color': '#0a0a0a'})

format2 = workbook.add_format({'bg_color': '#e7fabe',
                           'font_color': '#0a0a0a'})

# Format worksheets.
worksheet = writer.sheets['Sheet1']
worksheet.conditional_format('A1:A24', {'type': 'cell',
                                 'criteria': '>=',
                                 'value': 50,
                                 'format': format1})

worksheet = writer.sheets['Sheet2']
worksheet.conditional_format('B1:B24', {'type': 'cell',
                                 'criteria': '>=',
                                 'value': 50,
                                 'format': format2})


# Close the Pandas Excel writer and output the Excel file.
writer.save()

There are alternative engines like Openpyxl that support appending. See this answer for details.

Drx
  • 142
  • 1
  • 1
  • 7