我有一个简单的excel文件:
A1 = 200
A2 = 300
A3 = =SUM(A1:A2)这个文件在excel中工作,并显示了SUM的适当值,但是当我使用python的openpyxl模块时,我无法在data_only=True模式下获得值
shell中的Python代码:
wb = openpyxl.load_workbook('writeFormula.xlsx', data_only = True)
sheet = wb.active
sheet['A3']
<Cell Sheet.A3> # python response
print(sheet['A3'].value)
None # python response而:
wb2 = openpyxl.load_workbook('writeFormula.xlsx')
sheet2 = wb2.active
sheet2['A3'].value
'=SUM(A1:A2)'  # python response有什么建议吗?我哪里做错了?
发布于 2021-06-18 23:09:59
是的,@Beno是对的。如果你想在不接触的情况下编辑文件,你可以制作一个小的“机器人”来编辑你的excel文件。
警告:这是编辑excel文件的递归方式。这些库依赖于您的计算机,请确保在继续其余代码之前正确设置了 time.sleep 。
例如,我使用time.sleep、subprocess.Popen和pywinauto.keyboard.send_keys,只需将随机字符添加到您设置的任何单元格,然后保存它。那么data_only=True就运行得很完美。有关pywinauto.keyboard的更多信息,请访问:pywinauto.keyboard
# import these stuff
import subprocess
from pywinauto.keyboard import send_keys
import time
import pygetwindow as gw
import pywinauto
excel_path = r"C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE"
excel_file_path = r"D:\test.xlsx"
def focus_to_window(window_title=None): # function to focus to window. https://stackoverflow.com/a/65623513/8903813
    window = gw.getWindowsWithTitle(window_title)[0]
    if not window.isActive:
        pywinauto.application.Application().connect(handle=window._hWnd).top_window().set_focus()
subprocess.Popen([excel_path, excel_file_path])
time.sleep(1.5) # wait excel to open. Depends on your machine, set it propoerly
focus_to_window("Excel") # focus to that opened file
send_keys('%{F3}') # excel's name box | ALT+F3
send_keys('AA1{ENTER}') # whatever cell do you want to insert somthing | Type 'AA1' then press Enter
send_keys('Stackoverflow.com') # put whatever you want | Type 'Stackoverflow.com'
send_keys('^s') # save | CTRL+S
send_keys('%{F4}') # exit | ALT+F4
print("Done")对不起,我的英语不好。
https://stackoverflow.com/questions/36116162
复制相似问题