Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

empty row when exporting dataframe with openpyxl

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')
like image 330
pybert Avatar asked Jan 27 '23 20:01

pybert


2 Answers

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

Output in the excel file

like image 30
Onur Tavaslıoğlu Avatar answered Jan 30 '23 09:01

Onur Tavaslıoğlu


Make index=False:

for rows in dataframe_to_rows(df, index=False, header=True):
    ws.append(rows)
like image 151
Erica Rosa Avatar answered Jan 30 '23 10:01

Erica Rosa