I am trying to print a pandas data frame in an excel sheet, using openpyxl. Until now I have accomplished to print the data frame with the default index. My question is, how to print it without the default index. The following example script generates Table 1 and I would like to know what I need to modify in order to come up with Table 2 .
import pandas as pd
from openpyxl.utils.dataframe import dataframe_to_rows
df = pd.DataFrame((1,2,3,4,5,6))
wb = openpyxl.Workbook()
sheet = wb.active
rows = dataframe_to_rows(df)
for r_idx, row in enumerate(rows, 1):
for c_idx, value in enumerate(row, 1):
sheet.cell(row=r_idx+1, column=c_idx, value=value)
wb.save('book1.xlsx')
Table 1
0
0 1
1 2
2 3
3 4
4 5
5 6
Table 2
1
2
3
4
5
6
Unless you have a more elaborated requirement, it's quite easier to go straight with pandas.DataFrame.to_excel
, which already integrates with openpyxl
.
df.to_excel('book1.xlsx')
To drop the index, just add:
df.to_excel('book1.xlsx', index=False)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.