Openpyxl 追加数据

Openpyxl append data

如何附加我在循环中声明的变量。我需要在一个单元格、角色和 activeStatus 中附加 userLogin、lastname + firstname?这将列出关于此 excel 文件的大数据。

for user in root.findall('user'):
    login = user.find('login').text
    #create excel
    wb = Workbook()
    ws = wb.active
    ws.title = "Active Users"
    ws['A1'] = "Login"
    ws['B1'] = "User Name"
    ws['C1'] = "Role"
    ws['D1'] = "Status"
    for m in tls.getUserByLogin(login):
            user_status = int(m.get("isActive"))
            
            if user_status == 1:
                lastname = m.get("lastName")
                firstname = m.get("firstName")
                userLogin = m.get("login")
                activeStatus = ("Active User")
                role = m.get("globalRole")
                tproject = m.get("tprojectRoles")
                
                print("Login: " + userLogin + " " + lastname + " " + firstname + " Role: " + str(role['name']) + " " + str(activeStatus))
                
            else:
                inactive = (str(m.get("firstName")) + " " + str(m.get("lastName")) +": User is not Active")
                print(inactive)
    wb.save(filename = 'USERS.xlsx')

你试过这个吗? ws.cell(row=row_no, column=column_no, value=value)

您可以使用以下代码更新 excel。如果您遇到任何错误,请告诉我,因为我没有 运行 因为我没有所需的数据。假设您只想添加活跃用户。

from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
import pandas as pd
#create excel
wb = Workbook()
ws = wb.active
ws.title = "Active Users"

df=pd.DataFrame(columns=["Login", "User Name", "Role", "Status"])

for user in root.findall('user'):
    login = user.find('login').text

    for m in tls.getUserByLogin(login):
            user_status = int(m.get("isActive"))
            
            if user_status == 1:
                lastname = m.get("lastName")
                firstname = m.get("firstName")
                userLogin = m.get("login")
                activeStatus = ("Active User")
                role = m.get("globalRole")
                tproject = m.get("tprojectRoles")
                
                print("Login: " + userLogin + " " + lastname + " " + firstname + " Role: " + str(role['name']) + " " + str(activeStatus))
                df.loc[len(df.index)] =[userLogin, lastname, str(role['name'], str(activeStatus))]
            else:
                inactive = (str(m.get("firstName")) + " " + str(m.get("lastName")) +": User is not Active")
                print(inactive)

for rows in dataframe_to_rows(df, index=False, header=True):
    ws.append(rows)
wb.save(filename = 'USERS.xlsx')