VBA将PDF文档内容逐行写入Excel

VBA是无法直接读取PDF文档的,但结合上期我给大家介绍了PDF转换工具xpdf-tools-4.05,先利用它将PDF文档转换为TXT文档,然后再将TXT的内容写入Excel,这样就间接实现了将PDF文档的内容导入Excel的操作。下面的代码将向大家演示如何实现这一操作:

复制代码
Sub Import_PDF_File()
'
' 导入PDF文档
'
    Dim pdftotext As String
    pdftotext = "C:\Program Files (x86)\xpdf-tools\bin32\pdftotext.exe"
    
    Dim fd As fileDialog
    Dim filePath As String
    
    ' 文件选择对话框
    Set fd = Application.fileDialog(msoFileDialogFilePicker)
    With fd
        .Title = "选择PDF文件"
        .InitialFileName = UserDirectory  ' 设置默认路径
        .Filters.Clear
        .Filters.Add "PDF文件", "*.pdf"
        .AllowMultiSelect = False
        If .Show <> -1 Then Exit Sub
        filePath = .SelectedItems(1)
    End With
    
    Cells.ClearContents    ' 清除所有数据
    
    Application.ScreenUpdating = False    ' 禁用屏幕更新
    
    Dim InputFile As String, OutputFile As String
    InputFile = filePath
    OutputFile = Left(filePath, Len(filePath) - 4) & ".txt"

    ' 转换PDF为TXT文档
    Dim shellCommand As String
    shellCommand = pdftotext & " -layout -enc UTF-8 """ & InputFile & """ """ & OutputFile & """"
    Shell shellCommand, vbHide

    ' 等待转换完成
    Application.Wait Now + TimeValue("00:00:02")
    
    Dim txtPath As String
    txtPath = OutputFile

    If UTF8TOANSI(txtPath) = False Then MsgBox "转换ANSI编码失败" & txtPath, vbCritical, "错误"

    Dim TxtPathANSI As String
    TxtPathANSI = Left(txtPath, Len(txtPath) - 4) & "_ANSI.txt"

    ' 读取文本文件
    Dim i As Long
    Dim Line As String
    Dim LineNum As Long
    Dim symbols As String
    Open TxtPathANSI For Input As #1
        i = 0
        Do While Not EOF(1)
            Line Input #1, Line
            i = i + 1
            Cells(i, 1).Value = Line
            LineNum = i
        Loop
    Close #1

    ' 删除临时文件
    Kill txtPath
    Kill TxtPathANSI

    Columns("A:A").Select
    With Selection
        .HorizontalAlignment = xlLeft   ' 左对齐
    End With
    Range("A1").Select
    
    Application.ScreenUpdating = True    ' 启用屏幕更新
    
    MsgBox "成功导入 " & LineNum & " 行数据。", vbInformation, "提示"

End Sub

该操作只适合文字版的PDF,不适合图片版的PDF,也就是说如果你的PDF是使用扫描仪生成的那该方法不适合。另外,导入txt文档需要使用UTF8TOANSI函数将UTF8编码转换为ANSI编码,否则可能导入的是乱码,关于该函数的使用方法详见《 VBA转换TXT文档编码(UTF-8转换为ANSI)》

相关推荐
软件资深者7 小时前
全能图片缩略图显示工具,体积较大,直接显示AI,PSD,EPS,PDF,INDD,TIFF,CR2,RAW等格式缩略图的图像解码包
windows·microsoft·pdf·windows11·系统修复
DS随心转小程序12 小时前
AI公式不乱码
人工智能·pdf·deepseek·ds随心转
luyun02020212 小时前
PDF神仙工具,批量处理
windows·pdf·figma
s石有八九13 小时前
PDF/文档LLM作业批改:2025年研究现状、技术进展与研究空白
人工智能·python·pdf·教育·ai教育·作业批改
开开心心_Every14 小时前
PDF转图片工具推荐:免费支持批量转换
linux·运维·服务器·spring boot·edge·pdf·powerpoint
ElasticPDF-新国产PDF编辑器16 小时前
基于 PDF.js 的 PDF 文字编辑解决方案,纯前端 SDK,跨平台、框架无关、Web 原生
前端·javascript·pdf
南风微微吹18 小时前
【2026年大英赛】全国大学生英语竞赛ABCD类历年真题及答案解析PDF电子版(2012-2025年)
pdf·大英赛
x***r15118 小时前
MasterPDFportable使用步骤详解(附PDF编辑与合并教程)
pdf
10km1 天前
MCP:Trace IDE 正确配置 PDF 读取 MCP 的完整指南
ide·pdf·mcp·trae
开开心心_Every2 天前
A3试卷分割工具:免费转为A4格式可离线
游戏·随机森林·微信·pdf·excel·语音识别·最小二乘法