2

Referencing How to write to an existing excel file without overwriting data? I tried the below code:

book = load_workbook('output.xlsx')
writer = pd.ExcelWriter('output.xlsx')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
Output.to_excel('output.xlsx', "Main", index=True, header=False, startcol = pickupcol)
writer.save()

This is part of a loop, but I found that to_excel could only write 256 columns at one time, so I decided to use a variable pickupcol so I could just add one section at a time. Unfortunately it deletes the previous data with blank cells.

Thoughts/Suggestions? Thanks!

Community
  • 1
  • 1
As3adTintin
  • 2,406
  • 12
  • 33
  • 59

1 Answers1

2

startcol refers to the column number of the upper left cell of the section in the Excel File where the dataframe is dumped. Selection of columns of the dataframe to be written to excel is done by the parameter columns of the to_excel function. The following code works for me. It does not overwrite the previous data

In [57]: import pandas as pd

In [58]: import numpy as np

In [59]: df = pd.DataFrame(np.random.randn(5,300))

In [60]: writer = pd.ExcelWriter("output.xlsx")

In [61]: df.to_excel(writer,columns=range(0,255))

In [62]: df.to_excel(writer,columns=range(256,300),startcol=257,index='False')

In [63]: writer.save()

By the way, I am able to write all the columns at one go , without any limit of 256 columns. I am using pandas version '0.15.2'

Siva-Sg
  • 2,741
  • 19
  • 27
  • Thanks @user1319128. When I use your code, I get the same results as you did. Something must be amiss in my code/data. – As3adTintin May 26 '15 at 13:32
  • For some reason I come back from the weekend and now it works just as yours does! Now i just have this issues: http://stackoverflow.com/questions/30404791/pandas-excel-export-columns-out-of-order?noredirect=1#comment48925456_30404791 – As3adTintin May 26 '15 at 14:34