[英]Combine csv files of different formats and make into one excel with different sheets
I have four csv files with different formats and variables, combining these 4 CSV files into one excel file using below code 我有四个具有不同格式和变量的csv文件,使用以下代码将这4个CSV文件合并为一个excel文件
library(rJava)
library(xlsx)
rm(list = ls())
# getting the path of all reports (they are in csv format)
files <- list.files(pattern = "\\.csv$")
# creating work book
wb <- createWorkbook()
# going through each csv file
for (item in files)
{
# create a sheet in the workbook
sheet <- createSheet(wb, sheetName=strsplit(item,"[.]")[[1]][1])
# add the data to the new sheet
addDataFrame(read.csv(item), sheet,row.names=FALSE)
}
# saving the workbook
saveWorkbook(wb, "crosstabs of data.xlsx")
In csv file one sheet the variable name is source / Medium But it is appeared in output excel file as Source...Medium, % New Sessions variable is appeared as X..New.Sessions and all variables delimited space occupied with . 在csv文件中,一个变量名称为source / Medium,但在输出excel文件中显示为Source ... Medium,%New Sessions变量显示为X..New.Sessions,所有变量都用分隔。 in output excel file How to overcome this i need what ever the variable names in CSV files same as in output Excel file
在输出excel文件中如何解决此问题,我需要CSV文件中与输出Excel文件中相同的变量名
This problem is due to read.csv changing names of headers. 此问题是由于read.csv更改标头名称引起的。 Column headers like
gi/joe
will be converted in gi.joe
if we do read.csv
with header=T
. 如果我们使用
header=T
进行read.csv
转换,则gi/joe
类的列标题将在gi.joe
进行转换。 So one need to convert just the header names again using: 因此,需要使用以下方法再次仅转换标头名称:
names(df) <- gsub("\\.","/",names(df))
OR if acceptable do simply (read headers as data): 或者,如果可以接受,则简单地进行操作(将标头读取为数据):
addDataFrame(read.csv(item,header=F), sheet,row.names=FALSE)
On a separate note looks like names like gi/joe
are not allowed as excel sheet names. 在单独的注释上看起来像
gi/joe
类的名称不允许作为excel工作表名称。 Now to validate limitation in excel end open excel and try to name a sheet hi/5
. 现在要验证excel中的限制,请打开excel并尝试将其命名为
hi/5
。 One should get error saying The sheet name contains invalid characters: : \\ / ? * [ ].
会出现一个错误,说工作
The sheet name contains invalid characters: : \\ / ? * [ ].
The sheet name contains invalid characters: : \\ / ? * [ ].
[I am testing this on mac excel 15.19.1] [我正在Mac excel 15.19.1上对此进行测试]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.