Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Answering this with the code that I'm now using to achieve the desired result. Note that I am manually inserting the row at position 1, but that should be easy enough to adjust for specific needs. You could also easily tweak this to insert more than one row, and simply populate the rest of the data starting at the relevant position.</p> <p>Also, note that due to downstream dependencies, we are manually specifying data from 'Sheet1', and the data is getting copied to a new sheet which is inserted at the beginning of the workbook, whilst renaming the original worksheet to 'Sheet1.5'.</p> <p>EDIT: I've also added (later on) a change to the format_code to fix issues where the default copy operation here removes all formatting: <code>new_cell.style.number_format.format_code = 'mm/dd/yyyy'</code>. I couldn't find any documentation that this was settable, it was more of a case of trial and error!</p> <p>Lastly, don't forget this example is saving over the original. You can change the save path where applicable to avoid this.</p> <pre><code> import openpyxl wb = openpyxl.load_workbook(file) old_sheet = wb.get_sheet_by_name('Sheet1') old_sheet.title = 'Sheet1.5' max_row = old_sheet.get_highest_row() max_col = old_sheet.get_highest_column() wb.create_sheet(0, 'Sheet1') new_sheet = wb.get_sheet_by_name('Sheet1') # Do the header. for col_num in range(0, max_col): new_sheet.cell(row=0, column=col_num).value = old_sheet.cell(row=0, column=col_num).value # The row to be inserted. We're manually populating each cell. new_sheet.cell(row=1, column=0).value = 'DUMMY' new_sheet.cell(row=1, column=1).value = 'DUMMY' # Now do the rest of it. Note the row offset. for row_num in range(1, max_row): for col_num in range (0, max_col): new_sheet.cell(row = (row_num + 1), column = col_num).value = old_sheet.cell(row = row_num, column = col_num).value wb.save(file) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload