计算 Excel 个单元格值并在同一行右侧一列中打印结果

Evaluate Excel cell values and print the result in the same row one column to the right

我想弄清楚如何读取 Excel 列中的数据,并在 Excel 工作表(而不是 Python 控制台)。下面是我正在测试的代码。好像可以,但是只是在控制台显示结果,我很想把结果写到Excel中相邻的单元格(B列)。

import openpyxl
wb = openpyxl.load_workbook('C:\Users\Excel\Desktop\Book1.xlsx')
ws = wb.get_sheet_by_name('Sheet1')
for row in ws.iter_rows('A{}:A{}'.format(ws.min_row,ws.max_row)):
    for cell in row:
        if isinstance(cell.value, str):
            print('string')
        elif isinstance(cell.value, int):
            print('integer')
        elif isinstance(cell.value, float):
            print('float')

使用cell.offset(column=1)获取下一个单元格。

很简单:

如果确定要写入 B 列:

for rowno,row in enumerate(ws.iter_rows('A{}:A{}'.format(ws.min_row,ws.max_row)),start=1):
    for cell in row:
        if isinstance(cell.value, str):
            print('string')
            ws.cell(row=rowno,column=2).value = str("string")
        elif isinstance(cell.value, int):
            print('integer')
            ws.cell(row=rowno,column=2).value = str("integer")
        elif isinstance(cell.value, float):
            print('float')
            ws.cell(row=rowno,column=2).value = str("float")
wb.save('C:\Users\Excel\Desktop\Book1.xlsx')

更通用的答案:

from openpyxl.utils import get_column_letter
from openpyxl.utils import coordinate_from_string, column_index_from_string

for rowno,row in enumerate(ws.iter_rows('A{}:A{}'.format(ws.min_row,ws.max_row)),start=1):
    for cell in row:
        if isinstance(cell.value, str):
            xy = coordinate_from_string(cell.coordinate)
            colno = column_index_from_string[0]
            ws.cell(row=rowno, column=colno+1).value = str("string")
        elif isinstance(cell.value, int):
            xy = coordinate_from_string(cell.coordinate)
            colno = column_index_from_string[0]
            ws.cell(row=rowno, column=colno+1).value = str("string")
        elif isinstance(cell.value, float):
            xy = coordinate_from_string(cell.coordinate)
            colno = column_index_from_string[0]
            ws.cell(row=rowno, column=colno+1).value = str("string")
wb.save('C:\Users\Excel\Desktop\Book1.xlsx')