python - .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
解决方案
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)
推荐阅读
- csv - 将 CSV 加载到 Neo4j 时出错
- java - 为什么我得到 MalformedJsonExection?
- regex - 为什么使用星号通配符时命令 grep 不起作用 *
- javascript - 哪个给定的 for 循环更快?
- google-chrome-devtools - chrome语音识别WebKitSpeechRecognition()不接受假音频设备的输入--use-file-for-fake-audio-capture或音频文件
- c++ - MiniDumpWriteDump 失败并显示“MiniDumpWithFullMemory”
- python-3.x - 如何在 python 中从 amazon_baby.csv 中删除停用词
- r - 如何使广义函数更新向量的值?
- android - Gradle 构建失败 [Android] 'META-INF/kotlinx-coroutines-core.kotlin_module'
- python - 在 python 项目中找不到模块?