3

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

1
  • Why are you trying to write the coordinates rather than using ws.append()? Creating a range over a sequence is poor Python. Use enumerate(seq) instead. Commented Apr 7, 2015 at 11:48

1 Answer 1

10
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.

Sign up to request clarification or add additional context in comments.

2 Comments

for row in new_data: ws.append(row)
Yes. I should have used that in my answer. Edited. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.