简体   繁体   English

在 R 中将 a.CSV 文件添加到 excel 作为工作表

[英]Adding a .CSV file to excel as a sheet in R

I'm able to add a dataframe to excel as a separate sheet.我可以将 dataframe 添加到 excel 作为单独的表格。 However, I want to be able to add a.CSV file that is already created as a sheet.但是,我希望能够添加已经创建为工作表的 .CSV 文件。

Code that works to add dataframe as a sheet:用于将 dataframe 添加为表格的代码:

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.但是,它不是 dataframe,而是一个 .CSV 文件。 Is there a solution?有解决办法吗?

Thanks谢谢

To start, here is a template that you can use to import an Excel file into R:首先,您可以使用以下模板将 Excel 文件导入 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:如果要在 Excel 文件中导入特定工作表,则可以使用此模板:

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:注意:在 R 控制台中,键入以下命令以安装 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 :似乎您的解决方案中唯一缺少的步骤是首先使用read.csvread.table将 CSV 文件读入 dataframe :

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.如果您特别想将 csv 添加到 excel 工作表而不首先阅读它,那么这是另一个故事,您应该在您的问题中澄清它。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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