openxlsx deleteRows corrupting file - r

Im reading in a template file, delete rows and then saving the file again but when I try to open up the file excel says it is corrupted.
Here is my code:
template <- loadWorkbook('foo.xlsx')
deleteData(template,sheet=1,cols=1:10000, rows = 6:10005 gridExpand = FALSE)
saveworkbook(template,'foo-test.xlsx',overwrite = TRUE
I have even tried it without the deleteData line and it still corupt the file.
Anyone have ideas son how I can change my code/ not corrupt the file.

Related

File opened with XLConnect doesn't close

I am working on an excel file with several sheets:
path_metadata<- file.path("archivos", "metadatos", "metadatos-copia.xlsx")
metadata_wb <- loadWorkbook(path_metadata)
Then I do some sheet manipulation (e.g. I write a data frame on a sheet), so I write it:
writeWorksheet(metadata_wb, df, sheet = "metadata")
And apply some style I have previously worked out
setCellStyle(metadata_wb,
formula = rango_header_1,
cellstyle = style_header)
And lastly, I save it
saveWorkbook(metadata_wb)
The problem comes when I try then to move onto the excel file and modify and save anything on it, it reports I cannot do it, because another instance keeps the file open.
I cannot do a close(metadata_wb) with an object of class workbook
What am I missing?
Thanx

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
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)
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")

Confused creating an xlsx file in R

I'm trying to read a txt file and create an xlsx out of it. and here is my code.
setwd("~/Downloads/Test")
FILES <- list.files( pattern = ".txt")
library(openxlsx)
for (i in 1:length(FILES)) {
FILE=read.delim(FILES[i],header=F,stringsAsFactors=FALSE,sep = "\t",, quote = "")
colnames(FILE) <- c("A","B","C","D","E","F")
write.csv(FILE,file="Dummy.xls")
}
when I run this piece of code, I'm able to create an Excel file with xls extension, but when I try to do the same with xlsx, by changing file="Dummy.xlsx", the file is getting created, but when I open it, I'm getting the below error.
please let me know where am I going wrong and how can I fix this.
Thanks

Append text to an Excel file

I have an excel file that I alread wrote code to. I want to add another line of code. Suppose, I want to add "Hello" under the data already there. I tried:
write.xlsx("Hello", "text.xlsx", sheetName = "Sheet1", append = TRUE)
And got the error:
Error in .jcall(wb, "Lorg/apache/poi/ss/usermodel/Sheet;", "createSheet", :
java.lang.IllegalArgumentException: The workbook already contains a sheet of this name
I was wondering how I could solve this problem.
Depending on how complex you want to get here is a simple way to load your text into excel
path = r'ENTER FILE PATH AND DESIRED FOLDER NAME HERE FOLLOWED BY .csv' #plug in the
folder path you want to save this as ending it with the filename.csv of your choice
with open(path, 'w', newline='', encoding='utf-8') as resultfile:
wr = csv.writer(resultfile, dialect='excel')
wr.writerow([x[0] for x in cursor.description])
for record in records:
wr.writerow(record)

read csv file from zipped temp file with multiple folders in R

I am trying to read a csv file that is contained in a file I extracted from the web. The problem is the zipped file has multiple cascading folders. I have to do that for several different units, so I am performing a loop. There is no problem with the loop, the file name is correct and I get to download the file. However I get an error message (and I think is because R cannot find the exact file I am asking it to find). The error is:
Error in open.connection(file, "rt") : cannot open the connection
In addition: Warning message:
In open.connection(file, "rt") :
cannot locate file 'XXXX.csv' in zip file 'c:\yyy\temp\bla\'
download.file(paste("http://web.com_",units[i],"_",places[j],".zip",
sep=""),
temp,
cacheOK = F )
data <- read.csv2(unz(temp,
paste("name_",units[i],"_",places[j],".csv",
sep="")),
header=F,
skip=1)
unlink(temp)
fili<-rbind(X,
data)
}
How do I make R find the file I want?
You have the right approach but (as the warning tells you) the wrong filename.
It's worth double checking that the zip file does exist before you start trying to read its contents.
if(file.exists(temp))
{
read.csv2(unz(...))
} else
{
stop("ZIP file has not been downloaded to the place you expected.")
}
It's also a good idea to a browse around inside the downloaded file (you may wish to unzip it first) to make sure that you are looking in the right place for the CSV contents.
It looks like the file, you're going to read, is located in directory. In this case your reading should be changed as follows:
data <- read.csv2(unz(temp,
paste("**dirname**/name_",units[i],"_",places[j],".csv",
sep="")),
header=F,
skip=1)

Resources