简体   繁体   English

如何使用 Python 删除 Excel 工作表中的一行?

[英]How To Delete A Row In Excel Sheet Using Python?

I am working on a Selenium program using Python where I want to delete a row in the Excel sheet using Openpyxl library.我正在使用Python Selenium程序,我想使用Openpyxl库在Excel表中删除一行。 The issue is I don't know how to implement the delete function in my program.问题是我不知道如何在我的程序中实现删除 function 。 Below here have 2 classes, AutoTest.py which is the testing class and NewCard.py which is the class where I implemented POM(Page Object Model) .下面有 2 个类, AutoTest.py是测试 class 和NewCard.py是 class ,我在其中实现了POM(Page Object Model) May I know how to implement the function to delete just 1 row in accordance with my program?我可以知道如何根据我的程序执行 function 以仅删除 1 行吗?

AutoTest.py自动测试.py

import unittest
import HtmlTestRunner
from selenium import webdriver
import openpyxl
import sys
sys.path.append("C:\Users\lukegoh\Desktop\Python Projects\SoftwareAutomationTesting")
from pageObjects.LoginPage import LoginPage
from pageObjects.HomePage import Homepage
from pageObjects.NewCard import NewCard

excpath = r"C:\Users\lukegoh\Desktop\Python Projects\SoftwareAutomationTesting\excel\new\ABT0475EC Card Init Detailed Rpt Test 01 - v13_1.xlsx"
excsheetName = "ABT0475EC Card Initialization D"

class AutoTest(unittest.TestCase):
    baseURL = "https://10.2.5.215:33000/viewTopUpRequest"
    username = "ezltest2svc"
    password = "Password123!"
    driver = webdriver.Chrome()

    @classmethod
    def setUpClass(cls):
        cls.driver.get(cls.baseURL)
        cls.driver.maximize_window()
        cls.driver.implicitly_wait(10)


    def test_1(self):  #This is scenario 1- to create request for new card
        lp = LoginPage(self.driver)
        hp = Homepage(self.driver)
        np = NewCard(self.driver)
        lp.setUsername(self.username)
        lp.setPassword(self.password)
        lp.clickLogin()
        hp.clickutil()
        hp.clickreqNewCard()
        np.setJobOrder()
        np.clickExcel()
        np.setTopUpAmount()
        np.calculateAmount()
        if not np.clickSubmit():
            np.deleteRow(excpath,excsheetName,3)
        else:
            print("Test Passed")


   # @classmethod
   # def tearDownClass(cls):
   #     cls.driver.close()
   #     print("Test Completed")


#if __name__ == '__main__':
#    unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='C:/Users/lukegoh/Desktop/Python Projects/SoftwareAutomationTesting/reports'))

NewCard.py新卡.py

import openpyxl

class NewCard:

    jobOrder_xpath="//body/div[@id='wrapper']/div[3]/div[1]/div[1]/div[1]/div[1]/input[1]"
    excelButton_xpath="//input[@id='img']"
    topup_textbox_xpath="//input[@id='input-live']"
    calculateAmount_xpath="(//button[@type='button'])[4]"
    buttonSubmit_xpath="(//button[@type='button'])[5]"


    def __init__(self,driver):
        self.driver=driver


    def setJobOrder(self):
        self.driver.find_element_by_xpath(self.jobOrder_xpath).send_keys("AutoTest1")

    def clickExcel(self):
        self.driver.find_element_by_xpath(self.excelButton_xpath).send_keys(r"C:\Users\lukegoh\Desktop\Python Projects\SoftwareAutomationTesting\excel\new\ABT0475EC Card Init Detailed Rpt Test 01 - v13_1.xlsx")

    def setTopUpAmount(self):
        self.driver.find_element_by_xpath(self.topup_textbox_xpath).send_keys("10")

    def calculateAmount(self):
        self.driver.find_element_by_xpath(self.calculateAmount_xpath).click()

    def clickSubmit(self):
        self.driver.find_element_by_xpath(self.buttonSubmit_xpath).click()

    def deleteRow(file, sheetName, rownum):
        workbook = openpyxl.load_workbook(file)
        sheet = workbook.get_sheet_by_name(sheetName)
        sheet.cell(row=rownum).
        workbook.save(file)

If you check OpenPyXL docs, it has something called delete_rows()如果你查看 OpenPyXL 文档,它有一个叫做delete_rows()的东西

Syntax delete_rows(idx, amount=1) , it deletes from idx and goes on deleting for amount语法delete_rows(idx, amount=1) ,它从idx中删除并继续删除amount

import openpyxl

filename = "example.xlsx"
wb = openpyxl.load_workbook(filename)
sheet = wb['Sheet1']
sheet.delete_rows(row_number, 1)
wb.save(filename)

Docs for delete_rows() : https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.worksheet.html#openpyxl.worksheet.worksheet.Worksheet.delete_rows delete_rows()的文档: https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.worksheet.html#openpyxl.worksheet.worksheet.Worksheet.delete_rows

use pandas使用 pandas

 import pandas as pd
 df = pd.read_excel("test.xlsx")
 df = df.drop(df.index[1])
 df.to_excel('test1.xlsx')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 python 从 excel 表中删除行 - delete the rows from excel sheet using python 使用python删除最后一张excel - 错误 - Delete last sheet of excel using python - ERROR 如果使用 python 在 excel 中发现重复数据,如何删除以下行? - How to delete the following row if duplicated data found in excel using python? 使用Python删除excel文件中的整行 - Delete an entire row in an excel file using Python 用Python删除excel行 - Delete excel row with Python 如何使用 python 删除 SharePoint excel 工作表中存在的所有行? - How to delete all the rows present in SharePoint excel sheet table using python? 如何使用 python 脚本将一行中存在的数据(以空格分隔)拆分为同一 excel 工作表中的不同列? - How to split data present in a row (separated by space) into different column in the same excel sheet using python script? 如何使用用户输入的 python pandas 从 excel 打印完整行? - How to print complete row from excel Sheet using python pandas from user input? 如何使用 Python 遍历 Excel 工作表的行或列并在单元格中查找特定值? - How to iterate over a Row or Column of an Excel sheet using Python and look for specific value in cells? 如何使用 Python Script 下载 Excel 表格中每一行下的 PDF 文件? - How to download PDF files under each row in Excel sheet using Python Script?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM