【问题标题】:Merge .txt files in one .doc, adding file names and page breaks将 .txt 文件合并到一个 .doc 中,添加文件名和分页符
【发布时间】:2014-05-19 02:24:25
【问题描述】:

我在一个文件夹中有一堆不同名称的 .txt 文件,我需要将它们合并成一个可以在 Office Word 或 LibreOffice Writer 中读取的文件。

棘手的部分是,粘贴的文件应该按创建日期组织,在内容之前有一个标题,最后有一个分页符,像这样

Title of older file
File content
Page break

Title of newer file
File content
Page break

我可以用 Java 做到这一点,但这似乎有点矫枉过正。如果这可以使用 Windows Powershell 或 Unix bash 完成,那就太好了。不过,添加的换行符应该是 Window 样式。

完全免责声明:我对 Bash 有所了解,对 Powershell 知之甚少,对 .doc/.odf 格式几乎一无所知。

【问题讨论】:

    标签: bash file powershell text merge


    【解决方案1】:

    将 TXT 合并到一个 DOCX 并添加分页符(PowerShell,需要 MS Word):

    [Ref]$rSaveFormat = "Microsoft.Office.Interop.Word.WdSaveFormat" -as [Type]
    $oWord = New-Object -ComObject Word.Application
    $oWord.Visible = $false
    $sPath = <path to dir with txt files>
    $cInFiles = Get-ChildItem $sPath
    $sOutFile = $sPath + "\outfile.docx"
    $iWordPageBreak = 7
    $iNewLineChar = 11
    $oDoc = $oWord.Documents.Add()
    $oWordSel = $oWord.Selection
    
    foreach ($sInFile in $cInFiles) {
        $sInFileTxt = Get-Content $sInFile
    
        $oWordSel.TypeText($sInFile)
        $oWordSel.TypeText([Char]$iNewLineChar)
        $oWordSel.TypeText($sInFileTxt)
        $oWordSel.InsertBreak($iWordPageBreak)
    }
    
    $oDoc.SaveAs($sOutFile, $rSaveFormat::wdFormatDocumentDefault)
    $oDoc.Close()
    $oWord.Quit()
    $oWord = $null
    

    For explanations see this blog post on TechNet.

    编辑:如果没有 Word,您可能应该使用 ODT 格式并直接编辑 content.xml。 Example in Python。虽然我个人会简单地连接 TXT 文件。除非您有一百万个,否则手动添加分页符比实际编辑 XML 更快、更容易。

    【讨论】:

    • 我没有安装 MS Word,是否需要运行它?我设置了$sPath = "C:\Users\Agostino\Desktop\fld",将此脚本保存为.ps1 文件,然后以管理员身份打开PowerShell,运行命令Set-ExecutionPolicy unrestricted 并输入脚本名称来运行它。我遇到了很多错误,它似乎甚至在我给它的路径之外搜索。
    猜你喜欢
    • 2020-11-14
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    相关资源
    最近更新 更多