Bỏ qua nội dung chính

Làm cách nào để nhanh chóng nhập hàng loạt nhiều tệp csv / text / xml trong Excel?

Trong Excel, bạn có thể buộc phải lưu sổ làm việc dưới dạng tệp csv, tệp văn bản hoặc tệp xml, nhưng bạn đã bao giờ cố gắng nhập nhiều tệp csv / text / xml từ một thư mục vào sổ làm việc hoặc trang tính chưa? Trong bài viết này, tôi giới thiệu một số phương pháp để nhập hàng loạt chúng một cách nhanh chóng.

Nhập nhiều tệp văn bản từ một thư mục vào từng trang tính của sổ làm việc với VBA

Nhập nhiều tệp csv từ một thư mục vào một trang tính duy nhất bằng VBA

Nhập nhiều tệp xml từ một thư mục vào một trang tính bằng VBA

Nhập hoặc kết hợp nhiều tệp xml / csv vào một trang tính hoặc một sổ làm việc với Kutools cho Excel ý kiến ​​hay3

Xuất từng trang tính dưới dạng csv / text / pdf sang một thư mục với Kutools cho Excelý kiến ​​hay3


Để nhập tệp văn bản từ một thư mục vào sổ làm việc, bạn có thể sử dụng VBA bên dưới để nhanh chóng xử lý nó.

1. Bật một sổ làm việc trống và nhấn Alt + F11 chìa khóa để mở Microsoft Visual Basic cho các ứng dụng cửa sổ.

2. nhấp chuột Chèn > Mô-đunvà dán VBA vào Mô-đun cửa sổ.

VBA: Nhập tất cả các tệp văn bản từ một thư mục vào một sổ làm việc

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. nhấn F5 phím hoặc chạy để chạy VBA và chọn một thư mục mà bạn muốn nhập các tệp văn bản từ trong hộp thoại bật lên. Xem ảnh chụp màn hình:

doc nhập nhiều văn bản csv xml 1

4. Và nhấp vào OKvà mỗi tệp văn bản trong thư mục đã chọn đã được nhập vào một trang tính của sổ làm việc đang hoạt động. Xem ảnh chụp màn hình:

doc nhập nhiều văn bản csv xml 2doc nhập nhiều văn bản csv xml 3

Dễ dàng kết hợp nhiều trang tính / Sổ làm việc thành một Trang tính hoặc Sổ làm việc

Để kết hợp nhiều trang tính hoặc sổ làm việc thành một trang tính hoặc sổ làm việc có thể khó khăn trong Excel, nhưng với Kết hợp trong Kutools cho Excel, bạn có thể kết hợp hợp nhất hàng chục trang tính / sổ làm việc thành một trang tính hoặc sổ làm việc, ngoài ra, bạn có thể hợp nhất các trang tính thành một chỉ bằng vài cú nhấp chuột.  Nhấp để dùng thử miễn phí 30 ngày đầy đủ tính năng!
kết hợp các tấm
 
Kutools cho Excel: với hơn 300 bổ trợ Excel tiện dụng, dùng thử miễn phí không giới hạn trong 30 ngày.

Để nhập tất cả các tệp csv tạo thành một thư mục vào một trang tính duy nhất, bạn có thể sử dụng mã VBA bên dưới.

1. Bật một trang tính trống và nhấn Alt + F11 chìa khóa để mở Microsoft Visual Basic cho các ứng dụng cửa sổ.

2. nhấp chuột Chèn > Mô-đunvà dán bên dưới VBA vào Mô-đun cửa sổ.

VBA: Nhập tệp csv từ một thư mục vào một trang tính

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. nhấn F5 phím hoặc bấm chạy để thực thi VBA và một hộp thoại bật ra để chọn một thư mục mà bạn muốn nhập tất cả các tệp csv từ đó. Xem ảnh chụp màn hình:

doc nhập nhiều văn bản csv xml 4

4. nhấp chuột OKvà một hộp thoại bật ra để nhắc bạn nếu xóa nội dung của trang tính đang hoạt động trước khi nhập, tôi nhấp vào đây. Xem ảnh chụp màn hình:

doc nhập nhiều văn bản csv xml 5

Sau khi nhấp , tất cả các tệp csv trong thư mục đã chọn được nhập vào trang tính hiện tại và đặt dữ liệu từ Cột A sang phải. Xem ảnh chụp màn hình:

doc nhập nhiều văn bản csv xml 6doc nhập nhiều văn bản csv xml 7

Mẹo: Nếu bạn muốn đặt tệp csv theo chiều ngang trong một trang tính, bạn có thể sử dụng VBA bên dưới.

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 nhập nhiều văn bản csv xml 8


Nếu bạn muốn nhập tất cả các tệp XML từ một thư mục vào một trang tính duy nhất, bạn có thể sử dụng mã VBA bên dưới.

1. Chọn một trang tính trống mà bạn muốn đặt dữ liệu đã nhập và nhấn Alt + F11 phím để kích hoạt Microsoft Visual Basic cho các ứng dụng cửa sổ.

2. nhấp chuột Chèn > Mô-đun, dán mã VBA vào Mô-đun cửa sổ.

VBA: Nhập tệp XML từ một thư mục vào một trang tính.

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. nhấp chuột chạy nút hoặc F5 để chạy VBA và chọn một thư mục trong hộp thoại bật lên, xem ảnh chụp màn hình:

doc nhập nhiều văn bản csv xml 9

4. nhấp chuột OK, và tất cả các tệp XML trong thư mục đã chọn được nhập vào trang tính hiện hoạt.


Nếu bạn không quen với VBA, đừng lo lắng, ở đây tôi giới thiệu một công cụ hữu ích - Kutools cho Excel cho bạn. Với sức mạnh của nó Kết hợp tiện ích, bạn có thể nhanh chóng kết hợp nhiều tệp xml hoặc tệp csv vào một sổ làm việc hoặc một trang tính Excel.

Kutools cho Excel, với hơn 300 chức năng tiện dụng, giúp công việc của bạn dễ dàng hơn. 

Sau khi cài đặt Kutools cho Excel, vui lòng làm như sau:(Tải xuống miễn phí Kutools cho Excel ngay!)

1. Active Excel và nhấp vào Kutools Plus > Kết hợp. Xem ảnh chụp màn hình :
doc kết hợp 1

2. Và trong bước 1 của Kết hợp hộp thoại, chọn một tùy chọn tách khi bạn cần. Xem ảnh chụp màn hình:
doc kết hợp 2

3. nhấp chuột Sau đi đến bước 2 của Kết hợp, Click Thêm để thêm tệp từ các thư mục khác nhau hoặc tệp từ một thư mục vào Bảng tính danh sách và bạn cũng có thể chỉ định các trang tính mà bạn muốn kết hợp Bảng danh sách của phần bên phải. Xem ảnh chụp màn hình:
doc kutools kết hợp các trang tính 3

4. nhấp chuột Sau đến bước cuối cùng của Kết hợpvà bạn có thể chỉ định các tùy chọn kết hợp.
doc kutools kết hợp các trang tính 4

5. nhấp chuột Kết thúc, một hộp thoại bật ra để nhắc bạn chọn một vị trí để lưu kết quả tổng hợp mới. Xem ảnh chụp màn hình:
doc kết hợp 5

6. nhấp chuột Lưu. Tất cả các trang tính thêm đã được kết hợp thành một trang tính mới.
doc kết hợp 6

Mẹo: Với Kết hợp, bạn cũng có thể kết hợp nhiều Tệp CSV tạo nhiều thư mục hoặc một thư mục thành một trang tính hoặc sổ làm việc.


Nếu bạn muốn xuất từng trang tính dưới dạng tệp csv / text / pdf vào một thư mục, Kutools cho Excel'S Chia sổ làm việc tiện ích có thể giúp ích cho bạn.

Sau cài đặt miễn phí Kutools cho Excel, vui lòng làm như sau:

1. Bật sổ làm việc bạn muốn xuất các trang tính của nó và nhấp vào Kutools Plus > Bảng tính > Chia sổ làm việc. Xem ảnh chụp màn hình:

doc nhập nhiều văn bản csv xml 10

2. bên trong Chia sổ làm việc hộp thoại, bạn có thể kiểm tra tên trang tính mà bạn cần xuất, theo mặc định, tất cả các trang tính đều được chọn và kiểm tra Chỉ định định dạng lưu và chọn định dạng tệp bạn muốn lưu từ danh sách thả xuống bên dưới. Xem ảnh chụp màn hình:

doc nhập nhiều văn bản csv xml 11

3. nhấp chuột chẻ và chọn một thư mục để lưu các tệp được chia nhỏ trong Chọn thư mục hộp thoại, xem ảnh chụp màn hình:

doc nhập nhiều văn bản csv xml 12

4. nhấp chuột OK, bây giờ tất cả các trang tính đã chọn được xuất dưới dạng định dạng tệp mới trong thư mục đã chọn.


Các bài báo tương đối:

Công cụ năng suất văn phòng tốt nhất

🤖 Trợ lý AI của Kutools: Cách mạng hóa việc phân tích dữ liệu dựa trên: Thực thi thông minh   |  Tạo mã  |  Tạo công thức tùy chỉnh  |  Phân tích dữ liệu và tạo biểu đồ  |  Gọi các hàm Kutools...
Các tính năng phổ biến: Tìm, đánh dấu hoặc xác định các bản sao   |  Xóa hàng trống   |  Kết hợp các cột hoặc ô mà không làm mất dữ liệu   |   Vòng không có công thức hữu ích. Cảm ơn !
Siêu tra cứu: Nhiều tiêu chí VLookup    VLookup Nhiều Giá Trị  |   VLookup trên nhiều trang tính   |   Tra cứu mờ ....
Danh sách thả xuống nâng cao: Tạo nhanh danh sách thả xuống   |  Danh sách thả xuống phụ thuộc   |  Danh sách thả xuống nhiều lựa chọn ....
Trình quản lý cột: Thêm một số cột cụ thể  |  Di chuyển cột  |  Chuyển đổi trạng thái hiển thị của các cột ẩn  |  So sánh dãy và cột hữu ích. Cảm ơn !
Các tính năng nổi bật: Tiêu điểm lưới   |  Chế độ xem thiết kế   |   Thanh công thức lớn    Trình quản lý sổ làm việc & trang tính   |  Thư viện tài nguyên (Văn bản tự động)   |  Bảng chọn ngày   |  Kết hợp các bảng tính   |  Mã hóa/Giải mã ô    Gửi email theo danh sách   |  Siêu lọc   |   Bộ lọc đặc biệt (lọc in đậm/nghiêng/gạch ngang...) ...
15 bộ công cụ hàng đầu12 bản văn CÔNG CỤ (thêm văn bản, Xóa ký tự,...)   |   50 + Biểu đồ Các loại (Biểu đồ Gantt,...)   |   40+ Thực tế Công thức (Tính tuổi dựa trên ngày sinh,...)   |   19 chèn CÔNG CỤ (Chèn mã QR, Chèn ảnh từ đường dẫn,...)   |   12 Chuyển đổi CÔNG CỤ (Số thành từ, Chuyển đổi tiền tệ,...)   |   7 Hợp nhất & Tách CÔNG CỤ (Các hàng kết hợp nâng cao, Chia ô,...)   |   ... và nhiều hơn nữa

Nâng cao kỹ năng Excel của bạn với Kutools for Excel và trải nghiệm hiệu quả hơn bao giờ hết. Kutools for Excel cung cấp hơn 300 tính năng nâng cao để tăng năng suất và tiết kiệm thời gian.  Bấm vào đây để có được tính năng bạn cần nhất...

Mô tả


Tab Office mang lại giao diện Tab cho Office và giúp công việc của bạn trở nên dễ dàng hơn nhiều

  • Cho phép chỉnh sửa và đọc theo thẻ trong Word, Excel, PowerPoint, Publisher, Access, Visio và Project.
  • Mở và tạo nhiều tài liệu trong các tab mới của cùng một cửa sổ, thay vì trong các cửa sổ mới.
  • Tăng 50% năng suất của bạn và giảm hàng trăm cú nhấp chuột cho bạn mỗi ngày!
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