跳至主要内容

如何在Excel中快速批量导入多个csv/文本/xml文件?

Author: Sun Last Modified: 2025-05-07

在Excel中,您可能尝试过将工作簿另存为csv文件、文本文件或xml文件,但您是否尝试过从文件夹中将多个csv/文本/xml文件导入到一个工作簿或工作表中呢?本文将介绍一些方法来快速批量导入它们。


使用VBA将文件夹中的多个文本文件导入到工作簿的每个工作表中

要从文件夹导入文本文件到工作簿,您可以使用以下VBA代码快速处理它。

1. 打开一个空白工作簿,并按 Alt + F11 键打开 Microsoft Visual Basic for Applications 窗口。

2. 单击 插入 > 模块,并将VBA粘贴到模块窗口中。

VBA:从文件夹导入所有文本文件到工作簿

Sub LoadPipeDelimitedFiles()
'UpdatebyKutoolsforExcel20151214
    Dim xStrPath As String
    Dim xFileDialog As FileDialog
    Dim xFile As String
    Dim xCount As Long
    On Error GoTo ErrHandler
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a folder [Kutools for Excel]"
    If xFileDialog.Show = -1 Then
        xStrPath = xFileDialog.SelectedItems(1)
    End If
    If xStrPath = "" Then Exit Sub
    Application.ScreenUpdating = False
    xFile = Dir(xStrPath & "\*.txt")
    Do While xFile <> ""
        xCount = xCount + 1
        Sheets(xCount).Select
        With ActiveSheet.QueryTables.Add(Connection:="TEXT;" _
          & xStrPath & "\" & xFile, Destination:=Range("A1"))
            .Name = "a" & xCount
            .FieldNames = True
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .RefreshStyle = xlInsertDeleteCells
            .SavePassword = False
            .SaveData = True
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .TextFilePromptOnRefresh = False
            .TextFilePlatform = 437
            .TextFileStartRow = 1
            .TextFileParseType = xlDelimited
            .TextFileTextQualifier = xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = False
            .TextFileTabDelimiter = False
            .TextFileSemicolonDelimiter = False
            .TextFileCommaDelimiter = False
            .TextFileSpaceDelimiter = False
            .TextFileOtherDelimiter = "|"
            .TextFileColumnDataTypes = Array(1, 1, 1)
            .TextFileTrailingMinusNumbers = True
            .Refresh BackgroundQuery:=False
            xFile = Dir
        End With
    Loop
    Application.ScreenUpdating = True
    Exit Sub
ErrHandler:
    MsgBox "no files txt", , "Kutools for Excel"
End Sub

3. 按 F5 键或单击“ 运行”按钮来运行VBA,并在弹出的对话框中选择要从中导入文本文件的文件夹。参见截图:

a screenshot of seleting a folder from which you want to import txt files

4. 单击“ 确定”,所选文件夹中的每个文本文件都已导入到当前工作簿的一个工作表中。参见截图:

a screenshot showing that each text file in the selected folder has been imported into different worksheets of the current workbooka screenshot showing that each text file in the selected folder has been imported into different worksheets of the current workbook 2
a screenshot of kutools for excel ai

使用 Kutools AI 解锁 Excel 魔法

  • 智能执行:执行单元格操作、分析数据和创建图表——所有这些都由简单命令驱动。
  • 自定义公式:生成量身定制的公式,优化您的工作流程。
  • VBA 编码:轻松编写和实现 VBA 代码。
  • 公式解释:轻松理解复杂公式。
  • 文本翻译:打破电子表格中的语言障碍。
通过人工智能驱动的工具增强您的 Excel 能力。立即下载,体验前所未有的高效!

使用VBA将文件夹中的多个csv文件导入到单个工作表中

要将文件夹中的所有csv文件导入到单个工作表中,可以使用以下VBA代码。

1. 打开一个空白工作表,并按 Alt + F11 键打开 Microsoft Visual Basic for Applications 窗口。

2. 单击 插入 > 模块,并将以下VBA粘贴到新的 模块窗口中。

VBA:从文件夹导入csv文件到一个工作表中

Sub ImportCSVsWithReference()
'UpdatebyKutoolsforExcel20151214
    Dim xSht  As Worksheet
    Dim xWb As Workbook
    Dim xStrPath As String
    Dim xFileDialog As FileDialog
    Dim xFile As String
    On Error GoTo ErrHandler
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a folder [Kutools for Excel]"
    If xFileDialog.Show = -1 Then
        xStrPath = xFileDialog.SelectedItems(1)
    End If
    If xStrPath = "" Then Exit Sub
    Set xSht = ThisWorkbook.ActiveSheet
    If MsgBox("Clear the existing sheet before importing?", vbYesNo, "Kutools for Excel") = vbYes Then xSht.UsedRange.Clear
    Application.ScreenUpdating = False
    xFile = Dir(xStrPath & "\" & "*.csv")
    Do While xFile <> ""
        Set xWb = Workbooks.Open(xStrPath & "\" & xFile)
        Columns(1).Insert xlShiftToRight
        Columns(1).SpecialCells(xlBlanks).Value = ActiveSheet.Name
        ActiveSheet.UsedRange.Copy xSht.Range("A" & Rows.Count).End(xlUp).Offset(1)
        xWb.Close False
        xFile = Dir
    Loop
    Application.ScreenUpdating = True
    Exit Sub
ErrHandler:
    MsgBox "no files csv", , "Kutools for Excel"
End Sub

3. 按 F5 键或单击“运行”按钮执行VBA,并弹出一个对话框以选择要从中导入所有csv文件的文件夹。参见截图:

a screenshot of seleting a folder from which you want to import csv files into a single worksheet

4. 单击“确定”,并弹出一个对话框提醒您是否在导入前清除活动工作表的内容,这里我单击 “是”。参见截图:

a screenshot of a prompt box reminding that whether you want to clear the existing sheet before importing csv files

单击“”后,所选文件夹中的所有csv文件都被导入到当前工作表中,并将数据从A列开始向右放置。参见截图:

a screenshot showing that all csv files in the selcted folder are imported into the current worksheeta screenshot showing that all csv files in the selcted folder are imported into the current worksheet 2

提示:如果您想将csv文件水平放置在工作表中,可以使用以下VBA代码。

Sub ImportCSVsWithReferenceI()
'UpdatebyKutoolsforExcel20151214
    Dim xSht  As Worksheet
    Dim xWb As Workbook
    Dim xStrPath As String
    Dim xFileDialog As FileDialog
    Dim xFile As String
    Dim xCount As Long
    On Error GoTo ErrHandler
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a folder [Kutools for Excel]"
    If xFileDialog.Show = -1 Then
        xStrPath = xFileDialog.SelectedItems(1)
    End If
    If xStrPath = "" Then Exit Sub
    Set xSht = ThisWorkbook.ActiveSheet
    If MsgBox("Clear the existing sheet before importing?", vbYesNo, "Kutools for Excel") = vbYes Then
        xSht.UsedRange.Clear
        xCount = 1
    Else
        xCount = xSht.Cells(3, Columns.Count).End(xlToLeft).Column + 1
    End If
    Application.ScreenUpdating = False
    xFile = Dir(xStrPath & "\" & "*.csv")
    Do While xFile <> ""
        Set xWb = Workbooks.Open(xStrPath & "\" & xFile)
        Rows(1).Insert xlShiftDown
        Range("A1") = ActiveSheet.Name
        ActiveSheet.UsedRange.Copy xSht.Cells(1, xCount)
        xWb.Close False
        xFile = Dir
        xCount = xSht.Cells(3, Columns.Count).End(xlToLeft).Column + 1
    Loop
    Application.ScreenUpdating = True
    Exit Sub
ErrHandler:
    MsgBox "no files csv", , "Kutools for Excel"
End Sub 

a screenshot of importing csv files horizontally in a worksheet


使用VBA将文件夹中的多个xml文件导入到单个工作表中

如果要将文件夹中的所有XML文件导入到单个工作表中,可以使用以下VBA代码。

1. 选择一个空白工作表以放置导入的数据,并按 Alt + F11 键启用 Microsoft Visual Basic for Applications 窗口。

2. 单击 插入 > 模块,将VBA代码粘贴到模块窗口中。

VBA:从文件夹导入XML文件到工作表中。

Sub From_XML_To_XL()
'UpdatebyKutoolsforExcel20151214
    Dim xWb As Workbook
    Dim xSWb As Workbook
    Dim xStrPath As String
    Dim xFileDialog As FileDialog
    Dim xFile As String
    Dim xCount As Long
    On Error GoTo ErrHandler
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a folder [Kutools for Excel]"
    If xFileDialog.Show = -1 Then
        xStrPath = xFileDialog.SelectedItems(1)
    End If
    If xStrPath = "" Then Exit Sub
    Application.ScreenUpdating = False
    Set xSWb = ThisWorkbook
    xCount = 1
    xFile = Dir(xStrPath & "\*.xml")
    Do While xFile <> ""
        Set xWb = Workbooks.OpenXML(xStrPath & "\" & xFile)
        xWb.Sheets(1).UsedRange.Copy xSWb.Sheets(1).Cells(xCount, 1)
        xWb.Close False
        xCount = xSWb.Sheets(1).UsedRange.Rows.Count + 2
        xFile = Dir()
    Loop
    Application.ScreenUpdating = True
    xSWb.Save
    Exit Sub
ErrHandler:
    MsgBox "no files xml", , "Kutools for Excel"
End Sub

3. 单击“运行”按钮或按F5键运行VBA,并在弹出的对话框中选择一个文件夹,参见截图:

a screenshot of seleting a folder from which you want to import xml files into a single worksheet

4. 单击“确定”,所选文件夹中的所有XML文件都被导入到活动工作表中。


使用Kutools for Excel将多个xml/csv文件导入或合并到工作表或工作簿中

如果您不熟悉VBA,不用担心,这里我为您介绍一个实用工具——Kutools for Excel。通过其强大的合并功能,您可以快速将多个xml文件或csv文件合并到一个工作簿或一个Excel工作表中。

安装Kutools for Excel后,请按照以下步骤操作:(立即免费下载Kutools for Excel!)

1. 启动Excel,并单击 Kutools Plus > 合并。参见截图:
a screenshot of enabling the Combine feature of Kutools for Excel

2. 在 合并的第一步 对话框中,根据需要选择一个分隔选项。参见截图:
a screenshot of selecting one operation as you need in the Combine Worksheets wizard

3. 单击 下一步 进入 合并的第二步,单击 添加 以从不同文件夹或一个文件夹中添加文件到 工作簿 列表中,并且您还可以从右侧部分的 工作表 列表中指定要合并的工作表。参见截图:
a screenshot of adding files or folders and specifying the sheets you want to combine

4. 单击 下一步 进入最后一步 合并,您可以指定合并选项。
a screenshot of specifying the combine options

5. 单击 完成,弹出一个对话框提醒您选择保存新合并结果的位置。参见截图:
a screenshot of selecting a location to save the new combined file

6. 单击 保存。所有添加的工作表都已合并到一个新的单一工作表中。
a screenshot showing all adding sheets have been combined into a new single worksheet

提示:使用合并功能,您还可以将来自多个文件夹或一个文件夹的多个CSV文件合并到一个工作表或工作簿中。


使用Kutools for Excel将每个工作表导出为csv/文本/pdf到文件夹中

如果您希望将每个工作表导出为csv/文本/pdf文件到文件夹中,Kutools for Excel分割工作簿功能可以为您提供帮助。

免费下载并安装 Kutools for Excel 后,请按照以下步骤操作:

1. 启用要导出其工作表的工作簿,并单击 Kutools Plus > 工作簿 > 分割工作簿。参见截图:

a screenshot of enabling the Split Workbook feature

2. 在 分割工作簿对话框中,您可以勾选需要导出的工作表名称,默认情况下所有工作表都已勾选,并勾选指定保存格式,然后从下拉列表中选择要保存为的文件格式。参见截图:

a screenshot of checking the sheet names you will export and specifying a save format

3. 单击“分割”并在“浏览文件夹”对话框中选择一个文件夹以保存分割后的文件,参见截图:

a screenshot of selecting a destination folder to save the exported files

4. 单击“确定”,现在所有被勾选的工作表都作为新文件格式导出到选定的文件夹中。


相关文章:


最佳办公效率工具

🤖 Kutools AI 助手:基于智能执行生成代码创建自定义公式分析数据并生成图表调用 Kutools 函数等功能,彻底改变数据分析方式…
热门功能查找、高亮或标记重复项 | 删除空行 | 合并不丢失数据的列或单元格 | 四舍五入 ...
高级 LOOKUP多条件 VLookup | 多值 VLookup | 多表查找 | 模糊查找 ....
高级下拉列表快速创建下拉列表 | 从属下拉列表 | 多选下拉列表 ....
列管理器添加指定数量的列 | 移动列 | 切换隐藏列的可见状态 | 比较区域和列 ...
精选功能网格聚焦 | 设计视图 | 增强编辑栏 | 工作簿与工作表管理器 | 资源库(自动文本) | 日期提取 | 合并数据 | 加密/解密单元格 | 按列表发送电子邮件 | 超级筛选 | 特殊筛选(筛选粗体/斜体/删除线...)...
排名前 15 的工具集12 种文本 工具添加文本删除特定字符等) | 50 多 种图表 类型甘特图等) | 40 多种实用 公式基于生日计算年龄等) | 19 种插入 工具插入二维码根据路径插入图片等) | 12 种转换 工具小写金额转大写汇率转换等) | 7 种合并与分割 工具高级合并行分割单元格等) | 还有更多...

使用 Kutools for Excel 提升您的 Excel 技能,体验前所未有的高效。 Kutools for Excel 提供超过 300 种高级功能来提高生产力并节省时间。 单击此处获取您最需要的功能...


Office Tab 将标签式界面引入 Office,让您的工作更加轻松

  • 在 Word、Excel、PowerPoint 中启用标签式编辑和阅读
  • 在同一窗口的新标签页中打开和创建多个文档,而不是在新窗口中进行操作。
  • 将您的生产力提升 50%,每天为您减少数百次鼠标点击!