I try to export an existing DataFrame to an Excel file using openpyxl.
import pandas as pd
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl import Workbook
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
wb = Workbook()
ws = wb.active
for rows in dataframe_to_rows(df, index=True, header=True):
ws.append(rows)
wb.save(filename = 'test.xlsx')
When doing so, I always get an empty row in the output file after the header row.
I know I can delete the 2nd row manually, but is there no other way?
I have already tried this here - with the same result:
import pandas as pd
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl import Workbook
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
wb = Workbook()
ws = wb.active
rows = dataframe_to_rows(df)
for r_idx, row in enumerate(rows, 1):
for c_idx, value in enumerate(row, 1):
ws.cell(row=r_idx, column=c_idx, value=value)
wb.save(filename = 'test.xlsx')
You can set the index as a column and then use index=False
import pandas as pd
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl import Workbook
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
wb = Workbook()
ws = wb.active
df.reset_index(level=0, inplace=True)
rows = dataframe_to_rows(df, index=False)
for r_idx, row in enumerate(rows, 1):
for c_idx, value in enumerate(row, 1):
ws.cell(row=r_idx, column=c_idx, value=value)
wb.save(filename = 'test.xlsx')
The Output of the excel file will be
Make index=False
:
for rows in dataframe_to_rows(df, index=False, header=True):
ws.append(rows)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With