Export pandas dataframe to an Excel spreadsheet
Thu Jan 05 2023 22:55:21 GMT+0000 (Coordinated Universal Time)
import io # Export to CSV/Excel file # Prep file to be saved data_buffer = io.BytesIO() # "placeholder" to hold data to be added to Excel sheet writer = pd.ExcelWriter(data_buffer, engine="xlsxwriter") # # write as Excel file workbook = writer.book # "create" empty Excel file worksheet_summary = workbook.add_worksheet("Case " + str(case_n) + " Summary") # write worksheet tab for "each" case bold = workbook.add_format({"bold": True}) # # Enable bold formatting row = 0 # start at top of Excel file # Can turn this into a function instead # Creating Table 1 worksheet_summary.write(row, 0, "Table 1", bold) # Table 1 title, bold format form_start_row = row + 1 # go to next row for data col = 0 # start at leftmost for each in st.session_state[summary_sess_state]: # go through each data in form. table worksheet_summary.write(form_start_row, col, each) # write out the header row row = form_start_row + 1 # go to next row for item in range(0, len(st.session_state[summary_sess_state])): # get each "sub-data" inside the dataframe after the header row try: worksheet_summary.write(row, col, st.session_state[summary_sess_state][each][item]) # write the "sub-data" in their respective locations except: pass row += 1 # go to next row col += 1 # go to next col row += 2 # next 2 rows for next table # Creating Table 2 worksheet_summary.write(row, 0, "Table 1", bold) # Table 2 title, bold format comp_start_row = row + 1 # go to next row for data col = 0 # start at leftmost for each in summary_table_component_results: # go through each data in comp. table worksheet_summary.write(comp_start_row, col, each) # write out the header row row = comp_start_row + 1 # go to next row for item in range(0, len(summary_table_component_results)): # get each "sub-data" inside the dataframe after the header row worksheet_summary.write(row, col, summary_table_component_results[each][item]) row += 1 col += 1 row +=1
Comments