Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending rows in excel xlswriter

I have created an xls file in which I write some user inputs into the cells. So far so good, the program works; it writes the first line. But when I run again the program instead of appending the rows it writes on top of the first one. I'm trying to understand how to make it append a new row into the excel sheet save it and close it etc

import xlsxwriter

workbook = xlsxwriter.Workbook("test.xlsx",)
worksheet = workbook.add_worksheet()

row = 0
col = 0

worksheet.write(row, col,     'odhgos')
worksheet.write(row, col + 1, 'e/p')
worksheet.write(row, col + 2, 'dromologio')
worksheet.write(row, col + 3, 'ora')


row += 1
worksheet.write_string(row, col,     odigosou)
worksheet.write_string(row, col + 1, dromou)
worksheet.write_string(row, col + 2, dromologio)
worksheet.write_string(row, col + 3, ora)

workbook.close()

With this code I created I'm able to write in the file but how do I make it to append a row in the existing sheet. All tutorials I watched, all instructions I researched, just don't work; I'm doing something wrong obviously but I'm not able to spot it.

like image 900
Nikolaos Gasparis Avatar asked Jul 14 '17 13:07

Nikolaos Gasparis


People also ask

How do I insert a row in Excel XLSX?

To insert a single row: Right-click the whole row above which you want to insert the new row, and then select Insert Rows. To insert multiple rows: Select the same number of rows above which you want to add new ones. Right-click the selection, and then select Insert Rows.


1 Answers

Question: ... how do I make it to append a row in the existing sheet

Solution using openpyxl, for instance:

from openpyxl import load_workbook

new_row_data = [
    ['odhgos', 'e/p', 'dromologio', 'ora'],
    ['odigosou', 'dromou', 'dromologio', 'ora']]

wb = load_workbook("test/test.xlsx")
# Select First Worksheet
ws = wb.worksheets[0]

# Append 2 new Rows - Columns A - D
for row_data in new_row_data:
    # Append Row Values
    ws.append(row_data)

wb.save("test/test.xlsx")

Tested with Python: 3.4.2 - openpyxl: 2.4.1 - LibreOffice: 4.3.3.2

like image 169
stovfl Avatar answered Oct 05 '22 22:10

stovfl