使用openpyxl获取特定单元格的值

时间:2015-03-20 00:14:55

标签: python openpyxl

我有以下Openpyxl代码。此代码获取范围中每个单元格的值。然而,我只想要每行的A,B,C,M,W和X列的值。我怎么做到这一点?提前谢谢大家。

from openpyxl import load_workbook
wb = load_workbook('C:\\Users\\RileyJ\\Documents\\Luci\\ASquad.xlsx', read_only=True, data_only=True)
ws = wb.get_active_sheet()
ws_ranges = ws['A4:X45']

for row in ws_ranges:
    html_data += "\t\t\t<tr>\n"
    for cell in row:
        if cell.value is None:
            html_data += "\t\t\t\t<td>" + ' ' + "</td>\n"
        else:
            html_data += "\t\t\t\t<td>" + str(cell.value) + "</td>\n"
    html_data += "\t\t\t</tr>\n"
html_data += "\t\t</table>\n"
html_data += "\t</body>\n"
html_data += "</html>"

with open("C:\\Users\\RileyJ\\Documents\\Luci\\Luci.html", "w") as html_fil:
    html_fil.write(html_data)

3 个答案:

答案 0 :(得分:7)

for row in range(4, 46):
    for column in "ABCMWX":  
        cell_name = "{}{}".format(column, row)
        print ws[cell_name].value

答案 1 :(得分:0)

弹跳 7stud的代码,如果你在python3中是一个更清洁的版本

for row in range(4, 46):
    for column in "ABCMWX":
        print ws[f"{column}{row}"].value

答案 2 :(得分:0)

再次,从 Shahriyar Shawon 反弹,不得不为 print() 添加括号,然后它完美地工作:

for row in range(4, 46):
    for column in "ABCMWX":
        print(ws[f"{column}{row}"].value)