Open In App

How to Convert a CSV File to Microsoft Excel in R

Last Updated : 30 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

CSV refers to Comma-Separated Values. It holds plain text as a series of values (cells) separated by commas (, ) in a series of lines (rows). CSV file can actually open in a text editor and read it. 

On the other hand, Excel is used to display the data in horizontal and vertical rows. The data are usually stored in the cells. We have an option of formulas in Excel that can be used for data and its place of storage.

So, In this article, we are going to convert the CSV(Comma Separated Values) file into an Excel file using R Programming. So to do this first we need to read the contents of the CSV file into our R console and later on write it an excel file using functions in R. The xlsx package in R is used to manipulate data of an excel file using R. 

Syntax: write.xlsx(df,file,sheetName,col.names,row.names,append,showNA,password)

where,

  • df – data frame to be converted.
  • file – the path to output file(excelfile) is specified here.
  • sheetName – to string is passed as sheet name.
  • col.names – logical value indicating if the column names of the data frame are to be written in the file.
  • row.names – logical value indicating if the column names of the data frame are to be written in the file.

The code to Convert a CSV File to Microsoft Excel is given below.

R




# install required packages
install.packages("xlsx")
  
# load the package
library(xlsx)
  
# Read the contents of CSV file as dataframe
df<- read.csv("C:\\Users\\Downloads\\biostats.csv")
  
# convert the data frame to excel file
xlsx::write.xlsx(df,
                 "Hello.xls",
                 col.names=TRUE,
                 row.names=TRUE,
                 sheetName="sample")


Output:

 

Explanation

  1. As discussed earlier to manipulate the excel data we need installed the package xlsx.
  2. First we need to read the contents of CSV file in R using read.csv() function in R.
  3. Later on using write.xlsx(0 function we converted the csv file data which is stored as data frame into an excel file at our specified path.

Note

  1. During package installation it asks to select the CRAN mirror then on that window select your country.
  2. If we have not specified path in write.xlsx() function then by default the excel file is going to save where the R documents(Script files) are stored y default. 

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads