简体   繁体   中英

Rename worksheets' names from an .xls file

I am creating an .xls file by converting two .csv files and joining them by following code:

import pandas as pd
import xlwt
from pandas import ExcelWriter

def save_xls(list_dfs, xls_path):
    writer = ExcelWriter(xls_path)
    for n, df in enumerate(list_dfs):
         df.to_excel(writer,'sheet%s' % n,index = False)
    writer.save()

save_xls((df,df1), "path/test.xls")

Of course I am creating dataframes df and df1 by reading two CSVs. And in path I am getting the joined .xls single file with two sheets (windows).

But the worksheets names are sheet0 and sheet1 like this. My requirement is how to rename those sheets to name1 and name2 .

i have tried passing a name tuple to it but throws error.

name = 'event','segment'

df.to_excel(writer,name,index = False)  #inside function block

#AttributeError: 'tuple' object has no attribute 'decode'

also tried to split the name tuple inside to_excel line:

df.to_excel(writer,name.split(","),index = False)

#AttributeError: 'tuple' object has no attribute 'split'

So is there a way to rename those worksheets' names?

Try:

name = 'event','segment'
for n, df in enumerate(list_dfs):
    df.to_excel(writer,name[n],index = False)  #inside function block

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM