Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

Write test result to a specific cell in Excel spreadsheet

In some cases, automation engineers need to write test results to a specific cell in an Excel spreadsheet. The code snippet below is for your reference. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Microsoft.Office.Interop.Excel;

namespace com.seleniummaster
{
//this method will write test result to a specific cell in Excel spreadsheet
public static void WriteToExcelFile(string fpath, string fname, string resutlToWrite, int cellrow, int cellcolumn)
{


string myPath = @fpath +@"\"+fname;

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook = excelApp.Workbooks.Open(myPath);
System.Threading.Thread.Sleep(2000);

excelApp.Cells[cellrow, cellcolumn] = resutlToWrite;

excelApp.Visible = false;
excelApp.ActiveWorkbook.Save();
System.Threading.Thread.Sleep(2000);
workbook.Close(false, Type.Missing, Type.Missing);
excelApp.Workbooks.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);

excelApp.Quit();
GC.Collect();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
}