Python Pandas: How to specify the starting cell position when exporting dataframe to Excel
Asked Answered
P

1

5

When a dataframe is exported from Pandas to Excel using xlsxwriter, it seems to put the table at cell A1 by default.

Is there a way to change this? I don't mind inserting rows and columns to move the table away from A1, as long as it's done programmatically via pandas or xlsxwriter.

In case it helps, here is my code.

writer = pd.ExcelWriter(r'c:\file.xlsx', engine = 'xlsxwriter')
workbook - writer.book
df.to_excel(writer, index=True, sheet_name ='Sheet1')

I couldn't find any XlsxWriter method for inserting rows and columns either.

Powerhouse answered 30/4, 2016 at 16:8 Comment(1)
The answer from DeepSpace is correct but just to note that this is covered in the XlsxWriter section on Working with Python Pandas and XlsxWriter.Moraceous
E
12

to_excel accepts startrow and startcol arguments which are zero-based numbers (ie startrow=1 and startcol=1 will put the top left cell of the table in cell B2).

startrow : upper left cell row to dump data frame

startcol : upper left cell column to dump data frame

Excerpt answered 30/4, 2016 at 16:10 Comment(3)
How can one do this with the alphanumeric 'A1' cell location instead of startrow and startcol?Enshroud
What if I want to write 3 dataframes of different row lengths to Same Excel Worksheet of an Excelfile? When I give startrow += df1.shape[0] and then supply this argument without a constant no to write the 2nd Dataframe, it displays : SyntaxError: positional argument follows keyword argumentSolvent
@Enshroud xlsxwriter.utility.xl_col_to_name(integer) will provide the alphanumeric representation of a 0-based numeric cell identifier. Example: xlsxwriter.utility.xl_col_to_name(0) returns "A". This will do the reverse: xlsxwriter.utility.xl_cell_to_rowcol(f'{string}1')[1]. Example: If {string} is A, the returned value is 0. You can make functions out of these, and work in your preferred representation. Just use the function to map your preferred representation to the required representation at time of.Paregmenon

© 2022 - 2024 — McMap. All rights reserved.