0

I am trying to open an excel file then insert data into the 2nd row (pushing all existing data below the 1st row down by one row). I don't want to overwrite any existing data, just add the new data and push the existing data down by one row.

Here is some code I'm using to get me started:

import xlrd  
import xlwt  
from xlutils.copy import copy 
def save_test_log(test_log_path, selected_save_path, test_type, date_n_time, tester):  
    rb = xlrd.open_workbook(test_log_path,formatting_info=True) 
    r_sheet = rb.sheet_by_index(0) # sets r_sheet to be the 1st sheet
    r = r_sheet.nrows # gets the number of rows in the 1st sheet.
    wb = copy(rb) # coppies contents of rb to a write file so we can edit it.
    sheet = wb.get_sheet(0) # select the 1st sheet in wb

This is about as far as I get. I know how to add rows to the end of the sheet but I have no idea how to "insert" rows of existing data into the sheet.

Do you have the answers I seek?

Thanks,

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
Crawdad_Buckwheat
  • 313
  • 1
  • 4
  • 16
  • This can easily be done using VBA which carries all the Excel object library (ranges, cells, sheets). I know Pythoners frown at the prospect. But until Microsoft ports Python, rewriting native functions may be overwork. Plus, the [xlutils](http://pythonhosted.org/xlutils/) package does not seem too extensive to do nuances like inserting rows. Consider writing a macro and have python run it using [win32com.client](http://stackoverflow.com/questions/11023990/python-run-excel-macro) or iterate your rows into CSVs and save as worksheets. – Parfait Feb 25 '15 at 02:44
  • Thanks for your input. I think I will try using xlrd to read the excel sheet into a list of lists, then insert a new 2nd row with new data into the list of lists. Then I will use xlwt to overwrite the old excel file using the data from the list of lists. Your way sounds cleaner though, so I may try it if my scheme doesn't work or if it's too slow. Thanks for your help! – Crawdad_Buckwheat Feb 26 '15 at 00:29
  • Also, look into using Python [Pandas](https://pypi.python.org/pypi/pandas) module. Instead of a list of lists, you can use data frames (tabular objects of rows and columns) which handle row inserts among other analytical processes. – Parfait Feb 26 '15 at 03:13

0 Answers0