Python Forum
Write data into existing Excel (xlsx) file with multiple sheets - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: Write data into existing Excel (xlsx) file with multiple sheets (/thread-3544.html)



Write data into existing Excel (xlsx) file with multiple sheets - BNB - Jun-01-2017

I have an excel (xlsx) file with 11 worksheets and I need to insert the contents of a text file from Row 3 onwards in Sheet 2 named 'Filtered'. Currently, this is the code I am trying

#!/usr/bin/env python

import csv
from openpyxl.reader.excel import load_workbook
import xlrd
from xlutils import copy as xl_copy


with open('S12_final.txt') as tab_file: #open tab text file
   tab_reader = csv.reader(tab_file, delimiter='\t')
   xls_readable_book = load_workbook('S12.xlsx') #load workbook
   xls_writeable_book = xl_copy.copy(xls_readable_book)
   xls_writeable_sheet = xls_writeable_book.get_sheet_by_name('Filtered') #write data on this sheet
   for row_index, row in enumerate(tab_reader):
       xls_writeable_sheet.write(row_index, 0, row[0])
       xls_writeable_sheet.write(row_index, 1, row[1])
   xls_writeable_book.save('S12.xlsx') #save excel file
and I end up with this error

Error:
Traceback (most recent call last):  File "./tab2excel_a.py", line 24, in <module>    xls_writeable_book = xl_copy.copy(xls_readable_book)  File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/copy.py", line 19, in copy    w  File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/filter.py", line 937, in process    reader(chain[0])  File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/filter.py", line 61, in __call__    filter.workbook(workbook,filename)  File "/usr/local/lib/python2.7/dist-packages/xlutils-1.6.0-py2.7.egg/xlutils/filter.py", line 287, in workbook    self.wtbook.dates_1904 = rdbook.datemode AttributeError: 'Workbook' object has no attribute 'datemode'
I am not very familiar with python , any suggestions will be appreciated. thank you


RE: Write data into existing Excel (xlsx) file with multiple sheets - Larz60+ - Jun-01-2017

you are using xlrd which only reads excel files.
you need a difference package to write to one.

Most people suggest pandas for both read and write,
I haven't had the need to use it.