簡體   English   中英

我可以從 R 中的同一數據幀中寫入相同的 xlsx 文件嗎?

[英]Can I write identical xlsx files from the same data frame in R?

當給定要寫入的相同數據時,我能否確保兩個 XLSX 文件(使用openxlsx::write.xlsx )相同? 我認為電子表格中寫入了一個時間戳,這意味着相隔一秒以上寫入的相同數據會創建一個不同的文件。

例如,當快速連續編寫時:

library(openxlsx)
write.xlsx(mtcars, "/tmp/t1.xlsx");write.xlsx(mtcars, "/tmp/t2.xlsx")

這些文件是相同的:

$ md5sum /tmp/t?.xlsx
c9b5f6509e20dd62b158debfbef376fe  /tmp/t1.xlsx
c9b5f6509e20dd62b158debfbef376fe  /tmp/t2.xlsx

但如果我在寫之間睡覺:

unlink("/tmp/t1.xlsx") # remove previous
unlink("/tmp/t2.xlsx")
write.xlsx(mtcars, "/tmp/t1.xlsx");Sys.sleep(2);write.xlsx(mtcars, "/tmp/t2.xlsx")

它完全不同:

$ md5sum /tmp/t?.xlsx
460945a610df3bc8a1ccdae9eb86c1fa  /tmp/t1.xlsx
a4865be49994092173792c9f7354e435  /tmp/t2.xlsx

我的用例是一個生成 XLSX 文件的進程,該文件將進入 git 存儲庫。 如果我自動執行此操作,則 XLSX 文件每次都會更改,即使源數據沒有更改。 我想可以測試數據是否在流程的早期發生了變化,而不是生成新的 XLSX 文件,但讓 git 做“這有變化嗎?”似乎更容易。 測試,但 XLSX 中明顯不可見的元數據打破了這一點。 叫我懶惰。

可以設置 XLSX 元數據來防止這種情況嗎? 我想也許那里有一個“創作日期”。 我不在乎這是否一直是 1970-01-01。

先發制人的防御:不,我不能使用 CSV,XLSX 有多個工作表,這就是我的最終用戶想要的。 是的,我也已經將它寫入 SQlite 數據庫,並且在向其寫入相同數據時是相同的。

I don't think this can be done with openxlsx as is, since the difference is due to the metadata XML created: https://github.com/ycphs/openxlsx/blob/7742063a4473879490d789c552bb8e6cc9a0d2c7/R/baseXML.R#L77 where it將當前的Sys.time()放入created的字段中。

似乎有兩個差異來源。 首先,將 Excel 元數據寫入 MS Excel 文檔結構中的<dcterms:created>元數據。 但是即使設置相同(通過猴子修補openxlsx )仍然會產生差異,因為文檔是使用標准 ZIP 格式捆綁的,並且還具有日期戳標頭。

這是兩個解壓縮的 XLSX 文件,它顯示了所有相同的 CRC-32 值,因此其中的文件是相同的:

Archive:  test1.xlsx
 Length   Method    Size  Cmpr    Date    Time   CRC-32   Name
--------  ------  ------- ---- ---------- ----- --------  ----
     587  Defl:N      234  60% 2022-01-31 15:22 b5dbec60  _rels/.rels
    1402  Defl:N      362  74% 2022-01-31 15:22 63422601  [Content_Types].xml
     284  Defl:N      173  39% 2022-01-31 15:22 f9153db0  docProps/app.xml
     552  Defl:N      278  50% 2022-01-31 15:22 37126cbe  docProps/core.xml
     696  Defl:N      229  67% 2022-01-31 15:22 14a147d3  xl/_rels/workbook.xml.rels
    4500  Defl:N      311  93% 2022-01-31 15:22 285db1ad  xl/printerSettings/printerSettings1.bin
     601  Defl:N      203  66% 2022-01-31 15:22 211e1d6e  xl/sharedStrings.xml
    1127  Defl:N      464  59% 2022-01-31 15:22 0d8ee71d  xl/styles.xml
    7075  Defl:N     1361  81% 2022-01-31 15:22 050f988c  xl/theme/theme1.xml
     950  Defl:N      382  60% 2022-01-31 15:22 1b8cce29  xl/workbook.xml
     612  Defl:N      223  64% 2022-01-31 15:22 f0584777  xl/worksheets/_rels/sheet1.xml.rels
   12729  Defl:N     2204  83% 2022-01-31 15:22 18057777  xl/worksheets/sheet1.xml
--------          -------  ---                            -------
   31115             6424  79%                            12 files
$ unzip -v test2.xlsx
Archive:  test2.xlsx
 Length   Method    Size  Cmpr    Date    Time   CRC-32   Name
