跳到主要内容

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

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

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

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

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

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

使用 Kutools for Excel 将每个工作表导出为 csv/text/pdf 到文件夹好主意3


要将文本文件从文件夹导入到工作簿中,可以使用VBA下面的命令对其进行快速处理。

1.启用空白工作簿,然后按 Alt + F11键 打开钥匙 Microsoft Visual Basic应用程序 窗口。

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,并在弹出对话框中选择要从中导入文本文件的文件夹。 看截图:

doc导入多个csv文本xml 1

4.然后点击 OK,并且所选文件夹中的每个文本文件都已导入到活动工作簿的一个工作表中。 看截图:

doc导入多个csv文本xml 2doc导入多个csv文本xml 3

轻松地将多个工作表/工作簿合并为一个工作表或工作簿

在Excel中,将多个工作表或工作簿组合成一个工作表或工作簿可能很麻烦,但是使用 结合 Kutools for Excel 中的功能,您可以将数十个工作表/工作簿合并为一张工作表或工作簿,也可以通过几次点击将工作表合并为一张。  点击获取全功能 30 天免费试用!
合并表
 
Kutools for Excel:拥有300多个便捷的Excel加载项,可以在30天内免费试用。

要将所有csv文件从一个文件夹导入到一张纸中,可以使用以下VBA代码。

1.启用空白工作表,然后按 Alt + F11键 打开钥匙 Microsoft Visual Basic应用程序 窗口。

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文件的文件夹。 看截图:

doc导入多个csv文本xml 4

4。 点击 OK,然后会弹出一个对话框,提醒您在导入之前是否清除了活动工作表的内容,请点击此处 USB MIDI(XNUMX通道)。 看截图:

doc导入多个csv文本xml 5

点击后 USB MIDI(XNUMX通道),所选文件夹中的所有csv文件都将导入到当前工作表中,并将数据从A列向右放置。 看截图:

doc导入多个csv文本xml 6doc导入多个csv文本xml 7

提示: 如果要将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 

doc导入多个csv文本xml 8


如果要将所有XML文件从一个文件夹导入到一张纸中,则可以使用以下VBA代码。

1.选择要放置导入数据的空白表,然后按 Alt + F11键 启用键 Microsoft Visual Basic应用程序 窗口。

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,然后在弹出对话框中选择一个文件夹,请参见屏幕截图:

doc导入多个csv文本xml 9

4。 点击 OK,并将所选文件夹中的所有XML文件导入到活动工作表中。


如果您不熟悉VBA,请放心,在这里,我介绍一个方便的工具– Kutools for Excel 为了你。 凭借其强大 结合 实用程序,您可以将多个xml文件或csv文件快速组合到一个工作簿或一个Excel工作表中。

Kutools for Excel, 与超过 300 方便的功能,使您的工作更加轻松。 

安装后 Kutools for Excel,请执行以下操作:(立即免费下载Kutools for Excel!)

1. Active Excel,然后单击 Kutools 加 > 结合。 查看截图:
doc合并1

2.然后 合并的第一步 对话框中,根据需要选择一个分离选项。 看截图:
doc合并2

3。 点击 下一页合并的第2步,单击“ 地址 将各种文件夹中的文件或一个文件夹中的文件添加到 工作簿 列表,还可以指定要从中合并的图纸 工作表 右侧部分列表。 看截图:
doc kutools结合床单3

4。 点击 下一页 到最后一步 结合,然后您可以指定合并选项。
doc kutools结合床单4

5。 点击 完成,会弹出一个对话框,提醒您选择一个位置来保存新的合并结果。 看截图:
doc合并5

6。 点击 保存。 所有添加的工作表都已合并为一个新的工作表。
doc合并6

提示: 结合,您也可以将多个 CSV文件 在一个工作表或工作簿中形成多个文件夹或一个文件夹。


如果要将每张工作表作为csv / text / pdf文件导出到文件夹, Kutools for Excel拆分工作簿 实用程序可以帮您一个忙。

免费安装 Kutools for Excel,请执行以下操作:

1.启用要导出其工作表的工作簿,然后单击 Kutools 加 > 工作簿 > 拆分工作簿。 看截图:

doc导入多个csv文本xml 10

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

doc导入多个csv文本xml 11

3。 点击 分裂 然后选择一个文件夹将拆分文件保存在 浏览文件夹 对话框,请参见屏幕截图:

doc导入多个csv文本xml 12

4。 点击 OK,现在所有选中的工作表都将作为新文件格式导出到所选文件夹中。


相关文章:

最佳办公生产力工具

🤖 Kutools 人工智能助手:基于以下内容彻底改变数据分析: 智能执行   |  生成代码  |  创建自定义公式  |  分析数据并生成图表  |  调用 Kutools 函数...
热门特色: 查找、突出显示或识别重复项   |  删除空白行   |  合并列或单元格而不丢失数据   |   不使用公式进行四舍五入 ...
超级查询: 多条件VLookup    多值VLookup  |   跨多个工作表的 VLookup   |   模糊查询 ....
高级下拉列表: 快速创建下拉列表   |  依赖下拉列表   |  多选下拉列表 ....
列管理器: 添加特定数量的列  |  移动列  |  切换隐藏列的可见性状态  |  比较范围和列 ...
特色功能: 网格焦点   |  设计图   |   大方程式酒吧    工作簿和工作表管理器   |  资源库 (自动文本)   |  日期选择器   |  合并工作表   |  加密/解密单元格    按列表发送电子邮件   |  超级筛选   |   特殊过滤器 (过滤粗体/斜体/删除线...)...
前 15 个工具集12 文本 工具 (添加文本, 删除字符,...)   |   50+ 图表 类型 (甘特图,...)   |   40+ 实用 公式 (根据生日计算年龄,...)   |   19 插入 工具 (插入二维码, 从路径插入图片,...)   |   12 转化 工具 (小写金额转大写, 货币兑换,...)   |   7 合并与拆分 工具 (高级组合行, 分裂细胞,...)   |   ... 和更多

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

产品描述


Office Tab 为 Office 带来选项卡式界面,让您的工作更加轻松

  • 在Word,Excel,PowerPoint中启用选项卡式编辑和阅读,发布者,Access,Visio和Project。
  • 在同一窗口的新选项卡中而不是在新窗口中打开并创建多个文档。
  • 每天将您的工作效率提高50%,并减少数百次鼠标单击!
Comments (36)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Bagaimana caranya menghilangkan header dari tiap-tiap file csv yang terbuka dalam worksheetnya
terima kasih
This comment was minimized by the moderator on the site
Hi there,this is a great tool, but I want to import the various XMl-Files into separate TAB-sheets. Is this possible as the XML's have different header ?
This comment was minimized by the moderator on the site
HelloThe instructions for importing multiple xmls into one tab of an excel document works but was wondering how to get it to line up the columns. My xmls don't all have the same tags. They are set up such that if the xml had no data for some headers(tags) then the header is missing from that xml. Is there a way to get the xmls to import so the same headers from each xml and associated data fall into the same column of excel?
This comment was minimized by the moderator on the site
Hi Experts

I am using the above code for importing multiple xml files into 1 worksheet using VBA however issue i am facing is when rows count reaches 650000 in a worksheet then this code doesn't process rest of the xml files in the folder. It gives an error "no files.xml". Require your kind support
This comment was minimized by the moderator on the site
Hi Team

I am using the code for importing Multiple XML files into single sheet with VBA however issue i am facing is when rows count reaches approximately 650000, then it doesn't processes rest of the xml files in the folder and gives an error that no xml files. Need your support to increase this count.
This comment was minimized by the moderator on the site
Hi, is there any way to import multiple csv files with semicolon as separator? Thank you!
PS Nice article!
This comment was minimized by the moderator on the site
Hello - I've used your VBA codes to extract data from multiple CSV files to excel file (the code on this page) and convert csv files to excel files ( this one: https://www.extendoffice.com/documents/excel/4615-excel-batch-convert-csv-to-xls-xlsx.html), with great results. They helped me save a lot of time.

