我有一个用 C# 编写的 Selenium WebDriver 脚本,它从 Excel 电子表格中读取一些值,然后使用该行中的值来填写 Web 表单。我现在面临的挑战是它从 Excel 文件中获取第一个单元格值并将其输入到表单中的所有字段中,然后获取下一个值并执行相同的操作,依此类推。
我怎样才能使它取第一个值,添加到表单中的第一个(命名字段),取第二个值和第二个命名字段等等。
请参阅下面的方法代码。
public void FillForm()
//Function reads entries from an Excel spreadsheet then uses values to populate and fill the form
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range xlrange;
string xlString;
int xlRowCnt = 0;
int xlColCnt = 0;
xlApp = new Excel.Application();
//Open Excel file
xlWorkBook = xlApp.Workbooks.Open(@"D:\Projects\Data\MSI_Data_file.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//This gives the used cells in the sheet
xlrange = xlWorkSheet.UsedRange;
for (xlRowCnt = 1; xlRowCnt <= xlrange.Rows.Count; xlRowCnt++)
{
for (xlColCnt = 1; xlColCnt <= xlrange.Columns.Count; xlColCnt++)
{
xlString = (string)(xlrange.Cells[xlRowCnt, xlColCnt] as Excel.Range).Value2;
driver.FindElement(By.XPath("//input[contains(@name, 'FirmName')]")).SendKeys(xlString);
driver.FindElement(By.XPath("//input[contains(@name, 'FirstName')]")).SendKeys(xlString);
driver.FindElement(By.XPath("//input[contains(@name, 'LastName')]")).SendKeys(xlString);
driver.FindElement(By.XPath("//input[contains(@name, 'Email')]")).SendKeys(xlString);
driver.FindElement(By.XPath("//input[contains(@name, 'FirmAddress')]")).SendKeys(xlString);
driver.FindElement(By.XPath("//select[@id= 'ddlCountry']")).SendKeys(xlString);
driver.FindElement(By.XPath("//input[contains(@name, 'PhoneNumber')]")).SendKeys(xlString);
driver.FindElement(By.XPath("//input[contains(@name, 'FaxNumber')]")).SendKeys(xlString);
driver.FindElement(By.XPath("//input[contains(@name, 'Website')]")).SendKeys(xlString);
driver.FindElement(By.XPath("//textarea[contains(@name, 'Comments')]")).SendKeys(xlString);
driver.FindElement(By.XPath("//input[@id='chkFirm_Service_Accounting']")).Click();
driver.FindElement(By.XPath("//select[contains(@name, 'LeadSource')]")).SendKeys(xlString);
//save screenshot of completed form
SaveScreenShot("CompleteForm");
driver.FindElement(By.XPath("//a[contains(text(), 'Submit')]")).Click();
//Take screenshot of successful form submission
SaveScreenShot("Submission_Success");
driver.FindElement(By.XPath("//a[contains(text(), 'click here')]")).Click();
}
}
}