gpt4 book ai didi

python - 使用 Python 在 Excel 中读取合并的单元格

转载 作者:太空狗 更新时间:2023-10-29 18:23:02 25 4
gpt4 key购买 nike

我正在尝试使用 xlrd 使用 Python 读取 Excel 的合并单元格。

我的 Excel:(注意第一列合并了三行)

    A   B   C
+---+---+----+
1 | 2 | 0 | 30 |
+ +---+----+
2 | | 1 | 20 |
+ +---+----+
3 | | 5 | 52 |
+---+---+----+

在这个例子中,我想读取第一列的第三行等于 2,但它返回 ''。您知道如何获取合并单元格的值吗?

我的代码:

all_data = [[]]
excel = xlrd.open_workbook(excel_dir+ excel_file)
sheet_0 = excel.sheet_by_index(0) # Open the first tab

for row_index in range(sheet_0.nrows):
row= ""
for col_index in range(sheet_0.ncols):
value = sheet_0.cell(rowx=row_index,colx=col_index).value
row += "{0} ".format(value)
split_row = row.split()
all_data.append(split_row)

我得到的:

'2', '0', '30'
'1', '20'
'5', '52'

我想得到什么:

'2', '0', '30'
'2', '1', '20'
'2', '5', '52'

最佳答案

我刚刚试过了,它似乎适用于您的示例数据:

all_data = []
excel = xlrd.open_workbook(excel_dir+ excel_file)
sheet_0 = excel.sheet_by_index(0) # Open the first tab

prev_row = [None for i in range(sheet_0.ncols)]
for row_index in range(sheet_0.nrows):
row= []
for col_index in range(sheet_0.ncols):
value = sheet_0.cell(rowx=row_index,colx=col_index).value
if len(value) == 0:
value = prev_row[col_index]
row.append(value)
prev_row = row
all_data.append(row)

回归

[['2', '0', '30'], ['2', '1', '20'], ['2', '5', '52']]

它会跟踪上一行的值,如果当前行的相应值为空,则使用它们。

请注意,上面的代码不会检查给定的单元格是否实际上是一组合并的单元格的一部分,因此在单元格应该为空的情况下,它可能会复制以前的值。不过,它可能会有一些帮助。

附加信息:

我随后找到了一个文档页面,其中讨论了 merged_cells可用于确定包含在各种合并单元格范围中的单元格的属性。文档说它是“版本 0.6.1 中的新增功能”,但是当我尝试将它与通过 pip 安装的 xlrd-0.9.3 一起使用时,我得到了错误

NotImplementedError: formatting_info=True not yet implemented

我并不是特别倾向于开始寻找不同版本的 xlrd 来测试 merged_cells 特性,但是如果上面的代码不能满足您的需求并且您可能有兴趣这样做遇到与我使用 formatting_info=True 时相同的错误。

关于python - 使用 Python 在 Excel 中读取合并的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30727017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com