Use Excel with PythonInR
There are several other options to read and write to excel from R.
library(PythonInR)
##
## Initialize Python Version 2.7.9 (default, Mar 1 2015, 13:01:26)
## [GCC 4.9.2]
Version
pyExec("import openpyxl")
pyExecp("openpyxl.__version__")
## u'2.3.3'
Export data to “.xlsx”
pyImport(import="Workbook", from="openpyxl")
wb <- Workbook()
ws <- wb$active
## ws <- wb$get_active_sheet() ## for older version!
ws$title <- "cars"
## write append the first 10 rows to the workbook
ws$append(colnames(cars))
## NULL
for (i in seq(1, 10)) {
ws$append(as.matrix(cars[i,]))
}
ws$append(c('=SUM(A3:A10)', '=SUM(A3:A10)'))
## NULL
wb$save(th.string("cars.xlsx"))
## NULL
Import data from “.xlsx”
pyImport(import="load_workbook", from="openpyxl")
wb <- load_workbook("cars.xlsx")
wb$get_sheet_names()
## [1] "cars"
ws <- wb$get_sheet_by_name("cars")
pyExec("
def get_range(ws, first_row, first_col, last_row, last_col):
x = []
for m in range(first_row, last_row):
row = []
for n in range(first_col, last_col):
row.append(ws.cell(row = m, column = n).value)
x.append(row)
return x
")
do.call(rbind, pyCall("get_range", list(ws, 1L, 1L, 10L, 3L), simplify=FALSE))
## [,1] [,2]
## [1,] "speed" "dist"
## [2,] 4 2
## [3,] 4 10
## [4,] 7 4
## [5,] 7 22
## [6,] 8 16
## [7,] 9 10
## [8,] 10 18
## [9,] 10 26