write xlsx file using openpyxl module in python

12,287
from openpyxl.workbook import Workbook

header = [u'Name', u'Email', u'Mobile', u'Current location',]
new_data = [[u'name1', u'[email protected]', 9929283421.0, u'xxxx'], 
            [u'name2', u'[email protected]', 9994191988.0, u'xxxx']]

wb = Workbook()

dest_filename = 'empty_book.xlsx'

ws1 = wb.active

ws1.title = "range names"

ws1.append(header)

for row in new_data:
    ws1.append(row)

wb.save(filename = dest_filename)

I am able to write the content to xlsx like above.

Share:
12,287
Anurag Sharma
Author by

Anurag Sharma

I have completed my Masters from University of Florida and currently working as a Python Developer. I enjoy learning and working on problems pertaining to the domains of Data Analytics, Sentiment Analysis and Information Retrieval.

Updated on June 04, 2022

Comments

  • Anurag Sharma
    Anurag Sharma almost 2 years

    I am having trouble writing to excel file using openpyxl module. So far I am able to write this code

    from openpyxl.workbook import Workbook
    import datetime
    
    header = [u'Name', u'Email', u'Mobile', u'Current location',]
    new_data = [
                   [u'name1', u'[email protected]', 9929283421.0, u'xxxx'], 
                   [u'name2', u'[email protected]', 9994191988.0, u'xxxx']
               ]
    wb = Workbook()
    cur_date = str(datetime.date.today())
    log_file = "%s/%s_%s_errorlog.xlsx" % (settings.MEDIA_ROOT,
                                           os.path.splitext(file_name)[0], 
                                           cur_date)
    log_csv = wb.worksheets[0]
    
    for i in range(1, len(header) + 1):
        log_csv.cell(row = 1 ,column = i).value = header[i - 1]
    
    wb.save(log_file)
    
    error_count = 0
    for each_row in new_data:
        error_count += 1
        for i in range(1, len(each_row) + 1):
            log_csv.cell(row = error_count ,column = i).value = each_row[i - 1]
    
    wb.save(log)
    

    File is created, but it is corrupted and I am not able to open it with the excel file reader (LibreOffice) provided by the OS (ubuntu). Also the contents of the file are not readable. Not sure what I am doing wrong

  • Charlie Clark
    Charlie Clark about 9 years
    for row in new_data: ws.append(row)
  • WannaBeCoder
    WannaBeCoder about 9 years
    Yes. I should have used that in my answer. Edited. :)