pythonexceldocumentods

Why is it possible to write to first row of .ods document by python but not to others?


I would like to open .ods table file and write new values into first available cell. Only to first three rows.

But this code just write it there always again. There is not data save. So how to do it?

from pyexcel_ods3 import save_data
from pyexcel_ods3 import get_data
from collections import OrderedDict
import ezodf

data = OrderedDict() # from collections import OrderedDict
data.update({"Sheet 1": [[1, 2, 3]]})
data.update({"Sheet 2": [["row 1", "row 2", "row 3"]]})
save_data("moje_data.ods", data)

Solution

  • You just need to read the spreadsheet file at the beginning of your code. Then ensure that "Sheet 1" exists, then append the rows that you want and save the file:

    from pyexcel_ods3 import save_data
    from pyexcel_ods3 import get_data
    
    
    def main():
        data = get_data("moje_data.ods")
        if 'Sheet 1' not in data:
            data["Sheet 1"] = []
        data["Sheet 1"].append([1, 2, 3])
        save_data("moje_data.ods", data)
    
    
    if __name__ == '__main__':
        main()
    

    Each time you run this code, the file will contain one more row.