2016-09-16 131 views
0

我正在嘗試將xlsx文件讀入R並提取Excel公式。看來,Apache POI是Job的正確工具,但是我無法讓它工作。我發現這個Page列出了POI組件及其依賴關係。我試了下面的代碼:RIO中的Apache POI

require(rJava) 
.jinit() 
.jaddClassPath("poi-3.11-20141221.jar") 
.jaddClassPath("poi-ooxml-3.11-20141221.jar") 
.jaddClassPath("poi-ooxml-schemas-3.11-20141221.jar") 
.jaddClassPath("xmlbeans-2.6.0.jar") 

inputStream <- .jnew("java/io/FileInputStream", path.expand(file.path)) 

xfile <- .jnew("org/apache/poi/xssf/eventusermodel/XSSFWorkbook", 
      .jcast(inputStream,"java/io/InputStream")) 
wext <- .jnew("org/apache/poi/xssf/extractor/XSSFExcelExtractor", xfile) 

text <- .jcall(wext, "Ljava/lang/String;", "getText") 

這導致java.lang.ClassNotFoundException錯誤。有人能指引我朝着正確的方向嗎?

回答

3

UPDATE

devtools::install_git("https://gitlab.com/hrbrmstr/xlsxtractr.git") 

devtools::install_github("hrbrmstr/xlsxtractr") 

然後:

doc <- read_xlsx(system.file("extdata/wb.xlsx", package="xlsxtractr")) 

extract_formulas(doc, 1) 
## # A tibble: 3 × 3 
## sheet cell   f 
## <dbl> <chr>  <chr> 
## 1  1 A4 SUM(A1:A3) 
## 2  1 B4 SUM(B1:B3) 
## 3  1 D4 SUM(A4:B4) 

摘自所有片材都與式公式:

purrr::map_df(seq_along(doc), ~extract_formulas(doc, .)) 

它只提取formlua,但現在它是其他功能的其他基礎可能會丟失(等待它...) excel借出軟件包。


這很容易被改編成小包裝或功能採取的路徑到xlsx文件並提取公式如此:

library(xml2) 
library(purrr) 

# need to write code to do the unzipping and also to work with all the 
# sheets from the xlsx file. 

sheet <- read_xml("~/dir/wb/xl/worksheets/sheet1.xml") 
ns <- xml_ns_rename(xml_ns(sheet), d1 = "x") 
xml_find_all(sheet, ".//x:row", ns) %>% 
    map_df(function(row) { 
    xml_find_all(row, ".//x:c", ns) %>% 
     map_df(function(col) { 
     xml_find_all(col, ".//x:f", ns) %>% 
      xml_text() -> f 
     if (length(f) > 0) { 
      data_frame(cell=xml_attr(col, "r"), f=f) 
     } else { 
      NULL 
     } 
     }) 
    }) 
## # A tibble: 2 × 2 
## cell      f 
## <chr>     <chr> 
## 1 B2   SUM(A1:A3) 
## 2 C2 SUM(A1:A3)*SUM(A1:A3) 

如果你有xls文件,這將不工作,但是。

+0

謝謝你的努力和出色的工作。您應該考慮將您的解決方案提供給'openxlsx'軟件包。目前有一個功能請求完全相同的[東西](https://github.com/awalker89/openxlsx/issues/202) – count