rexcelxlsxxlsm

Convert .xlsm to .xlsx in R


I would like to convert an Excel file (say it's name is "Jimmy") that is saved as a macro enabled workbook (Jimmy.xlsm) to Jimmy.xlsx.

I need this to be done in a coding environment. I cannot simply change this by opening the file in Excel and assigning a different file-type. I am currently programming in R. If I use the function

file.rename("Jimmy.xlsm", "Jimmy.xlsx")

the file becomes corrupted.


Solution

  • In your framework you have to read in the sheet and write it back out. Suppose you have an XLSM file (with macros, I presume) called "testXLSM2X.xlsm" containing one sheet with tabular columns of data. This will do the trick:

    library(xlsx)
    r <- read.xlsx("testXLSMtoX.xlsm", 1) # read the first sheet
    # provides a data frame
    # use the first column in the spreadsheet to create row names then delete that column from the data frame
    # otherwise you will get an extra column of row index numbers in the first column
    r2w<-data.frame(r[-1],row.names=r[,1])
    w <- write.xlsx(r2w,"testXLSMtoX.xlsx") # write the sheet
    

    The macros will be stripped out, of course.

    That's an answer but I would question what you are trying to accomplish. In general it is easier to control R from Excel than Excel from R. I use REXCEL from http://rcom.univie.ac.at/, which is not open source but pretty robust.