--------  ------  ------- ---- ---------- ----- --------  ----
     587  Defl:N      234  60% 2022-01-31 15:22 b5dbec60  _rels/.rels
    1402  Defl:N      362  74% 2022-01-31 15:22 63422601  [Content_Types].xml
     284  Defl:N      173  39% 2022-01-31 15:22 f9153db0  docProps/app.xml
     552  Defl:N      278  50% 2022-01-31 15:22 37126cbe  docProps/core.xml
     696  Defl:N      229  67% 2022-01-31 15:22 14a147d3  xl/_rels/workbook.xml.rels
    4500  Defl:N      311  93% 2022-01-31 15:22 285db1ad  xl/printerSettings/printerSettings1.bin
     601  Defl:N      203  66% 2022-01-31 15:22 211e1d6e  xl/sharedStrings.xml
    1127  Defl:N      464  59% 2022-01-31 15:22 0d8ee71d  xl/styles.xml
    7075  Defl:N     1361  81% 2022-01-31 15:22 050f988c  xl/theme/theme1.xml
     950  Defl:N      382  60% 2022-01-31 15:22 1b8cce29  xl/workbook.xml
     612  Defl:N      223  64% 2022-01-31 15:22 f0584777  xl/worksheets/_rels/sheet1.xml.rels
   12729  Defl:N     2204  83% 2022-01-31 15:22 18057777  xl/worksheets/sheet1.xml

但文件仍然不同:

$ md5sum test1.xlsx test2.xlsx 
27783e8b19631039a1c940db214f25e1  test1.xlsx
ba0678946aea1e01093ce25130b2c467  test2.xlsx

由於 ZIP 元數據,使用exiftool可見:

$ exiftool test*.xlsx | grep Zip | grep Date
Zip Modify Date                 : 2022:01:31 15:22:52
Zip Modify Date                 : 2022:01:31 15:22:54

一種可能的解決方法是在openxlsx命名空間中重新定義genBaseCore function。

在下面的示例中, xlsx文件在Sys.time()前一天created

library(openxlsx)

replaceIllegalCharacters <- function(v){
  
  vEnc <- Encoding(v)
  v <- as.character(v)
  
  flg <- vEnc != "UTF-8"
  if(any(flg))
    v[flg] <- iconv(v[flg], from = "", to = "UTF-8")
  
  v <- gsub('&', "&amp;", v, fixed = TRUE)
  v <- gsub('"', "&quot;", v, fixed = TRUE)
  v <- gsub("'", "&apos;", v, fixed = TRUE)
  v <- gsub('<', "&lt;", v, fixed = TRUE)
  v <- gsub('>', "&gt;", v, fixed = TRUE)
  
  ## Escape sequences
  v <- gsub("\a", "", v, fixed = TRUE)
  v <- gsub("\b", "", v, fixed = TRUE)
  v <- gsub("\v", "", v, fixed = TRUE)
  v <- gsub("\f", "", v, fixed = TRUE)
  
  return(v)
}




genBaseCore <- function(creator = "", title = NULL, subject = NULL, category = NULL) {
  core <- '<coreProperties xmlns="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'
  
  core <- stringi:::stri_c(core, sprintf("<dc:creator>%s</dc:creator>", replaceIllegalCharacters(creator)))
  core <- stringi:::stri_c(core, sprintf("<cp:lastModifiedBy>%s</cp:lastModifiedBy>", replaceIllegalCharacters(creator)))

# Modify creation date here
  core <- stringi:::stri_c(core, sprintf('<dcterms:created xsi:type="dcterms:W3CDTF">%s</dcterms:created>', format(Sys.time()-86400, "%Y-%m-%dT%H:%M:%SZ")))
  
  if (!is.null(title)) {
    core <- stringi:::stri_c(core, sprintf("<dc:title>%s</dc:title>", replaceIllegalCharacters(title)))
  }
  
  if (!is.null(subject)) {
    core <- stringi:::stri_c(core, sprintf("<dc:subject>%s</dc:subject>", replaceIllegalCharacters(subject)))
  }
  
  if (!is.null(category)) {
    core <- stringi:::stri_c(core, sprintf("<cp:category>%s</cp:category>", replaceIllegalCharacters(category)))
  }
  
  core <- stringi:::stri_c(core, "</coreProperties>")
  
  return(core)
}

assignInNamespace("genBaseCore", genBaseCore, ns="openxlsx")

write.xlsx(mtcars, "test.xlsx")

您可以嘗試使用更簡單的包裝器來比較工作簿對象(假設您已閱讀上一個工作簿)並將其與當前工作簿進行比較。

library(openxlsx)
file1 <- temp_xlsx()
file2 <- temp_xlsx()
write.xlsx(mtcars, file1)
Sys.sleep(2)
write.xlsx(mtcars, file2)

wb1 <- loadWorkbook(file1)
wb2 <- loadWorkbook(file2)

all_equal_wb <- function(target, current) {
  exp <- "Workbook"
  attr(exp, "package") <- "openxlsx"
  stopifnot(identical(class(target), exp), identical(class(current), exp))
  target <- target$copy()
  current <- current$copy()
  target$core <- ""
  current$core <- ""
  # openxlsx::all.equal.Workbook
  all.equal(target, current)
}

all.equal(wb1, wb2)
#> [1] "Component \"core\": 1 string mismatch"
all_equal_wb(wb1, wb2)
#> [1] TRUE

代表 package (v2.0.1) 於 2022 年 1 月 31 日創建

openxlsx::all.equal.Workbook()沒有這種控制( ...被忽略),但可以添加。 package 仍在維護中,因此請隨時留下問題: https://github.com/ycphs/openxlsx/issues

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM