〇、前情提要
在学小甲鱼的使用Python读写Excel文件时,遇到了如下警告:
DeprecationWarning: Call to deprecated function get_sheet_names (Use wb.sheetnames).
DeprecationWarning: Call to deprecated function get_sheet_by_name (Use wb[sheetname]).
DeprecationWarning: Call to deprecated function remove_sheet (Use wb.remove(worksheet) or del wb[sheetname]).
参考:
- 【办公篇】《极客Python之效率革命》(小甲鱼)https://www.bilibili.com/video/av23697305/?p=1
- [办公] 使用Python读写Excel文件(2)
https://fishc.com.cn/thread-102046-1-1.html
一、报错解释
DeprecationWarning: Call to deprecated function get_sheet_names (Use wb.sheetnames).
不推荐警告:调用已弃用的函数get_sheet_names(请使用wb.sheetnames)
DeprecationWarning: Call to deprecated function get_sheet_by_name (Use wb[sheetname]).
不推荐警告:调用已弃用的函数get_sheet_by_name(请使用wb[sheetname])
DeprecationWarning: Call to deprecated function remove_sheet (Use wb.remove(worksheet) or del wb[sheetname]).
不推荐警告:调用已弃用的函数remove_sheet(请使用Use wb.remove(worksheet) 或者 del wb[sheetname])
二、解决
get_sheet_names
改用wb.sheetnames
get_sheet_by_name
改用wb[sheetname]
>>> import openpyxl
>>> wb = openpyxl.load_workbook(r"你的excel文件路径")
>>> print(type(wb))
<class 'openpyxl.workbook.workbook.Workbook'>
>>> wb.get_sheet_names()
Warning (from warnings module):
File "__main__", line 1
DeprecationWarning: Call to deprecated function get_sheet_names (Use wb.sheetnames).
['Sheet']
>>> print(wb.sheetnames)
['Sheet']
>>> ws = wb.get_sheet_by_name('Sheet')
Warning (from warnings module):
File "__main__", line 1
DeprecationWarning: Call to deprecated function get_sheet_by_name (Use wb[sheetname]).
>>> ws=wb["Sheet"]
>>> ws
<Worksheet "Sheet">
>>>
remove_sheet
改用Use wb.remove(worksheet)
或者 del wb[sheetname]
>>> wb.remove_sheet(wb["FishC Demo"])
Warning (from warnings module):
File "__main__", line 1
DeprecationWarning: Call to deprecated function remove_sheet (Use wb.remove(worksheet) or del wb[sheetname]).
>>> wb.remove_sheet(wb["FishC Demo"])
>>> print(wb.sheetnames)
['Sheet']