Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. """ Appending DataFrame data to Excel Worksheets.
  2.  
  3. This script appends the contents of a dataframe to an existing
  4. Excel (xlsx) file. If the file doesn't exist, it will create
  5. a blank Excel file with the expected sheet names.
  6.  
  7. """
  8. import pandas as pd
  9. from openpyxl import load_workbook, Workbook
  10. import os
  11.  
  12.  
  13. filename = "example.xlsx" # Excel filename to append to.
  14.  
  15. # If the file doesn't exist, lets create a blank one with the right
  16. # worksheet names so we have something to use for the rest of the process.
  17.  
  18. if not os.path.exists(filename):
  19. print("Creating blank XLSX file...")
  20. wb = Workbook()
  21. ws = wb.active
  22. print("Creating default sheet's")
  23. ws.title = "a"
  24. wb.create_sheet("b")
  25. wb.create_sheet("c")
  26. wb.save(filename)
  27.  
  28. book = load_workbook(filename)
  29.  
  30. # A few of DataFrames to play with:
  31.  
  32. data_one = pd.DataFrame(
  33. [["a", "b"], ["c", "d"]], index=["row 1", "row 2"], columns=["col 1", "col 2"]
  34. )
  35. df_one = pd.DataFrame(data=data_one)
  36.  
  37. data_two = pd.DataFrame(
  38. [["e", "f"], ["g", "h"]], index=["row 1", "row 2"], columns=["col 1", "col 2"]
  39. )
  40. df_two = pd.DataFrame(data=data_two)
  41.  
  42. data_three = pd.DataFrame(
  43. [["i", "j"], ["k", "l"]], index=["row 1", "row 2"], columns=["col 1", "col 2"]
  44. )
  45. df_three = pd.DataFrame(data=data_three)
  46.  
  47. # Create a writer object, and create references in that object to the
  48. # existing workbook we have open already (`book`):
  49.  
  50. writer = pd.ExcelWriter(filename, engine="openpyxl")
  51. writer.book = book
  52. writer.sheets = {ws.title: ws for ws in book.worksheets}
  53.  
  54. # Export to Excel
  55. # Doing a few things here, we don't want the header appended every time, so `header=False`
  56. # Nor do we really need the Pandas index, so `index=False`
  57. # and we use the `max_row` to read the last row of df data in the sheet.
  58.  
  59. df_one.to_excel(
  60. writer,
  61. sheet_name="a", # name of the sheet to write to.
  62. startrow=writer.sheets["a"].max_row, # the row to start writing the data from
  63. index=False, # don't export panda's index.
  64. header=False, # dont't write the column headers.
  65. )
  66.  
  67. df_two.to_excel(
  68. writer,
  69. sheet_name="b",
  70. startrow=writer.sheets["b"].max_row,
  71. index=False,
  72. header=False,
  73. )
  74.  
  75. df_three.to_excel(
  76. writer,
  77. sheet_name="c",
  78. startrow=writer.sheets["c"].max_row,
  79. index=False,
  80. header=False,
  81. )
  82.  
  83. writer.save()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement