简体   繁体   English

R / openxlsx /在Excel文件中查找第一个非空单元格

[英]R / openxlsx / Finding the first non-empty cell in Excel file

I'm trying to write data to an existing Excel file from R, while preserving the formatting. 我正在尝试从R将数据写入现有的Excel文件,同时保留格式。 I'm able to do so following the answer to this question ( Write from R into template in excel while preserving formatting ), except that my file includes empty columns at the beginning, and so I cannot just begin to write data at cell A1. 我可以按照以下问题的答案进行操作( 在保留格式的同时从R中写入R到excel中的模板中 ),除了我的文件开头包含空列,因此我不能仅仅开始在单元格A1中写入数据。

As a solution I was hoping to be able to find the first non-empty cell, then start writing from there. 作为解决方案,我希望能够找到第一个非空单元格,然后从那里开始写入。 If I run read.xlsx(file="myfile.xlsx") using the openxlsx package, the empty columns and rows are automatically removed, and only the data is left, so this doesn't work for me. 如果我使用openxlsx包运行read.xlsx(file="myfile.xlsx") ,则空列和空行将被自动删除,仅保留数据,因此这对我不起作用。

So I thought I would first load the worksheet using wb <- loadWorkbook("file.xlsx") so I have access to getStyles(wb) (which works). 所以我想我首先要使用wb <- loadWorkbook("file.xlsx")加载工作表,这样我就可以访问getStyles(wb) (有效)。 However, the subsequent command getTables returns character(0) , and wb$tables returns NULL . 但是,后续命令getTables返回character(0) ,而wb$tables返回NULL I can't figure out why this is? 我不知道为什么会这样吗? Am I right in that these variables would tell me the first non-empty cell? 我对吗,这些变量会告诉我第一个非空单元格吗?

I've tried manually removing the empty columns and rows preceding the data, straight in the Excel file, but that doesn't change things. 我尝试手动在Excel文件中直接删除数据前面的空列和行,但这并没有改变。 Am I on the right path here or is there a different solution? 我在正确的道路上还是有其他解决方案?

As suggested by Stéphane Laurent , the package tidyxl offers the perfect solution here. 根据StéphaneLaurent的建议, tidyxl软件包在这里提供了完美的解决方案。

For instance, I can now search the Excel file for a character value, like my variable names of interest ("Item", "Score", and "Mean", which correspond to the names() of the data.frame I want to write to my Excel file): 例如,我现在可以在Excel文件中搜索字符值,例如感兴趣的变量名(“ Item”,“ Score”和“ Mean”,它们对应于我想要的data.framenames() 。写入我的Excel文件):

require(tidyxl)
colnames <- c("Item","Score","Mean")
excelfile <- "FormattedSheet.xlsx"
x <- xlsx_cells(excelfile)

  # Find all cells with character values: return their address (i.e., Cell) and character (i.e., Value)
  chars <- x[x$data_type == "character", c("address", "character")]

  starting.positions <- unlist(
    chars[which(chars$character %in% colnames), "address"]
  )
     # returns: c(C6, D6, E6)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM