简体   繁体   中英

Adding a .CSV file to excel as a sheet in R

I'm able to add a dataframe to excel as a separate sheet. However, I want to be able to add a.CSV file that is already created as a sheet.

Code that works to add dataframe as a sheet:

library(xlsx)
write.xlsx(dataframe, file = excelFileName,
           sheetName=excelsheetname, append=TRUE,row.names = FALSE)

I need to be able to replicate the same thing as above. However, instead of a dataframe, it is a.CSV file. Is there a solution?

Thanks

To start, here is a template that you can use to import an Excel file into R:

library("readxl")
read_excel("Path where your Excel file is stored\\File Name.xlsx")

And if you want to import a specific sheet within the Excel file, then you may use this template:

library("readxl")
read_excel("Path where your Excel file is stored\\File Name.xlsx",sheet = "Your sheet name")

Note: In the R Console, type the following command to install the readxl package:

install.packages("readxl")

It seems like the only step missing in your solution is to first read the CSV file into a dataframe using read.csv or read.table :

library(xlsx)
dataframe <- read.csv(csv)
write.xlsx(dataframe, file = excelFileName,
           sheetName=excelsheetname, append=TRUE,row.names = FALSE)

If you specifically want to add a csv to an excel sheet without first reading it in then that is another story, and you should clarify it in your question.

The following works and suits my needs.

csvDF = read.csv(file = csvFileName, as.is = 1,stringsAsFactors = FALSE, header = FALSE)
write.xlsx(csvDF , file = excelFileName,sheetName=sheetNameInfo, append=TRUE,row.names = FALSE, col.names = FALSE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM