Milano
Milano

Reputation: 18745

Switching between worksheets

I'm trying to create a xlsx file from csv. Each line in this csv contains attribute 'ATR'. Many lines can have the same attribute 'ATR', for example 'x','y' etc.

So what I want to do is to go throug csv file lines one by one and write them into this xlsx file. If there is no worksheet with the name as a value of attribute 'ATR', create it and write this line there. It there is already this worksheet, write the line into this worksheet.

def temp_file_to_xlsx():
    wb = xlsxwriter.Workbook('export.xlsx')

    with open('export/export.csv') as f:
        r=-1
        for row in f:
            r+=1
            data = {}
            splitted_row = row.split('::')
            for column in splitted_row:
                splitted_column = column.split('.:.')
                data[splitted_column[0]]=splitted_column[1]

            ws = wb.add_worksheet(data['ATR']) # IT SAYS THAT THERE IS ALREADY WORKSHEET WITH THIS NAME SO I WANT TO WRITE IT THERE
            attributes = data.keys()
            for c in xrange(len(attributes)):
                try:
                    ws.write(c,r,data[attributes[c]])
                except:
                    ws.write(c,r,'-')
        wb.close()

Is it possible and if yes, how?

Upvotes: 1

Views: 666

Answers (1)

meuh
meuh

Reputation: 12255

You need to note all the worksheets you create and re-use them. For example, at the start of your function, create a dictionary:

sheets = {}

Then replace the line:

ws = wb.add_worksheet(data['ATR'])

by

if not sheets.has_key(data['ATR']):
    sheets[data['ATR']] = wb.add_worksheet(data['ATR'])
ws = sheets[data['ATR']]

hence keeping all the previously created worksheets and reusing them.

Upvotes: 2

Related Questions