Salt la conținutul principal

Cum să importați rapid mai multe fișiere CSV / text / XML în Excel?

În Excel, este posibil să fiți legat pentru a salva un registru de lucru ca fișier csv, fișier text sau fișier xml, dar ați încercat vreodată să importați mai multe fișiere csv / text / xml dintr-un folder într-un registru de lucru sau într-o foaie de lucru? În acest articol, introduc câteva metode pentru a le importa rapid pe lot.

Importați mai multe fișiere text dintr-un folder în fiecare fișă de lucru a unui registru de lucru cu VBA

Importați mai multe fișiere CSV dintr-un folder într-o singură foaie cu VBA

Importați mai multe fișiere XML dintr-un folder într-o singură foaie cu VBA

Importați sau combinați mai multe fișiere xml / csv într-o foaie sau un registru de lucru cu Kutools pentru Excel idee bună3

Exportați fiecare foaie ca csv / text / pdf într-un folder cu Kutools pentru Excelidee bună3


Pentru a importa fișiere text dintr-un folder într-un registru de lucru, puteți utiliza mai jos VBA pentru a le gestiona rapid.

1. Activați un registru de lucru gol și apăsați Alt + F11 tastele pentru a deschide Microsoft Visual Basic pentru aplicații fereastră.

2. clic Insera > Module, și lipiți VBA în Module fereastră.

VBA: Importați toate fișierele text dintr-un folder într-un registru de lucru

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. presa F5 cheie sau Alerga pentru a rula VBA și selectați un folder din care doriți să importați fișierele text din dialogul popping. Vedeți captura de ecran:

import doc mai multe text CSV xml 1

4. Și faceți clic pe OKși fiecare fișier text din folderul selectat a fost importat într-o foaie de lucru a registrului de lucru activ. Vedeți captura de ecran:

import doc mai multe text CSV xml 2import doc mai multe text CSV xml 3

Combinați cu ușurință mai multe foi / registru de lucru într-o singură coală sau registru de lucru

Pentru a combina mai multe foi sau registre de lucru într-o singură foaie sau registru de lucru poate fi dificil în Excel, dar cu Combina funcție în Kutools pentru Excel, puteți combina fuzionarea a zeci de foi / registre de lucru într-o singură foaie sau registru de lucru, de asemenea, puteți consolida foile într-una numai cu câteva clicuri.  Faceți clic pentru o versiune de încercare gratuită de 30 de zile!
combina foi
 
Kutools pentru Excel: cu peste 300 de programe de completare la îndemână Excel, gratuit pentru a încerca fără limitări în 30 de zile.

Pentru a importa toate fișierele CSV dintr-un dosar într-o singură foaie, puteți utiliza codul VBA de mai jos.

1. Activați o foaie de lucru goală și apăsați Alt + F11 tastele pentru a deschide Microsoft Visual Basic pentru aplicații fereastră.

2. clic Insera > Module, și lipiți mai jos VBA în noul Module fereastră.

VBA: Importați fișiere CSV dintr-un folder într-o singură foaie de lucru

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. presa F5 tasta sau faceți clic Alerga pentru a executa VBA și apare un dialog pentru a selecta un folder din care doriți să importați toate fișierele CSV. Vedeți captura de ecran:

import doc mai multe text CSV xml 4

4. clic OKși apare un dialog pentru a vă reaminti dacă ștergeți conținutul foii de lucru active înainte de import, aici fac clic Da. Vedeți captura de ecran:

import doc mai multe text CSV xml 5

După ce faceți clic Da, toate fișierele CSV din folderul selectat sunt importate în foaia curentă și plasează datele din Coloana A în dreapta. Vedeți captura de ecran:

import doc mai multe text CSV xml 6import doc mai multe text CSV xml 7

Sfat: Dacă doriți să plasați fișierele CSV orizontal într-o foaie de lucru, puteți utiliza mai jos 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 

import doc mai multe text CSV xml 8


Dacă doriți să importați toate fișierele XML dintr-un folder într-o singură foaie, puteți utiliza mai jos codul VBA.

1. Selectați o foaie goală pe care doriți să plasați datele importate și apăsați Alt + F11 taste pentru activare Microsoft Visual Basic pentru aplicații fereastră.

2. clic Insera > Module, lipiți codul VBA în Module fereastră.

VBA: Importați fișiere XML dintr-un folder într-o foaie de lucru.

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. clic Alerga butonul sau F5 tasta pentru a rula VBA și selectați un folder în caseta de dialog popping, consultați captura de ecran:

import doc mai multe text CSV xml 9

4. clic OKși toate fișierele XML din folderul selectat sunt importate în foaia activă.


Dacă nu sunteți familiarizați cu VBA, vă faceți griji, aici vă prezint un instrument la îndemână - Kutools pentru Excel Pentru dumneavoastră. Cu puterea sa Combina utilitar, puteți combina rapid mai multe fișiere XML sau fișiere CSV într-un singur registru de lucru sau într-o singură foaie Excel.

Kutools pentru Excel, cu mai mult de 300 funcții la îndemână, vă face munca mai ușoară. 

După instalare Kutools pentru Excel, faceți următoarele:(Descărcați gratuit Kutools pentru Excel acum!)

1. Activez Excel și faceți clic pe Kutools Plus > Combina. Vedeți captura de ecran :
doc combina 1

2. Și în pasul 1 din Combinați , alegeți o opțiune de separare după cum aveți nevoie. Vedeți captura de ecran:
doc combina 2

3. clic Pagina Următoare → a merge la pasul 2 al Combinației, Faceți clic pe Adăuga pentru a adăuga fișiere din diferite foldere sau fișiere dintr-un folder în Workbook listă și, de asemenea, puteți specifica foile din care doriți să combinați Fisa de lucru lista secțiunii din dreapta. Vedeți captura de ecran:
doc kutools combină foile 3

4. clic Pagina Următoare → până la ultimul pas al Combina, și puteți specifica opțiunile de combinare.
doc kutools combină foile 4

5. clic finalizarea, apare un dialog pentru a vă reaminti să selectați o locație pentru a salva noul rezultat combinat. Vedeți captura de ecran:
doc combina 5

6. clic Economisiți. Toate foile adăugate au fost combinate într-o singură foaie nouă.
doc combina 6

Sfat: cu Combina, de asemenea, puteți combina mai multe Fișiere CSV formează mai multe foldere sau un singur folder într-o singură foaie sau registru de lucru.


Dacă doriți să exportați fiecare foaie ca fișier csv / text / pdf într-un folder, Kutools pentru Excel'S Carnet de lucru divizat utilitatea vă poate face o favoare.

După instalare gratuită Kutools pentru Excel, faceți următoarele:

1. Activați registrul de lucru pe care doriți să-l exportați foile de lucru și faceți clic pe Kutools Plus > Workbook > Carnet de lucru divizat. Vedeți captura de ecran:

import doc mai multe text CSV xml 10

2. În Carnet de lucru divizat caseta de dialog, puteți verifica numele foilor pe care trebuie să le exportați, în mod implicit toate foile sunt verificate și verificați Specificați formatul de salvare și selectați formatul de fișier pe care doriți să îl salvați din lista verticală de mai jos. Vedeți captura de ecran:

import doc mai multe text CSV xml 11

3. clic Despică și selectați un folder pentru a salva fișierele împărțite în Căutați dosarul dialog, vezi captura de ecran:

import doc mai multe text CSV xml 12

4. clic OK, acum toate foile verificate sunt exportate ca nou format de fișier în folderul selectat.


Articole relative:

Cele mai bune instrumente de productivitate de birou

🤖 Kutools AI Aide: Revoluționați analiza datelor pe baza: Execuție inteligentă   |  Generați codul  |  Creați formule personalizate  |  Analizați datele și generați diagrame  |  Invocați funcțiile Kutools...
Caracteristici populare: Găsiți, evidențiați sau identificați duplicatele   |  Ștergeți rândurile goale   |  Combinați coloane sau celule fără a pierde date   |   Rundă fără Formula ...
Super căutare: VLookup cu mai multe criterii    VLookup cu valori multiple  |   VLookup pe mai multe foi   |   Căutare fuzzy ....
Listă derulantă avansată: Creați rapid o listă derulantă   |  Listă drop-down dependentă   |  Listă derulantă cu selectare multiplă ....
Manager de coloane: Adăugați un număr specific de coloane  |  Mutați coloanele  |  Comutați starea vizibilității coloanelor ascunse  |  Comparați intervale și coloane ...
Caracteristici prezentate: Focus pe grilă   |  Vedere de proiectare   |   Big Formula Bar    Manager registru de lucru și foi   |  Biblioteca de resurse (Text automat)   |  Data Picker   |  Combinați foi de lucru   |  Criptare/Decriptare celule    Trimiteți e-mailuri după listă   |  Super Filtru   |   Filtru special (filtrează bold/italic/barat...) ...
Top 15 seturi de instrumente12 Text Instrumente (Adăuga text, Eliminați caractere,...)   |   50+ Diagramă Tipuri de (Gantt Chart,...)   |   40+ Practic Formule (Calculați vârsta pe baza zilei de naștere,...)   |   19 inserare Instrumente (Introduceți codul QR, Inserați imaginea din cale,...)   |   12 Convertire Instrumente (Numere la cuvinte, conversie valutara,...)   |   7 Merge & Split Instrumente (Rânduri combinate avansate, Celule divizate,...)   |   ... și altele

Îmbunătățiți-vă abilitățile Excel cu Kutools pentru Excel și experimentați eficiența ca niciodată. Kutools pentru Excel oferă peste 300 de funcții avansate pentru a crește productivitatea și a economisi timp.  Faceți clic aici pentru a obține funcția de care aveți cea mai mare nevoie...

Descriere


Fila Office aduce interfața cu file în Office și vă face munca mult mai ușoară

  • Activați editarea și citirea cu file în Word, Excel, PowerPoint, Publisher, Access, Visio și Project.
  • Deschideți și creați mai multe documente în filele noi ale aceleiași ferestre, mai degrabă decât în ​​ferestrele noi.
  • Vă crește productivitatea cu 50% și reduce sute de clicuri de mouse pentru dvs. în fiecare zi!
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