Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Created October 8, 2023 14:46
Show Gist options
  • Save code-boxx/2b2bb7f5ebe7cb3234fbc1b521fbea57 to your computer and use it in GitHub Desktop.
Save code-boxx/2b2bb7f5ebe7cb3234fbc1b521fbea57 to your computer and use it in GitHub Desktop.
Python Add New Rows To Excel File

PYTHON EXCEL ADD NEW ROWS

https://code-boxx.com/python-add-new-rows-excel/

NOTES

  1. GIST does not allow Excel files. Convert the demo CSV file to Excel, or use your own dummy Excel file.
  2. Run unpack.bat (Windows) unpack.sh (Linux/Mac). This will automatically:
    • Create a virtual environment - virtualenv venv
    • Activate the virtual environment - venv\scripts\activate (Windows) venv/bin/activate (Mac/Linux)
    • Install Flask pip install openpyxl
    • Run the example excel.py

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Job Doe job@doe.com
Joe Doe joe@doe.com
Joi Doe joi@doe.com
Jon Doe jon@doe.com
Joy Doe joy@doe.com
# (A) LOAD EXCEL FILE
from openpyxl import load_workbook
wb = load_workbook(filename = "demo.xlsx")
ws = wb.active
# (B) APPEND ROW
ws.append(["A", "B"])
# (C) PREPEND ROW
ws.insert_rows(1)
ws["A1"] = "C"
ws["B1"] = "D"
# (D) INSERT ROW (LOOP)
data = ["E", "F"]
r = 5
c = 1
ws.insert_rows(r)
for v in data:
ws.cell(row=r, column=c, value=v)
c += 1
# (E) INSERT ROW ("HACK")
ws.insert_rows(7)
ws._current_row = 6
ws.append(["G", "H"])
# (F) SAVE
wb.save("updated.xlsx")
virtualenv venv
call venv\Scripts\activate
pip install openpyxl
python excel.py
virtualenv venv
source "venv/bin/activate"
pip install openpyxl
python excel.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment