用 vscode + pandoc 將大量 .md 轉換為 .docx

Phanix
·
(修改过)
·
IPFS
·
因為公司改換用 microsoft 365 solution, 所以要把原本付費的 notion 停掉,改成用 sharepoint

# 從Notion備份

Notion頁面左上角可以找到匯出(export)的功能,如果該頁面有很多字頁面的話,會產生一大包 zip 檔案。我這邊是選擇匯出 markdown 格式,所以在轉入 sharepoint 時就會有轉換檔案格式的問題要處理。

# 轉換為 Word .docx 格式

Microsoft 365 生態系內,在 Sharepoint 內使用時,用 word 格式會是最方便的,其他檔案格式會很難做後續編輯。將 md 檔案轉換為 word 格式時,最好的方法是透過 vscode 當中的 pandoc extension。

不過當有很多 md 檔案,且有很多層的子目錄時,慢慢用 pandoc 轉換就很痛苦,所以可以用 powershell script 的方始解決。

# powershell
# 取得所有 md 檔案
$mdFiles = Get-ChildItem -Recurse -Filter "*.md"
$totalFiles = $mdFiles.Count
$currentFile = 0
Write-Host "找到 $totalFiles 個 Markdown 檔案,開始轉換..." -ForegroundColor Yellow
foreach ($file in $mdFiles) {
    $currentFile++
    $inputPath = $file.FullName

    # 移除 hash 亂數
    # matching:空格 + 32 個十六進制字符 + .md 結尾
    $baseNameWithoutHash = $file.BaseName -replace ' [0-9a-f]{32}$', ''
    $outputPath = Join-Path $file.DirectoryName ($baseNameWithoutHash + ".docx")
    Write-Progress -Activity "轉換 Markdown 檔案" -Status "處理: $($file.Name) → $baseNameWithoutHash.docx" -PercentComplete (($currentFile / $totalFiles) * 100)

    try {
        pandoc $inputPath -o $outputPath
        Write-Host "[$currentFile/$totalFiles] ✓ $($file.Name) → $baseNameWithoutHash.docx" -ForegroundColor Green
    } catch {
        Write-Host "[$currentFile/$totalFiles] ✗ $($file.Name) - $($_.Exception.Message)" -ForegroundColor Red
    }
}
Write-Progress -Activity "轉換完成" -Completed
Write-Host "所有檔案轉換完成!" -ForegroundColor Green
CC BY-NC-ND 4.0 授权

喜欢我的作品吗?别忘了给予支持与赞赏,让我知道在创作的路上有你陪伴,一起延续这份热忱!