Vai al contenuto principale

Come importare rapidamente in batch più file csv / text / xml in Excel?

In Excel, potresti aver legato per salvare una cartella di lavoro come file csv, file di testo o file xml, ma hai mai provato a importare più file csv / text / xml da una cartella in una cartella di lavoro o in un foglio di lavoro? In questo articolo, introduco alcuni metodi per importarli rapidamente in batch.

Importa più file di testo da una cartella in ogni foglio di lavoro di una cartella di lavoro con VBA

Importa più file CSV da una cartella in un unico foglio con VBA

Importa più file xml da una cartella in un unico foglio con VBA

Importa o combina più file xml/csv in un foglio o una cartella di lavoro con Kutools per Excel buona idea 3

Esporta ogni foglio come csv/testo/pdf in una cartella con Kutools per Excelbuona idea 3


Per importare file di testo da una cartella a una cartella di lavoro, puoi usare sotto VBA per gestirlo rapidamente.

1. Abilitare una cartella di lavoro vuota e premere Alt + F11 chiavi per aprire Microsoft Visual Basic, Applications Edition finestra.

2. Clic inserire > Modulie incolla il VBA nel file Moduli finestra.

VBA: importa tutti i file di testo da una cartella in una cartella di lavoro

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. Stampa F5 chiave o Correre pulsante per eseguire VBA e selezionare una cartella da cui si desidera importare i file di testo nella finestra di dialogo popping. Vedi screenshot:

doc importa più testo csv xml 1

4. E fare clic su OKe ogni file di testo nella cartella selezionata è stato importato in un foglio di lavoro della cartella di lavoro attiva. Vedi screenshot:

doc importa più testo csv xml 2doc importa più testo csv xml 3

Combina facilmente più fogli / cartella di lavoro in un unico foglio o cartella di lavoro

Combinare più fogli o cartelle di lavoro in un unico foglio o cartella di lavoro può essere fastidioso in Excel, ma con l'estensione Combinare funzione in Kutools per Excel, puoi combinare unire dozzine di fogli / cartelle di lavoro in un foglio o cartella di lavoro, inoltre, puoi consolidare i fogli in uno solo con diversi clic.  Fai clic per la prova gratuita di 30 giorni con tutte le funzionalità!
unire i fogli
 
Kutools per Excel: con oltre 300 pratici componenti aggiuntivi di Excel, provabili gratuitamente senza limitazioni in 30 giorni.

Per importare tutti i file CSV da una cartella in un unico foglio, puoi utilizzare il codice VBA sottostante.

1. Abilitare un foglio di lavoro vuoto e premere Alt + F11 chiavi per aprire Microsoft Visual Basic, Applications Edition finestra.

2. Clic inserire > Modulie incolla sotto VBA nel nuovo Moduli finestra.

VBA: importa i file CSV da una cartella in un foglio di lavoro

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. Stampa F5 tasto o fare clic Correre per eseguire il VBA e viene visualizzata una finestra di dialogo per selezionare una cartella da cui si desidera importare tutti i file CSV. Vedi screenshot:

doc importa più testo csv xml 4

4. Clic OKe viene visualizzata una finestra di dialogo per ricordarti se cancellare il contenuto del foglio di lavoro attivo prima dell'importazione, qui faccio clic. Vedi screenshot:

doc importa più testo csv xml 5

dopo aver fatto clic , tutti i file CSV nella cartella selezionata vengono importati nel foglio corrente e posizionano i dati dalla Colonna A a destra. Vedi screenshot:

doc importa più testo csv xml 6doc importa più testo csv xml 7

Mancia: Se vuoi posizionare i file CSV orizzontalmente in un foglio di lavoro, puoi usare sotto 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 importa più testo csv xml 8


Se desideri importare tutti i file XML da una cartella in un unico foglio, puoi utilizzare il codice VBA sottostante.

1. Selezionare un foglio bianco in cui inserire i dati importati e premere Alt + F11 tasti per abilitare Microsoft Visual Basic, Applications Edition finestra.

2. Clic inserire > Moduli, incolla il codice VBA nel file Moduli finestra.

VBA: importa file XML da una cartella in un foglio di lavoro.

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 Correre pulsante o F5 chiave per eseguire VBA e selezionare una cartella nella finestra di dialogo popping, vedi screenshot:

doc importa più testo csv xml 9

4. Clic OKe tutti i file XML nella cartella selezionata vengono importati nel foglio attivo.


Se non hai familiarità con VBA, preoccupati, qui presento uno strumento utile: Kutools for Excel per te. Con i suoi potenti Combinare utility, puoi combinare rapidamente più file xml o file csv in una cartella di lavoro o in un foglio Excel.

Kutools for Excel, con oltre 300 funzioni utili, rende il tuo lavoro più facile. 

Dopo l'installazione Kutools per Excel, per favore fai come di seguito:(Scarica subito Kutools per Excel!)

1. Active Excel e fare clic su Kutools Plus > Combinare. Vedi screenshot :
doc combinare 1

