将UI表数据写入CSV文件

本文关键字:CSV 文件 数据 UI | 更新日期: 2023-09-27 18:09:33

新到c#,我试图从一个网站上的数据表中获取数据,并将其保存为csv文件。到目前为止,我已经设法获得数据到csv文件,但每个记录附加到列a中的新单元格(如在Excel中查看)。即…

  A           B           C
1 A_record1
2 A_record2
3 A_record3
4 B_record1
5 B_record2
6 B_record3

而我希望数据以csv文件的格式…

  A           B           C
1 A_record1   A_record2   A_record3
2 B_record1   B_record2   B_record3

在第一个示例中填充csv的代码是…

//divided xpath In three parts to pass Row_count and Col_count values.
String firstPart = "//div[@id='lwDataGrid']/table/tbody/tr[";
String secondPart = "]/td[";
String thirdPart = "]";
//Row and Column counts
int rowCount = driver.FindElements(By.XPath("//div[@id='lwDataGrid']/table/tbody/tr[*]")).Count - 3;
int colCount = driver.FindElements(By.XPath("//div[@id='lwDataGrid']/table/tbody/tr[1]/td")).Count;
System.Diagnostics.Debug.WriteLine(rowCount + ": This is the number of rows in the table");
System.Diagnostics.Debug.WriteLine(colCount + ": This is the number of columns in the table");
string path = @"C:'...'my.csv";
for (int j = 2; j <= colCount; j++)
{
    //Used for loop for number of columns.
    for (int i = 4; i <= rowCount; i++)
    {
        //Prepared final xpath of specific cell as per values of i and j.
        String finalXpath = firstPart + i + secondPart + j + thirdPart;
        //Will retrieve value from located cell and print It.
        String tableData = driver.FindElement(By.XPath(finalXpath)).Text; 
        using (StreamWriter sw = File.AppendText(path))
        {
            sw.WriteLine(tableData);
        }
    }
}

最终目标是将此csv与另一个"预期结果"csv进行比较,以检查UI表中的数据是否符合预期。如果有比比较两个文件更有效的方法,即使用数组来比较结果csv,我愿意听取建议。

将UI表数据写入CSV文件

从-

for (int j = 2; j <= colCount; j++)
{
    //Used for loop for number of columns.
    for (int i = 4; i <= rowCount; i++)
    {
        //Prepared final xpath of specific cell as per values of i and j.
        String finalXpath = firstPart + i + secondPart + j + thirdPart;
        //Will retrieve value from located cell and print It.
        String tableData = driver.FindElement(By.XPath(finalXpath)).Text; 
        using (StreamWriter sw = File.AppendText(path))
        {
            sw.WriteLine(tableData);
        }
    }
}

到下面可以解决这个问题

    for (int j = 2; j <= colCount; j++)
        {
            using (StreamWriter sw = File.AppendText(path))
            {
                string line = string.Empty;
                //Used for loop for number of columns.
                for (int i = 4; i <= rowCount; i++)
                {
                    //Prepared final xpath of specific cell as per values of i and j.
                    String finalXpath = firstPart + i + secondPart + j + thirdPart;
                    //Will retrieve value from located cell and print It.
                    String tableData = driver.FindElement(By.XPath(finalXpath)).Text;
                    line = line + string.Format("{0},",tableData);
                }
                sw.WriteLine(line);
            }
        }