davidgohel / officer

:cop: officer: office documents from R
https://ardata-fr.github.io/officeverse/
Other
594 stars 107 forks source link

[Feature request] Ability to close a specific open word document from R #617

Open kendonB opened 2 days ago

kendonB commented 2 days ago

A common development flow for tables is to look at the final product in Word, then iterate the code. An annoying thing about this process is having to manually close the open document before saving. browseURL() can automatically open a file, but we have no way to automatically close a file. o1-preview offered this solution for Windows which may provide some inspiration:

# Replace with the name of your Word document
docName <- "YourDocumentName.docx"

# Create the PowerShell script as a string
psScript <- sprintf('
$word = [Runtime.InteropServices.Marshal]::GetActiveObject("Word.Application")
foreach ($doc in $word.Documents) {
    if ($doc.Name -eq "%s") {
        $doc.Close()
    }
}
', docName)

# Write the PowerShell script to a temporary file
psFile <- tempfile(fileext = ".ps1")
writeLines(psScript, psFile)

# Execute the PowerShell script
system2("powershell", args = c("-ExecutionPolicy", "Bypass", "-File", psFile))

# Optionally, delete the temporary PowerShell script file
file.remove(psFile)
davidgohel commented 2 days ago

This would be more for package doconv

However while iterating on a document I prefer to use tempfile so that there is no clash with edited documents