2. E in passaggio 1 di Combina finestra di dialogo, scegli un'opzione di separazione di cui hai bisogno. Vedi screenshot:
doc combinare 2

3. Clic Successivo andare passaggio 2 del Combine, fare clic su Aggiungi per aggiungere file da varie cartelle o file da una cartella a Cartella di lavoro e puoi anche specificare i fogli da cui desideri combinare Foglio di lavoro elenco delle sezioni di destra. Vedi screenshot:
doc kutools combina fogli 3

4. Clic Successivo all'ultimo passaggio di Combinaree puoi specificare le opzioni di combinazione.
doc kutools combina fogli 4

5. Clic Fine, viene visualizzata una finestra di dialogo per ricordare di selezionare una posizione in cui salvare il nuovo risultato combinato. Vedi screenshot:
doc combinare 5

6. Clic Risparmi. Tutti i fogli aggiunti sono stati combinati in un nuovo foglio singolo.
doc combinare 6

Mancia: Con Combinare, puoi anche combinare più file File CSV formare più cartelle o una cartella in un foglio o cartella di lavoro.


Se desideri esportare ogni foglio come file csv / testo / pdf in una cartella, Kutools for Excel'S Cartella di lavoro divisa l'utilità può farti un favore.

Dopo shavasana, sedersi in silenzio; saluti; installazione gratuita Kutools per Excel, per favore fai come di seguito:

1. Abilitare la cartella di lavoro di cui si desidera esportare i fogli di lavoro e fare clic su Kutools Plus > Cartella di lavoro > Cartella di lavoro divisa. Vedi screenshot:

doc importa più testo csv xml 10

2. Nel Cartella di lavoro divisa finestra di dialogo, puoi controllare i nomi dei fogli che devi esportare, di default tutti i fogli sono controllati e spuntati Specifica il formato di salvataggio e selezionare il formato di file che si desidera salvare dal seguente elenco a discesa. Vedi screenshot:

doc importa più testo csv xml 11

3. Clic Diviso e seleziona una cartella in cui salvare i file divisi in Cerca cartella finestra di dialogo, vedi screenshot:

doc importa più testo csv xml 12

4. Clic OK, ora tutti i fogli selezionati vengono esportati come nuovo formato di file nella cartella selezionata.


Articoli relativi:

I migliori strumenti per la produttività in ufficio

🤖 Assistente AI di Kutools: Rivoluziona l'analisi dei dati basandosi su: Esecuzione intelligente   |  Genera codice  |  Crea formule personalizzate  |  Analizzare i dati e generare grafici  |  Richiama le funzioni di Kutools...
Funzioni popolari: Trova, evidenzia o identifica i duplicati   |  Elimina righe vuote   |  Combina colonne o celle senza perdere dati   |   Round senza formula ...
Super ricerca: VLookup a criteri multipli    VLookup a valori multipli  |   VLookup su più fogli   |   Ricerca fuzzy ....
Elenco a discesa avanzato: Crea rapidamente un elenco a discesa   |  Elenco a discesa dipendente   |  Elenco a discesa a selezione multipla ....
Gestore di colonna: Aggiungi un numero specifico di colonne  |  Sposta colonne  |  Attiva/disattiva lo stato di visibilità delle colonne nascoste  |  Confronta intervalli e colonne ...
Funzionalità in primo piano: Messa a fuoco della griglia   |  Vista di progettazione   |   Grande barra delle formule    Gestore di cartelle di lavoro e fogli   |  Resource Library (Testo automatico)   |  Date picker   |  Combina fogli di lavoro   |  Crittografa/decrittografa le celle    Invia e-mail per elenco   |  Super filtro   |   Filtro speciale (filtro grassetto/corsivo/barrato...) ...
I 15 migliori set di strumenti12 Testo Strumenti (aggiungi testo, Rimuovi personaggi, ...)   |   50+ Grafico Tipi (Diagramma di Gantt, ...)   |   40+ Pratico Formule (Calcola l'età in base al compleanno, ...)   |   19 Inserimento Strumenti (Inserisci il codice QR, Inserisci immagine dal percorso, ...)   |   12 Conversione Strumenti (Numeri in parole, Conversione di valuta, ...)   |   7 Unisci e dividi Strumenti (Combina righe avanzate, Celle divise, ...)   |   ... e altro ancora

Potenzia le tue competenze di Excel con Kutools per Excel e sperimenta l'efficienza come mai prima d'ora. Kutools per Excel offre oltre 300 funzionalità avanzate per aumentare la produttività e risparmiare tempo.  Fai clic qui per ottenere la funzionalità di cui hai più bisogno...

Descrizione


Office Tab porta l'interfaccia a schede in Office e semplifica notevolmente il tuo lavoro

  • Abilita la modifica e la lettura a schede in Word, Excel, PowerPoint, Publisher, Access, Visio e Project.
  • Apri e crea più documenti in nuove schede della stessa finestra, piuttosto che in nuove finestre.
  • Aumenta la produttività del 50% e riduce ogni giorno centinaia di clic del mouse!
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