Skip to main content

如何在 Excel 中快速批量匯入多個 csv/文字/xml 文件?

Author: Sun Last Modified: 2025-05-12

在 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 個插入工具插入QR碼根據路徑插入圖片、...)   |   12 個轉換工具金額轉大寫匯率轉換、...)   |   7 個合併與分割工具高級合併行分割儲存格、...)   |   ... 還有更多

使用 Kutools for Excel 提升您的 Excel 技巧,體驗前所未有的高效。 Kutools for Excel 提供超過 300 種高級功能來提高生產力並節省時間。  點擊這裡獲取您最需要的功能...


Office Tab 將標籤式界面帶到 Office,讓您的工作更加輕鬆

  • 在 Word、Excel、PowerPoint、Publisher、Access、Visio 和 Project 中啟用標籤式編輯和閱讀。
  • 在同一窗口的新標籤中打開和創建多個文檔,而不是在新窗口中。
  • 將您的生產力提高 50%,每天為您減少數百次鼠標點擊!