首页 > 解决方案 > .xslx 文件不会使用 openpyxl 返回单元格值

问题描述

我对编码很陌生,我从 Python 开始。我正在尝试使用 openpyxl 作为教程的一部分。具体来说,我正在尝试在 Excel 工作簿的工作表中打印特定单元格的值。我已按照教程进行操作,将文件添加到我的项目中,并且代码与教学视频中的代码相同,但我很难理解错误。起初 Pycharm 无法识别该目录,所以我修复了它,但它仍然返回几个错误。希望有人能指教迷路的新手!我非常感谢它!

这是代码:

import openpyxl as xl

wb = xl.load_workbook("transactions.xlsx")

sheet = wb["Sheet1"]

**#instead of the method below, I have also tried: cell = sheet["a1"] to specify the cell I want.**

cell = sheet.cell(1, 1)

print(cell.value)

这是错误:

C:\Users\acost\PycharmProjects\pythonProject\HelloWorld\venv\Scripts\python.exe 
C:/Users/acost/AppData/Roaming/JetBrains/PyCharmCE2021.1/scratches/scratch_3.py
Traceback (most recent call last):
  File "C:\Users\acost\AppData\Roaming\JetBrains\PyCharmCE2021.1\scratches\scratch_3.py", line 2, in 
<module>
     wb = xl.load_workbook("transactions.xlsx")
  File "C:\Users\acost\PycharmProjects\pythonProject\HelloWorld\venv\lib\site- 
   packages\openpyxl\reader\excel.py", line 315, in load_workbook
    reader = ExcelReader(filename, read_only, keep_vba,
  File "C:\Users\acost\PycharmProjects\pythonProject\HelloWorld\venv\lib\site- 
    packages\openpyxl\reader\excel.py", line 124, in __init__
    self.archive = _validate_archive(fn)
  File "C:\Users\acost\PycharmProjects\pythonProject\HelloWorld\venv\lib\site- 
packages\openpyxl\reader\excel.py", line 96, in _validate_archive
    archive = ZipFile(filename, 'r')
  File "C:\python39\lib\zipfile.py", line 1239, in __init__
    self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: 'transactions.xlsx'

Process finished with exit code 1

标签: pythonexcelopenpyxl

解决方案


Zeromika 的评论是正确的,这只是一个阐述:

from openpyxl import load_workbook

## OPTION 1: move excel file to your python project folder

# in order for this to work, the 'transactions.xlsx' file
# must be in the same folder as this python script
wb = load_workbook('transactions.xlsx')
sheet = wb['Sheet1']

cell_value = sheet.cell(row=1, column=1).value

print(cell_value)


## OPTION 2: use full path to file
# NOTE: this is a raw string (r-string), it allows us to use special characters without escaping them
# if we didn't use a raw string here, we would have to escape the backslashes like this:
# file_path = "C:\\Users\\acost\\AppData\\Roaming\\JetBrains\\PyCharmCE2021.1\\scratches\\transactions.xlsx"
file_path = r"C:\Users\acost\AppData\Roaming\JetBrains\PyCharmCE2021.1\scratches\transactions.xlsx"

wb = load_workbook(file_path)
sheet = wb['Sheet1']

cell_value = sheet.cell(row=1, column=1).value

print(cell_value)

推荐阅读