D
D
dima_love_friends2021-09-30 18:19:36
Python
dima_love_friends, 2021-09-30 18:19:36

How to add value to excel spreadsheet in Python?

I want to add values ​​​​to cells in an excel table and immediately save the table with a new added random value.
I am using the xlwings library.
But when I call the save method, the program seems to loop.
As a result, she added a number in the table (this is visually visible in the table), but did not save it. That is, if you close the table and open it again, then this number is no longer there.
You cannot attach an excel table here, but you can (if necessary)
And then the numbers are no longer added.
How to add numbers one by one to empty cells and immediately save the table at the current stage?
The code:

import xlwings
from xlwings import Book
import pandas as pd
import random

path_to_excel_file = 'C:/Users/me/Desktop/k.xlsx'

wb = Book(path_to_excel_file)
sheet = wb.sheets['Лист1']

df = pd.read_excel(path_to_excel_file)
count_rows = len(df)
# узнали сколько всего строчек в таблице

table = xlwings.Range(f"1:{count_rows + 1}").value
count = 0
for row in table:
    count += 1
    if count >= 5 and count <= 15:  # начинаем с пятой строки
        if row[5] is None:  # если пустая ячейка в 6 колонке, начиная с пятой строки
            id_for_item = random.randint(1, 10)
            print(id_for_item)
            sheet[f"F{count}"].value = str(id_for_item) # F - шестая колонка в excel, а F6, F7 ... отвечают за номер строки 
            wb.save(path_to_excel_file)  # после выполнения этой строки дальше прога не робит, она словно зациклилась

wb.save(path_to_excel_file)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question