如何使用Selenium WebDriver和C#将数据写入Excel文件?

时间:2016-05-26 06:20:17

标签: c# selenium-webdriver

如何使用C#中的Selenium WebDriver将数据写入excel文件。我正在使用配置文件读取所有Excel数据。

2 个答案:

答案 0 :(得分:0)

您可以分享创建问题的代码部分吗? 以下是可能对您有帮助的示例代码 -

从数据表到csv -

        StringBuilder sb = new StringBuilder();

        IEnumerable<string> columnNames = resultstable.Columns.Cast<DataColumn>().
                                          Select(column => column.ColumnName);
        sb.AppendLine(string.Join(",", columnNames));

        foreach (DataRow row in resultstable.Rows)
        {
            IEnumerable<string> fields = row.ItemArray.Select(field =>
              string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
            sb.AppendLine(string.Join(",", fields));
        }

        File.WriteAllText("C:\\path\\Test.csv", sb.ToString());

将它直接写入csv使用system.io中的文件功能

File.AppendAllText(@"C:\\path\\test.csv","data to write"+ Environment.NewLine);

答案 1 :(得分:0)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    using Excel = Microsoft.Office.Interop.Excel;

    namespace WriteExcelData
    {
    class Program
    {
    static void Main(string[] args)
    {
        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.Application();
        xlWorkBook = xlApp.Workbooks.Add(misValue);

        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        List MyInfo = new List { "CLASS NAME", "RESULT", "ReadExcelData", "Success", "WriteExcelData", "Success" };

        int index = 0;
        for (int i = 1; i <= 3; i++)
        {
            for (int j = 1; j <= 2; j++)
            {
                xlWorkSheet.Cells[i, j] = MyInfo[index];
                index++;
            }
        }

        var fileLocation = "C:\\Users\\user\\Desktop\\Selenium       Learing\\WriteExcelData\\TestResultFile\\MyExcelFile.xls";

        xlWorkBook.SaveAs(fileLocation, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();
    }
}

}