Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing to existing workbook using xlwt [closed]

Tags:

python

xlrd

xlwt

I am unable to find examples where xlwt is used to write into existing files. I have a existing xls file that I need to write to. When I use xlrd to read the file, I cant seem to figure out how to transform the "Book" type returned into a xlwt.Workbook. I would appreciate if someone can point me to an example.

like image 790
Raj N Avatar asked Apr 27 '10 23:04

Raj N


People also ask

How do you write data in Excel sheet using Python xlwt?

Using xlwt module, one can perform multiple operations on spreadsheet. For example, writing or modifying the data can be done in Python. Also, the user might have to go through various sheets and retrieve data based on some criteria or modify some rows and columns and do a lot of work.

Can xlwt write to Xlsx?

2019 update: xlwt doesn't support xlsx Format. XlsxWriter is 100% compatible with xlsx, well-maintained and has a good reputation. For reading xlsx files, you can use xlrd .

How do I read and write an Excel file using Python xlrd?

Read Excel File in PythonThe command need to be installed is xlrd module. xlrd module is used to extract data from a spreadsheet. After writing the above code (Read Excel File in Python), Ones you will print then the output will appear as a “ Name ”. Here, row 0 and column 0 data is extracted from the spreadsheet.

How do I merge cells in Excel with xlwt?

There are two methods on the Worksheet class to do this, write_merge and merge . merge takes existing cells and merges them, while write_merge writes a label (just like write ) and then does the same stuff merge does. Both take the cells to merge as r1, r2, c1, c2 , and accept an optional style parameter.


1 Answers

Here's some sample code I used recently to do just that.

It opens a workbook, goes down the rows, if a condition is met it writes some data in the row. Finally it saves the modified file.

from xlutils.copy import copy # http://pypi.python.org/pypi/xlutils from xlrd import open_workbook # http://pypi.python.org/pypi/xlrd  START_ROW = 297 # 0 based (subtract 1 from excel row number) col_age_november = 1 col_summer1 = 2 col_fall1 = 3  rb = open_workbook(file_path,formatting_info=True) r_sheet = rb.sheet_by_index(0) # read only copy to introspect the file wb = copy(rb) # a writable copy (I can't read values out of this, only write to it) w_sheet = wb.get_sheet(0) # the sheet to write to within the writable copy  for row_index in range(START_ROW, r_sheet.nrows):     age_nov = r_sheet.cell(row_index, col_age_november).value     if age_nov == 3:         #If 3, then Combo I 3-4 year old  for both summer1 and fall1         w_sheet.write(row_index, col_summer1, 'Combo I 3-4 year old')         w_sheet.write(row_index, col_fall1, 'Combo I 3-4 year old')  wb.save(file_path + '.out' + os.path.splitext(file_path)[-1]) 
like image 154
Greg Avatar answered Sep 20 '22 00:09

Greg