如何批量将.doc/.docx文件转为.txt格式以便导入Excel
批量Word转文本/导入Excel解决方案
导出txt空白的核心原因
你之前使用的脚本没有正确配置Word COM对象的安全参数、另存为编码设置,导致导出的文本为空。手动操作时默认选择的Windows(默认)编码、自动跳过受保护视图的逻辑在旧脚本里没有复现,就会出现导出文件空白的问题。
方案1:VBA批量转换(无需编程基础,按步骤操作即可)
操作步骤:
- 打开任意空白Word文档,按
Alt + F11调出VBA编辑器 - 左侧工程栏右键点击当前文档,选择【插入】>【模块】
- 把下方代码粘贴到右侧编辑区,修改代码里的
源文件夹路径和导出txt文件夹路径为你自己的本地路径 - 按
F5运行,等待执行完成即可
代码:
Sub 批量Word转TXT() Dim sourceFolder As String, outputFolder As String Dim wordFile As String Dim doc As Document ' 此处修改为你的Word文件所在文件夹 sourceFolder = "C:\你的Word文件所在文件夹\" ' 此处修改为你要保存TXT的文件夹 outputFolder = "C:\导出TXT的保存文件夹\" ' 关闭屏幕更新和警告弹窗 Application.ScreenUpdating = False Application.DisplayAlerts = wdAlertsNone ' 遍历所有doc和docx文件 wordFile = Dir(sourceFolder & "*.doc*") Do While wordFile <> "" Set doc = Documents.Open(FileName:=sourceFolder & wordFile, _ ReadOnly:=True, AddToRecentFiles:=False, Visible:=False) ' 另存为txt,编码为Windows默认 doc.SaveAs2 FileName:=outputFolder & Replace(wordFile, ".doc", ".txt"), _ FileFormat:=wdFormatText, Encoding:=msoEncodingDefault doc.Close SaveChanges:=wdDoNotSaveChanges wordFile = Dir Loop ' 恢复设置 Application.ScreenUpdating = True Application.DisplayAlerts = wdAlertsAll MsgBox "转换完成!" End Sub
方案2:PowerShell批量转换
操作步骤:
- 新建文本文档,把下方代码粘贴进去,修改
$sourcePath和$outputPath为你的本地路径 - 保存后修改后缀为
.ps1,右键选择【使用PowerShell运行】即可
代码:
$sourcePath = "C:\你的Word文件所在文件夹" $outputPath = "C:\导出TXT的保存文件夹" # 初始化Word对象 $word = New-Object -ComObject Word.Application $word.Visible = $false $word.DisplayAlerts = 0 # 遍历所有Word文件 Get-ChildItem -Path $sourcePath -Include *.doc,*.docx -Recurse | ForEach-Object { $doc = $word.Documents.Open($_.FullName, $false, $true) $txtName = $outputPath + "\" + $_.BaseName + ".txt" # 保存为Windows默认编码的TXT $doc.SaveAs2([ref]$txtName, [ref]2, [ref]$false, [ref]$null, [ref]$false, [ref]$null, [ref]$false, [ref]$false, [ref]$false, [ref]$false, [ref]$false, [ref]0) $doc.Close() } $word.Quit() [System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null Write-Host "转换完成!"
可选优化:直接提取内容到Excel
如果不需要中间TXT文件,可以直接调整上述代码,把提取到的Word文本直接写入Excel工作表,省掉中间转换步骤,避免二次处理。
内容的提问来源于stack exchange,提问作者user16766172
相关产品推荐
相关产品推荐

