Python – получение числа из файла excel вместо формулы

Первые шаги с Python, так что будьте снисходительны. Я много искал, но мне так и не ясно, где может быть ошибка.

Доступ к файлу excel -> запись в него суммы -> повторное чтение значения суммы. Я получаю =SUM(C3:N9) вместо значения, даже если data_only=True

Любая подсказка, пожалуйста? заранее спасибо

# Load the sources of interest
import openpyxl
from openpyxl import load_workbook

# Open the document
excel_document = openpyxl.load_workbook('1.xlsx', data_only=True)

# Open the sheet of interest
sheet = excel_document.get_sheet_by_name('Foglio1')

# Read a cell of interest and print its content
cell_of_interest_1 = sheet['C4'].value
print cell_of_interest_1

#Ask a value to the user to be inserted for updating the cell of interest
valore1 = input ("Insert the new value for the cell :")

#The cell is updated with the user input
sheet['C4'] = valore1

#Insert the total sum of the values of the Sheet in cell P9
sheet["P9"] = "=SUM(C3:N9)"

# The value of cell P9
grand_sum = sheet['P9'].value

# Read and print the value of cell P9
print "Total sum of the Sheet values:"
print grand_sum

d = sheet.cell(row=9, column=16).value
print d

# Save the updated file
excel_document.save("1.xlsx")
Почему в Python есть оператор "pass"?
Почему в Python есть оператор "pass"?
Оператор pass в Python - это простая концепция, которую могут быстро освоить даже новички без опыта программирования.
Некоторые методы, о которых вы не знали, что они существуют в Python
Некоторые методы, о которых вы не знали, что они существуют в Python
Python - самый известный и самый простой в изучении язык в наши дни. Имея широкий спектр применения в области машинного обучения, Data Science,...
Основы Python Часть I
Основы Python Часть I
Вы когда-нибудь задумывались, почему в программах на Python вы видите приведенный ниже код?
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
LeetCode - 1579. Удаление максимального числа ребер для сохранения полной проходимости графа
Алиса и Боб имеют неориентированный граф из n узлов и трех типов ребер:
Оптимизация кода с помощью тернарного оператора Python
Оптимизация кода с помощью тернарного оператора Python
И последнее, что мы хотели бы показать вам, прежде чем двигаться дальше, это
Советы по эффективной веб-разработке с помощью Python
Советы по эффективной веб-разработке с помощью Python
Как веб-разработчик, Python может стать мощным инструментом для создания эффективных и масштабируемых веб-приложений.
0
1
997
1

Ответы 1

Взгляните на ответ, связанный stovfl выше. Openpyxl не вычисляет результат формулы, поэтому вы можете либо

Опция 1 сохраните и снова откройте книгу с data_only=True и попробуйте прочитать пересчитанное значение

вариант 2 вычислите значение самостоятельно, используя обновленное входное значение.

# Load the sources of interest
import openpyxl
from openpyxl import load_workbook

# Open the document
excel_document = openpyxl.load_workbook('1.xlsx', data_only=True)

# Open the sheet of interest
sheet = excel_document.get_sheet_by_name('Foglio1')

# Read a cell of interest and print its content
cell_of_interest_1 = sheet['C4'].value
print (cell_of_interest_1)

#Ask a value to the user to be inserted for updating the cell of interest
valore1 = input ("Insert the new value for the cell :")

#The cell is updated with the user input
sheet['C4'] = int(valore1)

#Insert the total sum of the values of the Sheet in cell P9
sheet["P9"] = "=SUM(C3:N9)"

# The value of cell P9
grand_sum = sheet['P9'].value


old_c4_value = int(sheet['C4'].value)
# Read and print the value of cell P9
print ("Total sum of the Sheet values:")
old_sum = 0
for row in sheet['C3:N9']:
  for cell in row:
      old_sum+= int(cell.value)

#subtracted the prev value of cell C4 then added the current value to the sum of other cells
real_sum = old_sum+int(valore1)-old_c4_value

print(real_sum)

d = sheet.cell(row=9, column=16).value
print(d)




# Save the updated file
excel_document.save("1.xlsx")

обратите внимание, что я предположил, что ячейки содержат целые значения

Большое тебе спасибо! Спасибо, я собираюсь подробно изучить ваш ответ.

InflatableGull 26.01.2019 17:34

Другие вопросы по теме