Write selected columns from pandas to excel with xlsxwriter efficiently

78 Views Asked by At

I’m trying to write some of the columns of a pandas dataframe to an Excel file, but it’s taking too long. I’m currently using xlsxwriter to write all of the data to the file, which is much faster. How can I write only some of the columns to the file without sacrificing performance?

My code for writing selected columns so far:

for col_num, col_name in enumerate(zip(column_indexes, selected_columns)):
for row_num in range(2, max_rows):
    value = df.iloc[row-2][col]
    if pd.isna(value):
        value =''
    worksheet.write(row_num-1, col_num, value )
1

There are 1 best solutions below

0
Cem Koçak On BEST ANSWER

You can use the write_column method

for col_num, col_name in enumerate(selected_columns):
    col_data = df[col_name].tolist()
    worksheet.write_column(1, col_num, col_data)

enter image description here

You can take a look and learn more about here: https://xlsxwriter.readthedocs.io/worksheet.html