D:\BaiduNetdiskWorkspace\PythonToTo\venv\Scripts\python.exe "D:\BaiduNetdiskWorkspace\PythonToTo\A0000 其他用途命令\execl美化.py" Traceback (most recent call last): File "D:\BaiduNetdiskWorkspace\PythonToTo\A0000 其他用途命令\execl美化.py", line 5, in <module> wb = load_workbook(filename='工作簿1.xlsx') File "D:\BaiduNetdiskWorkspace\PythonToTo\venv\lib\site-packages\openpyxl\reader\excel.py", line 344, in load_workbook reader = ExcelReader(filename, read_only, keep_vba, File "D:\BaiduNetdiskWorkspace\PythonToTo\venv\lib\site-packages\openpyxl\reader\excel.py", line 123, in __init__ self.archive = _validate_archive(fn) File "D:\BaiduNetdiskWorkspace\PythonToTo\venv\lib\site-packages\openpyxl\reader\excel.py", line 95, in _validate_archive archive = ZipFile(filename, 'r') File "zipfile.py", line 1251, in __init__ FileNotFoundError: [Errno 2] No such file or directory: '工作簿1.xlsx'
时间: 2023-06-30 11:12:40 浏览: 177
根据错误提示信息,Python找不到名为“工作簿1.xlsx”的文件。请确保该文件在指定的路径下,并且文件名拼写正确。
你可以通过以下方式来查看文件路径是否正确:
```python
import os
# 获取当前工作目录
print(os.getcwd())
# 列出当前目录下的所有文件和文件夹
print(os.listdir())
```
如果文件路径不正确,可以使用以下代码来指定文件路径:
```python
from openpyxl import load_workbook
from openpyxl.styles import PatternFill
# 指定文件路径
filename = 'D:\\BaiduNetdiskWorkspace\\PythonToTo\\A0000 其他用途命令\\工作簿1.xlsx'
# 加载Excel文件
wb = load_workbook(filename=filename)
# 选择默认的工作表
ws = wb.active
# 设置列宽自适应
for column in ws.columns:
max_length = 0
column = list(column)
for cell in column:
try:
if len(str(cell.value)) > max_length:
max_length = len(str(cell.value))
except:
pass
adjusted_width = (max_length + 2) * 1.2
ws.column_dimensions[cell.column_letter].width = adjusted_width
# 将没有内容的单元格底色设为灰色
grey_fill = PatternFill(start_color='C0C0C0', end_color='C0C0C0', fill_type='solid')
for row in ws.rows:
for cell in row:
if cell.value is None:
cell.fill = grey_fill
# 保存Excel文件
wb.save(filename)
```
在这段代码中,我们使用了双斜线(\\)来代替单斜线(/),以便正确指定路径。
阅读全文