python - 无法阻止显示弃用警告

标签 python python-3.x

我正在尝试从 Excel 文件中读取值,当我这样做时:

for i in range(1, row_num + 1): 
        try:
            cell_obj = sheet.cell(row = i, column = 1) 

我收到以下警告:

DeprecationWarning: Call to deprecated function get_squared_range (Use ws.iter_rows()).
  for row in self.get_squared_range(column, row, column, row):

我尝试实现Python文档所说的内容,但它不起作用或者我没有正确使用它,我还尝试执行以下操作:

for i in range(1, row_num + 1): 
        try:
            cell_obj = sheet.cell(row = i, column = 1) 
            myList.append((cell_obj).value)   
            warnings.filterwarnings("ignore", category=DeprecationWarning)

但是,什么也没发生。有人能解释一下吗?

最佳答案

正如警告所建议的,您可以使用 iter_rows 方法来迭代单元格。

以下是使用 iter_rows 存储前五行单元格值的示例。

from openpyxl import load_workbook
wb = load_workbook(filename = 'data.xlsx')
sheet = wb['Sheet1']
number_of_rows = sheet.max_row
number_of_columns = sheet.max_column

# Store values from first five rows
rows_iter = sheet.iter_rows(min_col=1, min_row=1,
                            max_col=number_of_columns, max_row=5)
values = [[cell.value for cell in row] for row in rows_iter]
print(values)

输出:

[['Segment', 'Country', 'Product', 'Discount Band', 'Units Sold', 'Manufacturing Price', 'Sale Price', 'Gross Sales', 'Discounts', ' Sales', 'COGS', 'Profit', 'Date', 'Month Number', 'Month Name', 'Year'], ['Government', 'Canada', 'Carretera', 'None', 1618.5, 3, 20, 32370, 0, 32370, 16185, 16185, datetime.datetime(2014, 1, 1, 0, 0), 1, 'January', '2014'], ['Government', 'Germany', 'Carretera', 'None', 1321, 3, 20, 26420, 0, 26420, 13210, 13210, datetime.datetime(2014, 1, 1, 0, 0), 1, 'January', '2014'], ['Midmarket', 'France', 'Carretera', 'None', 2178, 3, 15, 32670, 0, 32670, 21780, 10890, datetime.datetime(2014, 6, 1, 0, 0), 6, 'June', '2014'], ['Midmarket', 'Germany', 'Carretera', 'None', 888, 3, 15, 13320, 0, 13320, 8880, 4440, datetime.datetime(2014, 6, 1, 0, 0), 6, 'June', '2014']]

我用过Sample Excel Spreadsheet provided by Microsoft作为data.xlsx

已安装的软件包:

et-xmlfile==1.0.1
jdcal==1.4.1
openpyxl==2.6.2
pkg-resources==0.0.0

关于python - 无法阻止显示弃用警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56269998/

相关文章:

python - matplotlib:我怎样才能 "predraw"动画?

python - Tkinter 键盘绑定(bind)

python - f.readline 与 f.read 打印输出

python - 如何将关键字放入我的代码中?

python - 提取每个类别元组中的最后一个元素

python - "async with lock"和 "with await lock"有什么区别?

python - 获取数据框中的特定值

python - 拟合 Keras 模型会产生错误 "constant folding failed: Invalid argument: Unsupported type: 21"

python - 使用 Python3 C API 添加到内置函数

python - 使用 Python Pillow 的镜头模糊效果