How to create, insert and save the Excel in Ranorex
File: CreateInsertSaveExcel.UserCode.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Text.RegularExpressions;usingSystem.Drawing;usingSystem.Threading;usingWinForms=System.Windows.Forms;usingRanorex;usingRanorex.Core;usingRanorex.Core.Repository;usingRanorex.Core.Testing;usingMicrosoft.Office.Interop.Excel;namespaceGlobalProjects{publicpartialclassCreateInsertSaveExcel{privatevoidInit(){StoreDataInExcel();}publicstringRandomData(){stringalphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZ";stringdigits="0123456789";Randomr=newRandom();stringgenrate="";while(genrate.Length!=7){intrPick=r.Next(4);if(rPick==1){genrate+=alphabets[(r.Next(25))];}elseif(rPick==3){genrate+=digits[(r.Next(9))];}}stringempid="EMP_"+genrate;returnempid;}Excel.Applicationxlapp;Excel.Workbookxlworkbook;Excel.Worksheetxlworksheet;Excel.Rangexlrange;publicvoidStoreDataInExcel(){xlapp=newExcel.ApplicationClass();if(xlapp==null){Report.Info("Excel application not installed in this machine");}else{xlapp.Visible=true;xlapp.WindowState=Excel.XlWindowState.xlMaximized;xlworkbook=xlapp.Workbooks.Add(1);xlworksheet=(Excel.Worksheet)xlworkbook.Sheets["Sheet1"];xlworksheet.Name="Data";xlworksheet=(Excel.Worksheet)xlapp.Worksheets.get_Item(1);stringsheetname=xlworksheet.Name;Report.Info("Worksheet Name - "+sheetname);xlrange=xlworksheet.UsedRange;for(inti=1;i<=10;i++){xlrange.Cells[i,1]=RandomData();}Report.Info("Data successfully generated in Excel");try{if(!System.IO.File.Exists("D:\\Ranorex\\GlobalProjects\\RandomData")){xlapp.DisplayAlerts=false;xlworkbook.SaveAs("D:\\Ranorex\\GlobalProjects\\RandomData");Report.Success("Excel saved successfully. Status: Pass");xlworkbook.Close();}}catch{Report.Info("Excel not saved. Error: Path not found. Status: Fail");}}xlapp.Quit();}}}
Dear User, Thank you for visitng KodingWindow. If you are interested in technical articles, latest technologies, and our journey further, please follow us on LinkedIn.