首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将递归命名应用于拆分文档(例如,DreamFile01.docx、Dream_File02.docx等)

如何将递归命名应用于拆分文档(例如,DreamFile01.docx、Dream_File02.docx等)
EN

Stack Overflow用户
提问于 2019-02-24 02:02:38
回答 1查看 56关注 0票数 0

我有一个脚本,拆分成单独的word文档的word文档。每个拆分文档为1页。

需要做什么修改,才能让每个拆分的文档递归命名为Dream_File01.docx、Dream_File02.docx、Dream_File03.docx、Dream_File04.docx、Dream_File05.docx、Dream_File06.docx等。

代码语言:javascript
复制
## -- Settings --
#$fileNamePattern = "ID #:\s+(\d+)"
$fileNamePattern = "Student ID #:\s+# (\d+)"
$pageLength = 1

$inputFile = "Dream_File.docx"
$outputPath = "outputDir\" #End the path with a slash

## -- End Settings


[ref]$SaveFormat = "microsoft.office.interop.word.WdSaveFormat" -as [type] 
$word = New-Object -ComObject word.application
$word.Visible = $true

$doc = $word.Documents.Open($inputFile)
$pages = $doc.ComputeStatistics([Microsoft.Office.Interop.Word.WdStatistic]::wdStatisticPages)

$rngPage = $doc.Range()

for($i=1;$i -le $pages; $i+=$pageLength)
{
    [Void]$word.Selection.GoTo([Microsoft.Office.Interop.Word.WdGoToItem]::wdGoToPage,
                         [Microsoft.Office.Interop.Word.WdGoToDirection]::wdGoToAbsolute,
                         $i #Starting Page
                         )
        $rngPage.Start = $word.Selection.Start

    [Void]$word.Selection.GoTo([Microsoft.Office.Interop.Word.WdGoToItem]::wdGoToPage,
                         [Microsoft.Office.Interop.Word.WdGoToDirection]::wdGoToAbsolute,
                         $i+$pageLength #Next page Number
                         )
    $rngPage.End = $word.Selection.Start

    $marginTop = $word.Selection.PageSetup.TopMargin
    $marginBottom = $word.Selection.PageSetup.BottomMargin
    $marginLeft = $word.Selection.PageSetup.LeftMargin
    $marginRight = $word.Selection.PageSetup.RightMargin



    $rngPage.Copy()
    $newDoc = $word.Documents.Add()

    $word.Selection.PageSetup.TopMargin = $marginTop 
    $word.Selection.PageSetup.BottomMargin = $marginBottom
    $word.Selection.PageSetup.LeftMargin = $marginLeft
    $word.Selection.PageSetup.RightMargin = $marginRight

    $word.Selection.Paste() # Now we have our new page on a new doc
    $word.Selection.EndKey(6,0) #Move to the end of the file
    $word.Selection.TypeBackspace() #Seems to grab an extra section/page break
    $word.Selection.Delete() #Now we have our doc down to size

    #Get Name
    $regex = [Regex]::Match($rngPage.Text, $fileNamePattern)
    if($regex.Success)
    {
        $id = $regex.Groups[1].Value
    }
    else
    {
        $id = "patternNotFound_" + $i 
    }

    $path = $outputPath + $id + ".docx"
    $newDoc.saveas([ref] $path, [ref]$SaveFormat::wdFormatDocumentDefault) 
    $newDoc.close() 

    Remove-Variable(regex)
    Remove-Variable(id) 

}


[gc]::collect() 
[gc]::WaitForPendingFinalizers()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-24 22:25:13

如果您想要的输出是一系列名为Dream_File_01.docxDream_File_02.docx等的Word文档,那么我不能完全理解您为什么要使用正则表达式来获取StudentID

正如Lee_Dailey已经注释的那样,顺序命名所需的页面计数器已经存在于$i变量中。

不管怎样,这是我对你的脚本的修改。请阅读我放在那里的评论,这样你就可以选择是否使用StudentID

代码语言:javascript
复制
## -- Settings --
#$fileNamePattern = "ID #:\s+(\d+)"
$fileNamePattern = "Student ID #:\s+# (\d+)"
$pageLength = 1

$inputFile  = "Dream_File.docx"
$outputPath = "outputDir" # Use Join-Path so don't worry about it not ending with a backslash.

## -- End Settings

[ref]$SaveFormat = "Microsoft.Office.Interop.Word.WdSaveFormat" -as [type] 
$word = New-Object -ComObject Word.Application
$word.Visible = $true

$doc     = $word.Documents.Open($inputFile)
$pages   = $doc.ComputeStatistics([Microsoft.Office.Interop.Word.WdStatistic]::wdStatisticPages)
$rngPage = $doc.Range()

for($i = 1; $i -le $pages; $i += $pageLength) {
    [void]$word.Selection.GoTo([Microsoft.Office.Interop.Word.WdGoToItem]::wdGoToPage,
                         [Microsoft.Office.Interop.Word.WdGoToDirection]::wdGoToAbsolute,
                         $i #Starting Page
                         )
    $rngPage.Start = $word.Selection.Start

    [void]$word.Selection.GoTo([Microsoft.Office.Interop.Word.WdGoToItem]::wdGoToPage,
                         [Microsoft.Office.Interop.Word.WdGoToDirection]::wdGoToAbsolute,
                         $i+$pageLength #Next page Number
                         )
    $rngPage.End = $word.Selection.Start

    $marginTop    = $word.Selection.PageSetup.TopMargin
    $marginBottom = $word.Selection.PageSetup.BottomMargin
    $marginLeft   = $word.Selection.PageSetup.LeftMargin
    $marginRight  = $word.Selection.PageSetup.RightMargin

    $rngPage.Copy()
    $newDoc = $word.Documents.Add()

    $word.Selection.PageSetup.TopMargin    = $marginTop 
    $word.Selection.PageSetup.BottomMargin = $marginBottom
    $word.Selection.PageSetup.LeftMargin   = $marginLeft
    $word.Selection.PageSetup.RightMargin  = $marginRight

    $word.Selection.Paste()         # Now we have our new page on a new doc
    $word.Selection.EndKey(6,0)     # Move to the end of the file
    $word.Selection.TypeBackspace() # Seems to grab an extra section/page break
    $word.Selection.Delete()        # Now we have our doc down to size

    # This part I don't fully understand..
    # Why do you want to get the Student ID number here? Should that be part of the filename?
    # Can you be sure that on every page this number can be found? 
    $regex = [Regex]::Match($rngPage.Text, $fileNamePattern)
    if($regex.Success) {
        # Get the filename without extension from the $inputFile string and append the student ID, the pagecounter '$i' and '.docx' extension to it
        $newFileName = '{0}_{1}_{2:00}.docx' -f [System.IO.Path]::GetFileNameWithoutExtension($inputFile), $regex.Groups[1].Value, $i
    }
    else {
        # Get the filename without extension from the $inputFile string and append 'patternNotFound', the pagecounter '$i' and '.docx' extension to it
        $newFileName = '{0}_patternNotFound_{1:00}.docx' -f [System.IO.Path]::GetFileNameWithoutExtension($inputFile), $i
    }

    # If the Student ID is not needed in the filename, use this instead:
    # Get the filename without extension from the $inputFile string and append the pagecounter '$i' and '.docx' extension to it
    # $newFileName = '{0}_{1:00}.docx' -f [System.IO.Path]::GetFileNameWithoutExtension($inputFile), $i

    # next combine the output path with the new filename for Save()
    $path = Join-Path -Path $outputPath -ChildPath $newFileName

    $newDoc.SaveAs([ref] $path, [ref]$SaveFormat::wdFormatDocumentDefault) 
    $newDoc.Close() 
}

# you're done, exit Word and clean up the Com object
$word.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null 
[System.GC]::Collect() 
[System.GC]::WaitForPendingFinalizers()

希望这能有所帮助

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54844481

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档