47

I am writing codes to export database from R into Excel, I have been trying others codes including:

write.table(ALBERTA1, "D:/ALBERTA1.txt", sep="\t")
write.csv(ALBERTA1,":\ALBERTA1.csv")
your_filename_in_R = read.csv("ALBERTA1.csv")
your_filename_in_R = read.csv("ALBERTA1.csv")
write.csv(df, file = "ALBERTA1.csv")
your_filename_in_R = read.csv("ALBERTA1.csv")
write.csv(ALBERTA1, "ALBERTA1.csv")
write.table(ALBERTA1, 'clipboard', sep='\t')
write.table(ALBERTA1,"ALBERTA1.txt")
write.table(as.matrix(ALBERTA2),"ALBERTA2.txt")
write.table(as.matrix(vecm.pred$fcst$Alberta_Females[,1]), "vecm.pred$fcst$Alberta_Females[,1].txt")
write.table(as.matrix(foo),"foo.txt")
write.xlsx(ALBERTA2, "/ALBERTA2.xlsx")
write.table(ALBERTA1, "D:/ALBERTA1.txt", sep="\t").

Other users of this forum advised me this:

write.csv2(ALBERTA1, "ALBERTA1.csv")
write.table(kt, "D:/kt.txt", sep="\t", row.names=FALSE)

enter image description here

You can see on the pictures the outcome I have got from this codes above. But this numbers can't be used to make any further operations such as addition with other matrices.

Has someone experienced this kind of problems?

Jaap
  • 71,900
  • 30
  • 164
  • 175
ntamjo achille
  • 651
  • 1
  • 6
  • 10
  • 1
    If you don't post output of `dput(ALBERTA1)` or `dput(head(ALBERTA1))` we will not be able to help. There would be too much guesswork. – IRTFM Oct 16 '13 at 21:57
  • 1
    Note that this is apparently a follow up on [this](http://stackoverflow.com/q/19385494/324364) question. – joran Oct 16 '13 at 22:12
  • The first 6 numbers on RGUI interface are the following: 55.5486398, 57.8471114, 54.5190511, 50.5751821, 49.4739451, 53.4697459. You can check out that there is a short decimal part of each output. However, when i transfer the same list of numbers on Excel through codes presented above, I obtain the following unclear shape of output: 555.486.398.454.784, 578.471.113.839.479, 54.519.051.119.506, 49.473.945.115.391, 534.697.459.336.592, 505.751.821.039.884..etc of course unmanageable You can see that 555.486.398.454.784(in excel) is totally different from 55.5486398(R-gui interface). – ntamjo achille Oct 16 '13 at 23:48

6 Answers6

57

Another option is the openxlsx-package. It doesn't depend on and can read, edit and write Excel-files. From the description from the package:

openxlsx simplifies the the process of writing and styling Excel xlsx files from R and removes the dependency on Java

Example usage:

library(openxlsx)

# read data from an Excel file or Workbook object into a data.frame
df <- read.xlsx('name-of-your-excel-file.xlsx')

# for writing a data.frame or list of data.frames to an xlsx file
write.xlsx(df, 'name-of-your-excel-file.xlsx')

Besides these two basic functions, the openxlsx-package has a host of other functions for manipulating Excel-files.

For example, with the writeDataTable-function you can create formatted tables in an Excel-file.

Jaap
  • 71,900
  • 30
  • 164
  • 175
  • 2
    `openxlsx` depends on Rtools, which need to be installed and added to the System variables path. Not ideal for corporate computers. I use this and now trying to find alternatives as I need to make portable versions of my code which work without installing anything. – Arani Jan 02 '18 at 11:57
  • 1
    @Arani I highly doubt that. I have installed `openxlsx` on a Windows VM without having Rtools and it works as it should. – Jaap Jan 02 '18 at 12:09
  • 1
    in my case it does everything except `saveWorkbook`, or `write.xlsx`. For that it asks for Rtools. Mysterious! – Arani Jan 03 '18 at 04:22
  • @jaap some functions depends of Rtools but not all – Benmoshe Jun 29 '18 at 07:53
  • @DimitriPetrenko Could you indicate which functions? If haven't run into that problem yet and I use this package quite often (and a lot / most of its functions) – Jaap Jun 29 '18 at 08:22
  • 3
    @Jaap yes check this page https://github.com/awalker89/openxlsx/issues/111 – Benmoshe Jul 03 '18 at 12:35
  • this library is not updated since I get this warning --> `Note: zip::zip() is deprecated, please use zip::zipr() instead` – Ibo Sep 19 '19 at 23:26
35

Recently used xlsx package, works well.

library(xlsx)
write.xlsx(x, file, sheetName="Sheet1")

where x is a data.frame

d2a2d
  • 1,026
  • 10
  • 12
  • 17
    `xlsx` requires Java. If for whatever reason it is not accessible by R (strange settings on corporate computers), then this won't work. – StasK Jul 25 '16 at 22:57
  • 1
    Add jre path of java into System variables Path, then R can access Java functionalities. For this go to My computer Properties, then Advanced System Settings, and then environment variables. Add java path to "Path". – indra_patil Oct 15 '16 at 11:52
19

writexl, without Java requirement:

# install.packages("writexl")
library(writexl)
tempfile <- write_xlsx(iris)
lukeA
  • 48,497
  • 5
  • 73
  • 84
  • Unfortunately not great for corporate computers either: "Package which is only available in source form, and may need compilation of C/C++/Fortran: ‘writexl’ These will not be installed" – Julian Drago Jan 18 '19 at 23:34
  • @JulianDrago Can't you compile it on a non-corporate computer? – lukeA Jan 19 '19 at 17:54
  • 2
    Not an option for me, and for many others judging by the comments on this question. My comment is intended to be a heads up to those of us that this may not work in firewalled/non-admin user work environments - I suspect that many of us are here for that reason, looking for alternatives to the popular xlsx package that might work. – Julian Drago Jan 19 '19 at 19:44
11

The WriteXLS function from the WriteXLS package can write data to Excel.

Alternatively, write.xlsx from the xlsx package will also work.

zx8754
  • 42,109
  • 10
  • 93
  • 154
Christopher Louden
  • 7,007
  • 2
  • 23
  • 29
  • 10
    `xlsx` requires Java. `WriteXLS` requires Perl. If for whatever reason these are not accessible by R (I cannot that easily choose what to install on my corporate computer), then neither of these will work. (I understand it is convenient for the developers to rely on the existing Java and Perl libraries; but isn't R supposed to stand on its own legs??) – StasK Jul 25 '16 at 23:02
  • 1
    `writeXLS` can't deal with newlines in characters. – Ruben Feb 28 '17 at 14:26
-1

Here is a way to write data from a dataframe into an excel file by different IDs and into different tabs (sheets) by another ID associated to the first level id. Imagine you have a dataframe that has email_address as one column for a number of different users, but each email has a number of 'sub-ids' that have all the data.

data <- tibble(id = c(1,2,3,4,5,6,7,8,9), email_address = c(rep('aaa@aaa.com',3), rep('bbb@bbb.com', 3), rep('ccc@ccc.com', 3)))

So ids 1,2,3 would be associated with aaa@aaa.com. The following code splits the data by email and then puts 1,2,3 into different tabs. The important thing is to set append = True when writing the .xlsx file.


temp_dir <- tempdir()

for(i in unique(data$email_address)){
    
  data %>% 
    filter(email_address == i) %>% 
    arrange(id) -> subset_data
  
  for(j in unique(subset_data$id)){
    write.xlsx(subset_data %>% filter(id == j), 
      file = str_c(temp_dir,"/your_filename_", str_extract(i, pattern = "\\b[A-Za-z0- 
       9._%+-]+"),'_', Sys.Date(), '.xlsx'), 
      sheetName = as.character(j), 
      append = TRUE)}
 
  }

The regex gets the name from the email address and puts it into the file-name.

Hope somebody finds this useful. I'm sure there's more elegant ways of doing this but it works.

Btw, here is a way to then send these individual files to the various email addresses in the data.frame. Code goes into second loop [j]

  send.mail(from = "sender@sender.com",
            to = i,
          subject = paste("Your report for", str_extract(i, pattern = "\\b[A-Za-z0-9._%+-]+"), 'on', Sys.Date()),
          body = "Your email body",
          authenticate = TRUE,
          smtp = list(host.name = "XXX", port = XXX,
                      user.name = Sys.getenv("XXX"), passwd = Sys.getenv("XXX")),
          attach.files = str_c(temp_dir, "/your_filename_", str_extract(i, pattern = "\\b[A-Za-z0-9._%+-]+"),'_', Sys.Date(), '.xlsx'))


Primesty
  • 89
  • 8
-4

I have been trying out the different packages including the function:

install.packages ("prettyR") 

library (prettyR)

delimit.table (Corrvar,"Name the csv.csv") ## Corrvar is a name of an object from an output I had on scaled variables to run a regression.

However I tried this same code for an output from another analysis (occupancy models model selection output) and it did not work. And after many attempts and exploration I:

  • copied the output from R (Ctrl+c)
  • in Excel sheet I pasted it (Ctrl+V)
  • Select the first column where the data is
  • In the "Data" vignette, click on "Text to column"

  • Select Delimited option, click next

  • Tick space box in "Separator", click next

  • Click Finalize (End)

Your output now should be in a form you can manipulate easy in excel. So perhaps not the fanciest option but it does the trick if you just want to explore your data in another way.

PS. If the labels in excel are not the exact one it is because Im translating the lables from my spanish excel.

NarendraR
  • 6,770
  • 7
  • 35
  • 69
Fabiola
  • 1
  • 3