Search code examples
pythonfor-loopxlsxwriterworksheet-functionworksheet

Combining two lists to make an Xlsxwriter row


Given two lists of strings (year and quarter), make an excel row like this:

"2001 q1", "2001 q2", ..., "2008 q3", "2008 q4"

This is the code I have so far:

import xlsxwriter
from xlsxwriter import workbook

workbook = xlsxwriter.Workbook('template.xlsx')
worksheet_data = workbook.add_worksheet( "data" )

year = ["2001 ", "2002 ", "2003 ", "2004 ", "2005 ", "2006 ", "2007 ", "2008 "]
quarter = ['q1 ', 'q2 ', 'q3 ', 'q4 ']

for x in year:
    for y in quarter:
        worksheet_data.write_row(
          "A1",       #start cell
          [x + y]
        )

workbook.close()

I need this for a clients customized tables.

Any ideas?


Solution

  • Hope it helps:

    import xlsxwriter
    from xlsxwriter import Workbook
    
    workbook = xlsxwriter.Workbook('template.xlsx')
    worksheet_data = workbook.add_worksheet("data")
    data = []
    
    year = ["2001 ", "2002 ", "2003 ", "2004 ", "2005 ", "2006 ", "2007 ", "2008 "]
    quarter = ['q1 ', 'q2 ', 'q3 ', 'q4 ']
    
    for x in year:
        for y in quarter:
            data.append(x + y)
    worksheet_data.write_row(0, 0, data)
    workbook.close()
    

    write_row(0, 0, data) is zero indexed, so this is A1.