Writing data into Excel File
In R, we can also write the data into our .xlsx file. R provides a write.xlsx() function to write data into the excel file. There is the following syntax of write.xlsx() function:
- The data_frame is our data, which we want to insert into our excel file.
- The file_names is the name of that file in which we want to insert our data.
- The col.names and row.names are the logical values that are specifying whether the column names/row names of the data frame are to be written to the file.
- The append is a logical value, which indicates our data should be appended or not into an existing file.
Let’s see an example to understand how write.xlsx() function works with its parameters.
#Loading xlsx package library("xlsx") #Creating data frame emp.data<- data.frame( name = c("Raman","Rafia","Himanshu","jasmine","Yash"), salary = c(623.3,915.2,611.0,729.0,843.25), start_date = as.Date(c("2012-01-01", "2013-09-23", "2014-11-15", "2014-05-11","2015-03-27")), dept = c("Operations","IT","HR","IT","Finance"), stringsAsFactors = FALSE ) # Writing the first data set in employee.xlsxRscript write.xlsx(emp.data, file = "employee.xlsx", col.names=TRUE, row.names=TRUE,sheetName="Sheet2",append = TRUE) # Reading the first worksheet in the file employee.xlsx. excel_data<- read.xlsx("employee.xlsx", sheetIndex = 1) print(excel_data) # Reading the first worksheet in the file employee.xlsx. excel_data<- read.xlsx("employee.xlsx", sheetIndex = 2) print(excel_data)