Перейти к основному содержанию

Как быстро импортировать несколько файлов csv / text / xml в Excel?

В Excel вам, возможно, приходилось сохранять книгу как файл csv, текстовый файл или файл xml, но пробовали ли вы когда-нибудь импортировать несколько файлов csv / text / xml из папки в книгу или рабочий лист? В этой статье я расскажу о некоторых методах их быстрого пакетного импорта.

Импортируйте несколько текстовых файлов из папки на каждый лист книги с помощью VBA

Импортируйте несколько файлов CSV из папки на один лист с помощью VBA

Импортируйте несколько файлов xml из папки на один лист с помощью VBA

Импортируйте или объедините несколько файлов xml / csv в лист или книгу с помощью Kutools for Excel хорошая идея3

Экспортируйте каждый лист как csv / text / pdf в папку с помощью Kutools for Excelхорошая идея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 ключа или Run кнопку, чтобы запустить 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 ключ или щелкните Run кнопку для выполнения VBA, и появится диалоговое окно для выбора папки, из которой вы хотите импортировать все CSV-файлы. Смотрите скриншот:

doc импортировать несколько текстов csv xml 4

4. Нажмите OK, и появится диалоговое окно, напоминающее вам, если очистить содержимое активного листа перед импортом, здесь я нажимаю Да. Смотрите скриншот:

doc импортировать несколько текстов csv xml 5

После нажатия кнопки Да, все 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. Нажмите Run или 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 и щелкните Кутулс Плюс > Сочетать. Смотрите скриншот :
док комбинировать 1

2. А в шаг 1 комбинирования В диалоговом окне выберите нужный вариант разделения. Смотрите скриншот:
док комбинировать 2

3. Нажмите Следующая идти на шаг 2 комбинирования, нажмите Добавить добавлять файлы из разных папок или файлы из одной папки в Workbook список, а также вы можете указать листы, которые хотите объединить из Рабочий лист список правого раздела. Смотрите скриншот:
doc kutools объединить листы 3

4. Нажмите Следующая до последнего шага Сочетать, и вы можете указать параметры комбинирования.
doc kutools объединить листы 4

5. Нажмите Завершить, появится диалоговое окно с напоминанием о выборе места для сохранения нового комбинированного результата. Смотрите скриншот:
док комбинировать 5

6. Нажмите Сохранить. Все добавляемые листы были объединены в новый единый лист.
док комбинировать 6

Наконечник: Доступно Сочетать, вы также можете объединить несколько Файлы CSV сформировать несколько папок или одну папку в один лист или книгу.


Если вы хотите экспортировать каждый лист как файл csv / text / pdf в папку, Kutools for ExcelАвтора Разделить книгу Утилита может оказать вам услугу.

После бесплатная установка Kutools for Excel, сделайте следующее:

1. Включите книгу, листы которой вы хотите экспортировать, и нажмите Кутулс Плюс > Workbook > Разделить книгу. Смотрите скриншот:

doc импортировать несколько текстов csv xml 10

2. в Разделить книгу в диалоговом окне вы можете проверить имена листов, которые нужно экспортировать, по умолчанию все листы отмечены, и проверить Укажите формат сохранения и выберите формат файла, который вы хотите сохранить, в раскрывающемся списке ниже. Смотрите скриншот:

doc импортировать несколько текстов csv xml 11

3. Нажмите Split и выберите папку для сохранения разделенных файлов в Найдите папку диалог, см. снимок экрана:

doc импортировать несколько текстов csv xml 12

4. Нажмите OK, теперь все отмеченные листы экспортируются как новый формат файла в выбранную папку.


Относительные статьи:

Лучшие инструменты для офисной работы

🤖 Kutools AI Помощник: Революционный анализ данных на основе: Интеллектуальное исполнение   |  Генерировать код  |  Создание пользовательских формул  |  Анализ данных и создание диаграмм  |  Вызов функций Kutools...
Популярные опции: Найдите, выделите или определите дубликаты   |  Удалить пустые строки   |  Объедините столбцы или ячейки без потери данных   |   Раунд без формулы ...
Супер поиск: Множественный критерий VLookup    VLookup с несколькими значениями  |   VLookup по нескольким листам   |   Нечеткий поиск ....
Расширенный раскрывающийся список: Быстрое создание раскрывающегося списка   |  Зависимый раскрывающийся список   |  Выпадающий список с множественным выбором ....
Менеджер столбцов: Добавить определенное количество столбцов  |  Переместить столбцы  |  Переключить статус видимости скрытых столбцов  |  Сравнить диапазоны и столбцы ...
Рекомендуемые функции: Сетка Фокус   |  Просмотр дизайна   |   Большой Формулный Бар    Менеджер книг и листов   |  Библиотека ресурсов (Авто текст)   |  Выбор даты   |  Комбинировать листы   |  Шифровать/дешифровать ячейки    Отправлять электронные письма по списку   |  Суперфильтр   |   Специальный фильтр (фильтровать жирным шрифтом/курсивом/зачеркиванием...) ...
15 лучших наборов инструментов12 Текст Инструменты (Добавить текст, Удалить символы, ...)   |   50+ График Тип (Диаграмма Ганта, ...)   |   40+ Практических Формулы (Рассчитать возраст по дню рождения, ...)   |   19 Вносимые Инструменты (Вставить QR-код, Вставить изображение из пути, ...)   |   12 Конверсия Инструменты (Числа в слова, Конверсия валюты, ...)   |   7 Слияние и разделение Инструменты (Расширенные ряды комбинирования, Разделить клетки, ...)   |   ... и более

Улучшите свои навыки работы с Excel с помощью Kutools for Excel и почувствуйте эффективность, как никогда раньше. Kutools for Excel предлагает более 300 расширенных функций для повышения производительности и экономии времени.  Нажмите здесь, чтобы получить функцию, которая вам нужна больше всего...

Описание


Вкладка Office: интерфейс с вкладками в Office и упрощение работы

  • Включение редактирования и чтения с вкладками в Word, Excel, PowerPoint, Издатель, доступ, Visio и проект.
  • Открывайте и создавайте несколько документов на новых вкладках одного окна, а не в новых окнах.
  • Повышает вашу продуктивность на 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