However, I notice a common problem with both of these types of codes. To clarify, my system is set up to use the European standards for dates, while some of the CSV files I received for my work contain dates in US standards. The first problem is, when I extract or convert data from a CSV file that contains dates in US format, all of those dates are reversed (matching the EU standards used by my system). This is great but it also caused me troubles since I didn't know the codes would reverse the dates for me, so I went on ahead and did the same thing again. The second problem is, for the CSV files that contain dates already in the same format as the one used by my system (EU standards), only the ambiguous dates are reversed (i.e 04/05/2019 - 05/04/2019), while the ones that are too obvious, remain unchanged (i.e 30/04/2019).

What I would like the codes to do, is the exact same thing as they are shown here, only that they should copy and paste the data (especially dates) in the exact formats used in the original files. This would help prevent any possible confusions and mistakes. I would like to learn VBA so I can one day write my own codes, but for now, I'm not even able to modify parts of the existing codes to suit my needs. So if you can help, please tell me where I should put the modified codes (that you come up with) to the existing codes. I appreciate all feedback & support I can get. Thank you all!
This comment was minimized by the moderator on the site
Hi Marshall, in the Workbooks.Open method, add in the option Local:=True.

i.e.
Set xWb = Workbooks.Open(xStrPath & "\" & xFile, Local:=True)
This comment was minimized by the moderator on the site
Hi Robert,
It's me again. It took me a while to actually have the time to figure out which part of the code the "Local:True" part should be added to. The result turned out great as the dates are no longer reversed. Thank you!
For anyone having the same problem, just change this line:
Set xWb = Workbooks.OpenXML(xStrPath & "\" & xFile)

To this:
Set xWb = Workbooks.Open(xStrPath & "\" & xFile, Local:=True)
This comment was minimized by the moderator on the site
Thank you very much Robert. Sorry I couldn't reply to you any earlier. I didn't get any notification until now. I will try this out and come back to you later to let you know if this works.
This comment was minimized by the moderator on the site
Hi - I'm using the import all csv files into one file listed above "Import Multiple Csv Files From A Folder Into A Single Sheet With VBA"- i'd like to define the folder it collects the data from without having to manually choose it. Can this be done? thanks - SW.
This comment was minimized by the moderator on the site
Hi, Scott W, I found a VBA code may can help you.
Option Explicit

Sub ImportCSVsWithReference()
'Author: Jerry Beaucaire
'Date: 10/16/2010
'Summary: Import all CSV files from a folder into a single sheet
' adding a field in column A listing the CSV filenames

Dim wbCSV As Workbook
Dim wsMstr As Worksheet: Set wsMstr = ThisWorkbook.Sheets("Sheet1")
Dim fPath As String: fPath = " C:\Users\DT168\Desktop\New folder\" 'path to CSV files, include the final \
Dim fCSV As String

If MsgBox("Clear the existing sheet before importing?", vbYesNo, "Clear?") _
= vbYes Then wsMstr.UsedRange.Clear

Application.ScreenUpdating = False 'speed up macro

fCSV = Dir(fPath & "*.csv") 'start the CSV file listing

Do While Len(fCSV) > 0
'open a CSV file
Set wbCSV = Workbooks.Open(fPath & fCSV)
'insert col A and add CSV name
Columns(1).Insert xlShiftToRight
Columns(1).SpecialCells(xlBlanks).Value = ActiveSheet.Name
'copy date into master sheet and close source file
ActiveSheet.UsedRange.Copy wsMstr.Range("A" & Rows.Count).End(xlUp).Offset(1)
wbCSV.Close False
'ready next CSV
fCSV = Dir
Loop

Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
How to eliminate duplicate header and CSV file name column. Please do help....I have gone through several articles, but unfortunately all give same result.
This comment was minimized by the moderator on the site
Thank you. This site has been a big help. I have one issue I cannot figure out. I am trying to import multiple csv files into an excel separate sheets in excel and have each sheet renamed after the file name of the csv file. I know this was covered below for a txt file but I am working with csv files. Thanks in advance.
This comment was minimized by the moderator on the site
Hi! I used the code to merge multiple XML files into one, but unfortunately the columns got messed up. The 5 files being merged all had the same format. Is there anyway to fix this? I also was wondering if there was a way to get rid of the headers that are duplicated when the files are merged. Thank you!
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations