Xml for excel import

Если вы ранее создали карту XML,вы можете использовать ее для импорта данных XML в ячейки, которые соеряду, но существуют также несколько способов и команд импорта данных XML без карты XML.

При наличии карты XML сделайте следующее для импорта данных XML в сопоставленные ячейки:

  1. В карте XML выберите одну из сопоставленных ячеек.

  2. На вкладке Разработчик нажмите кнопку Импорт.

    Если вкладка Разработчик не отображается, см. раздел Отображение вкладки «Разработчик».

  3. В диалоговом окне Импорт XML найдите и выберите файл данных XML (XML-файл), который вы хотите импортировать, и нажмите кнопку Импорт.

Другие способы импорта данных XML

  • Импорт файла данных XML в качестве XML-таблицы

  • Импорт нескольких файлов данных XML

  • Импорт нескольких файлов данных XML в качестве внешних данных

  • Открытие файла данных XML для импорта данных

Дополнительные сведения о проблемах см. в разделе Типичные проблемы при импорте данных XML в конце этой статьи.

Импорт файла данных XML в качестве XML-таблицы

  1. На вкладке Разработчик нажмите кнопку Импорт.

    Если вкладка Разработчик не отображается, см. раздел Отображение вкладки «Разработчик».

  2. В диалоговом окне Импорт XML найдите и выберите файл данных XML (XML-файл), который вы хотите импортировать, и нажмите кнопку Импорт.

    Если файл данных XML не ссылается ни на какую схему, Excel создает ее на основе этого файла.

  3. В диалоговом окне Импорт данных выполните одно из следующих действий:

    1. Выберите XML-таблицу на существующем компьютере, чтобы импортировать содержимое файла данных XML в XML-таблицу на вашем компьютере в указанной ячейке.

    2. Чтобы импортировать содержимое файла в XML-таблицу на новом, начиная с ячейки A1, выберите XML-таблицу на новом. Карта файла данных XML отобразится в области задач Источник XML.

  4. Если файл данных XML не ссылается ни на какую схему, Excel создает ее на основе этого файла.

  5. Чтобы контролировать поведение данных XML (например, привязку данных, форматирование и макет), нажмите кнопку Свойства ,чтобы отобразить диалоговое окно Свойства карты XML. Например, при импорте данных по умолчанию существующие данные в диапазоне будут перезаписаны, но это можно изменить.

Импорт нескольких файлов данных XML

  1. Выберите сопоставленную ячейку, чтобы импортировать несколько XML-файлов в один набор сопоставленных ячеек.

    Если вы хотите импортировать несколько XML-файлов в несколько наборов сопоставленных ячеек, щелкните любую несопоставленную ячейку листа.

  2. На вкладке Разработчик нажмите кнопку Импорт.

    Если вкладка Разработчик не отображается, см. раздел Отображение вкладки «Разработчик».

  3. В диалоговом окне Импорт XML найдите и выберите файл данных XML (XML-файл), который вы хотите импортировать.

    • Если файлы являются смежными, нажмите клавишу SHIFT, а затем щелкните первый и последний файл в списке. Все данные из XML-файлов будут импортированы и добавлены в сопоставленные ячейки.

    • Если файлы не являются смежными, нажмите клавишу CTRL, а затем щелкните все файлы списка, которые вы хотите импортировать.

  4. Нажмите кнопку Импорт.

    Если вы выбрали несколько файлов, появится диалоговое окно Импорт <>.xml файл. Выберите карту XML, соответствующую импортируемому файлу данных XML.

    Чтобы использовать одну карту для всех выделенных файлов, которые еще не были импортированы, установите флажок Использовать эту карту XML для всех выбранных файлов этой схемы.

Импорт нескольких файлов данных XML в качестве внешних данных

Если нужно импортировать несколько XML-файлов с одним пространством имен, но с разными схемами XML, вы можете воспользоваться командой Из импорта данных XML. Excel создаст уникальную карты XML для каждого импортируемого файла данных XML.

Примечание: При импорте нескольких XML-файлов, в которых не определено пространство имен, считается, что они используют одно пространство имен.

  1. Если вы используете Excel с подпиской наMicrosoft 365, щелкните Данные > Получить данные > из файла > из XML.

    Если вы используете Excel 2016 или более раннюю версию, на вкладке Данные нажмите кнопку Из других источников, а затем щелкните Из импорта данных XML.

  2. Выберите диск, папку или расположение в Интернете, где находится файл данных XML (XML-файл), который вы хотите импортировать.

  3. Выберите файл и нажмите кнопку Открыть.

  4. В диалоговом окне Импорт данных выберите один из следующих параметров:

    • В XML-таблицу в существующей книге.    Содержимое файла импортируется в новую таблицу XML на новом листе. Если файл данных XML не ссылается ни на какую схему, Excel создает ее на основе этого файла.

    • Существующий таблица    Данные XML импортируется в двумерную таблицу со строками и столбцами, где теги XML показаны как заголовки столбцов, а данные — в строках под заголовками столбцов. Первый элемент (корневой узел) используется как заголовок и отображается в указанном расположении ячейки. Остальные теги отсортировали по алфавиту во второй строке. В этом случае схема не создается и вы не можете использовать карту XML.

    • На новый лист.    Excel добавляет в книгу новый лист и автоматически помещает данные XML в его левый верхний угол. Если файл данных XML не ссылается ни на какую схему, Excel создает ее на основе этого файла.

  5. Чтобы контролировать поведение данных XML, таких как привязка, форматирование и макет, нажмите кнопку Свойства ,чтобы отобразить диалоговое окно Свойства карты XML. Например, при импорте данных по умолчанию существующие данные в соеченом диапазоне перезаписываются, но это можно изменить.

Открытие файла данных XML для импорта данных

  1. Выберите команду Файл > Открыть.

    Если вы используете Excel 2007, нажмите Microsoft Office кнопку Изображение кнопки Office >открыть.

  2. В диалоговом окне Открытие файла выберите диск, папку или веб-адрес, где расположен нужный файл.  

  3. Выберите файл и нажмите кнопку Открыть.

  4. Если появится диалоговое окно Импорт XML, открытый файл ссылается на одну или несколько таблиц стилей XSLT, поэтому можно щелкнуть один из следующих параметров:

    • Открытие файла без применения таблицы стилей    Данные XML импортируется в двумерную таблицу со строками и столбцами, где теги XML показаны как заголовки столбцов, а данные — в строках под заголовками столбцов. Первый элемент (корневой узел) используется как заголовок и отображается в указанном расположении ячейки. Остальные теги отсортировали по алфавиту во второй строке. В этом случае схема не создается и вы не можете использовать карту XML.

    • Открыть файл, применив следующую таблицу стилей (выберите одну).    Выберите таблицу стилей, которую вы хотите применить, и нажмите кнопку ОК. Данные XML будут отформатированы в соответствии с выбранным листом стилей.

      Примечание: Данные XML будут открыты в Excel в режиме «только для чтения», что позволяет предотвратить случайное сохранение первоначального исходного файла в формате книги Excel с поддержкой макросов (XLSM). В этом случае схема не создается и вы не можете использовать карту XML.

  5. Если появится диалоговое окно Открыть XML, в XML-файле не будет ссылок на таблицу стилей XSLT. Чтобы открыть файл, выберите один из следующих параметров:

    • Щелкните XML-таблица для создания XML-таблицы в новой книге.

      Содержимое файла импортируется в XML-таблицу. Если файл данных XML не ссылается ни на какую схему, Excel создает ее на основе этого файла.

    • Выберите в качестве книги, которая будет работать только для чтения.

      Данные XML импортируется в двумерную таблицу со строками и столбцами, где теги XML показаны как заголовки столбцов, а данные — в строках под заголовками столбцов. Первый элемент (корневой узел) используется как заголовок и отображается в указанном расположении ячейки. Остальные теги отсортировали по алфавиту во второй строке. В этом случае схема не создается и вы не можете использовать карту XML.

      Данные XML будут открыты в Excel в режиме «только для чтения», что позволяет предотвратить случайное сохранение первоначального исходного файла в формате книги Excel с поддержкой макросов (XLSM). В этом случае схема не создается и вы не можете использовать карту XML.

    • Щелкните Использовать область задач XML-источника.

      Карта файла данных XML отобразится в области задач Источник XML. Для сопоставления элементов схемы с листом их можно перетащить на лист.

      Если файл данных XML не ссылается ни на какую схему, Excel создает ее на основе этого файла.

Распространенные проблемы при импорте данных XML

Excel отображает диалоговое окно Ошибка импорта XML, если не может проверить данные в соответствии с картой XML. Чтобы получить дополнительные сведения об ошибке, нажмите кнопку Сведения в этом диалоговом окне. В следующей ниже таблице описаны ошибки, которые часто возникают при импорте данных.

Ошибка

Объяснение

Ошибка при проверке схемы

Когда вы выбрали в диалоговом окне Свойства карты XML параметр Проверять данные на соответствие схеме при импорте и экспорте, данные были импортированы, но не проверены на соответствие указанной карте XML.

Некоторые данные были импортированы как текст

Часть импортированных данных или все данные были преобразованы из объявленного типа в текст. Чтобы использовать эти данные в вычислениях, необходимо преобразовать их в числа или даты. Например, значение даты, преобразованное в текст, не будет работать должным образом в функции ГОД, пока вы не преобразуйте его в тип данных «Дата». Excel преобразует данные в текст в следующих случаях:

  • Данные в формате, который Excel не поддерживается.

  • Данные несовместимы с внутренним представлением типа данных XSD в Excel. Чтобы исправить эту проблему, удостоверьтесь, что данные XML соответствуют XML-схеме, проверив каждое из определений типа данных.

Ошибка разбора XML

Средству синтаксического анализа XML не удается открыть указанный XML-файл. Убедитесь, что в XML-файле отсутствуют синтаксические ошибки и XML построен правильно.

Не удается найти карту XML, соответствующую этим данным

Эта проблема может возникнуть в том случае, если для импорта выбрано несколько файлов данных XML и Excel не удается найти соответствующую карту XML для одного из них. Импортируйте схему для файла, указанного в строке заголовка этого диалогового окна, сначала следует, а затем повторно выполните импорт файла.

Не удается изменить размер XML-таблицы для включения данных

Вы пытаетесь добавить строки путем импорта или добавления данных в XML-таблицу, однако таблицу невозможно расширить. XML-таблицу можно дополнять только снизу. Например, сразу под XML-таблицей может находиться объект, такой как рисунок или даже другая таблица, который не позволяет расширить ее. Кроме того, возможно, что при расширении XML-таблицы будет превышен установленный в Excel предел по количеству строк (1 048 576). Чтобы исправить эту проблему, измените расположение таблиц и объектов на листе, чтобы XML-таблица могла дополняться снизу.

Указанный XML-файл не ссылается на схему

XML-файл, который вы пытаетесь открыть, не ссылается на схему XML. Для работы с данными XML, содержащимися в файле, Excel требуется схема, основанная на его содержимом. Если такая схема неверна или не отвечает вашим требованиям, удалите ее из книги. Затем создайте файл схемы XML и измените файл данных XML так, чтобы он ссылался на схему. Дополнительные сведения см. в статье Сопоставление XML-элементов с ячейками карты XML.

Примечание: Схему, созданную Excel, невозможно экспортировать в качестве отдельного файла данных схемы XML (XSD-файла). Хотя существуют редакторы схем XML и другие способы создания файлов схемы XML, возможно, вы не имеете к ним доступа или не знаете, как ими пользоваться.

Выполните следующие действия, чтобы удалить из книги схему, созданную Excel:

  1. На вкладке Разработчик выберите команду Источник.

    Команды XML на вкладке "Разработчик"

    Если вкладка Разработчик не отображается, см. раздел Отображение вкладки «Разработчик».

  2. В области задач Источник XML выберите пункт Карты XML.

  3. В диалоговом окне Карты XML щелкните карту XML, созданную Excel ,и нажмите кнопку Удалить.

Возникают проблемы при импорте нескольких XML-файлов, которые используют одно пространство имен, но разные схемы

При работе с несколькими файлами данных XML и несколькими схемами XML стандартным подходом является создание карты XML для каждой схемы, сопоставление нужных элементов, а затем импорт каждого из файлов данных XML в соответствующую карту XML. При использовании команды Импорт для открытия нескольких XML-файлов с одним пространством имен можно использовать только одну схему XML. Если эта команда используется для импорта нескольких XML-файлов, использующих одно пространство имен при разных схемах, можно получить непредсказуемые результаты. Например, это может привести к тому, что данные будут перезаписаны или файлы перестанут открываться.

Если нужно импортировать несколько XML-файлов с одним пространством имен, но с разными схемами XML, вы можете воспользоваться командой Из импорта данных XML (выберите Данные > Из других источников). Эта команда позволяет импортировать несколько XML-файлов с одним пространством имен и разными схемами XML. Excel создаст уникальную карты XML для каждого импортируемого файла данных XML.

Примечание: При импорте нескольких XML-файлов, в которых не определено пространство имен, считается, что они используют одно пространство имен.

Отображение вкладки «Разработчик»

Если вкладка Разработчик недоступна, выполните следующие действия, чтобы открыть ее.

  • В Excel 2013 и Excel 2010

    1. Выберите Файл > Параметры.

    2. Щелкните категорию Настроить ленту.

    3. В разделе Основные вкладки установите флажок Разработчик и нажмите кнопку ОК.

  • В Excel 2007

    1. Нажмите кнопку Microsoft Office кнопку Изображение кнопки Office>Excel параметры.

    2. Выберите категорию Основные.

    3. В разделе Основные параметры работы с Excel установите флажок Показывать вкладку «Разработчик» на ленте и нажмите кнопку ОК.

См. также

Просмотр XML в Excel

Сопоставление XML-элементов с ячейками карты XML

Экспорт данных XML

If you previously created an XML Map, you can use it to import XML data into cells that are mapped, but there also are several methods and commands for importing XML data without an XML Map.

If you have an XML Map, do this to import XML data into mapped cells:

  1. In the XML Map, select one of the mapped cells.

  2. Click Developer > Import.

    If you don’t see the Developer tab, see Show the Developer tab.

  3. In the Import XML dialog box, locate and select the XML data file (.xml) you want to import, and click Import.

Other ways to import XML data

  • Import an XML data file as an XML table

  • Import multiple XML data files

  • Import multiple XML data files as external data

  • Open an XML data file to import its data

For more information about issues, see Common issues with importing XML data at the end of this article.

Import an XML data file as an XML table

  1. Click Developer > Import.

    If you don’t see the Developer tab, see Show the Developer tab.

  2. In the Import XML dialog box, locate and select the XML data file (.xml) you want to import, and click Import.

    If the XML data file doesn’t refer to a schema, Excel infers the schema from the XML data file.

  3. In the Import Data dialog box, do one of the following:

    1. Select XML table in existing worksheet to import the contents of the XML data file into an XML table in your worksheet at the specified cell location.

    2. Select XML table in new worksheet to import the contents of the file into an XML table in a new worksheet starting at cell A1. The schema of the XML data file is displayed in the XML Source task pane.

  4. If the XML data file doesn’t refer to a schema, then Excel infers the schema from the XML data file.

  5. To control the behavior of XML data (such as data binding, format, and layout), click Properties, which displays the XML Map properties dialog box. For example, existing data in a mapped range will be overwritten when you import data by default, but you can change this.

Import multiple XML data files

  1. Select a mapped cell to import multiple XML files into a single set of mapped cells.

    If you want to import multiple XML files into multiple sets of mapped cells, click a cell anywhere on the worksheet that isn’t mapped.

  2. Click Developer > Import.

    If you don’t see the Developer tab, see Show the Developer tab.

  3. In the Import XML dialog box, locate and select the XML data file (.xml) you want to import.

    • If the files are contiguous, press Shift, and click the first and the last file in the list. All of the data from the XML files will be imported and appended to the mapped cells.

    • If the files aren’t contiguous, press and hold Ctrl, and click each file you want to import in the list.

  4. Click Import.

    If you selected files that aren’t contiguous, the Importing <filename>.xml dialog box appears. Select the XML Map that corresponds to the XML data file you’re importing for each file.

    To use a single map for all of the selected files that aren’t yet imported, select Use this XML Map for all selected files of this schema.

Import multiple XML data files as external data

To import multiple XML files that use the same namespace but different XML schemas, you can use the From XML Data Import command. Excel creates a unique XML Map for each XML data file you import.

Note: If you’re importing multiple XML files that don’t define a namespace, these XML files are treated as if they use the same namespace.

  1. If you’re using Excel with a Microsoft 365 subscription, click Data > Get Data > From File > From XML.

    If you’re using Excel 2016 or earlier, click Data > From Other Sources > From XML Data Import.

  2. Go to the drive, folder, or Internet location that has the XML data file (.xml) you want to import.

  3. Select the file and click Open.

  4. In the Import Data dialog box, do one of the following:

    • XML table in existing worksheet    The contents of the file are imported into a new XML table in a new worksheet. If the XML data file doesn’t refer to a schema, Excel infers the schema from the XML data file.

    • Existing worksheet    The XML data is imported in a two-dimensional table with rows and columns that shows XML tags as column headings, and data in rows below the column headings. The first element (the root node) is used like a title and is displayed in the specified cell location. The rest of the tags are sorted alphabetically across the second row. In this case, Excel doesn’t infer a schema, and you can’t use an XML Map.

    • New worksheet    Excel adds a new worksheet to your workbook and automatically puts the XML data in the upper-left corner of the new worksheet. If the XML data file doesn’t refer to a schema, Excel infers the schema from the XML data file.

  5. To control the behavior of XML data, such as data binding, format, and layout, click Properties, which displays the XML Map properties dialog box. For example, existing data in a mapped range is overwritten when you import data by default, but you can change this.

Open an XML data file to import its data

  1. Click File > Open.

    If you’re using Excel 2007, click Microsoft Office Button Office button image > Open.

  2. In the Open dialog box, click the drive, folder, or Internet location that has the file that you want to open.  

  3. Select the file and click Open.

  4. If the Import XML dialog box appears, the file you opened refers to one or more Extensible Stylesheet Language Transformation (XSLT) style sheets, so you can click one of the following options:

    • Open the file without applying a style sheet    The XML data is imported in a two-dimensional table with rows and columns that shows XML tags as column headings, and data in rows below the column headings. The first element (the root node) is used like a title and is displayed in the specified cell location. The rest of the tags are sorted alphabetically across the second row. In this case, Excel doesn’t infer a schema, and you can’t use an XML Map.

    • Open the file with the following style sheet applied (select one)    Select the style sheet that you want to apply, and then click OK. The XML data is formatted according to the style sheet that you selected.

      Note: The XML data is opened as read-only in Excel so that you don’t accidentally save your original source file in the Excel Macro-Enabled Workbook file format (.xlsm). In this case, Excel doesn’t infer a schema, and you can’t use an XML Map.

  5. If the Open XML dialog box appears, the XML file doesn’t have any XSLT style sheet references. To open the file, click one of the following options:

    • Click As an XML table to create an XML table in a new workbook.

      The contents of the file are imported into the XML table. If the XML data file doesn’t refer to a schema, Excel infers the schema from the XML data file.

    • Click As a read-only workbook.

      The XML data is imported in a two-dimensional table with rows and columns that shows XML tags as column headings, and data in rows below the column headings. The first element (the root node) is used like a title and is displayed in the specified cell location. The rest of the tags are sorted alphabetically across the second row. In this case, Excel doesn’t infer a schema, and you can’t use an XML Map.

      The XML data is opened as read-only in Excel so that you don’t accidentally save your original source file in the Excel Macro-Enabled Workbook file format (.xlsm). In this case, Excel doesn’t infer a schema, and you can’t use an XML Map.

    • Click Use the XML Source task pane.

      The schema of the XML data file is displayed in the XML Source task pane. You can then drag elements of the schema to the worksheet to map those elements to the worksheet.

      If the XML data file doesn’t refer to a schema, Excel infers the schema from the XML data file.

Common issues with importing XML data

Excel displays the XML Import Error dialog box when it can’t validate data according to the XML Map. In this dialog box, click Details for additional information about each error. The following table lists some common import errors:

Error

What happened

Failed schema validation

When you clicked Validate data against schema for import and export in the XML Map Properties dialog box, the data was imported, but the data wasn’t validated against the specified XML Map.

Some data was imported as text

Some or all of the data you imported was converted from its declared data type to text. To use this data in a calculation, you’ll need to convert the data from text to numbers or dates. For example, a date value converted to text won’t work as intended in the YEAR function until you convert it to the Date data type. Excel converts data to text when:

  • The data is in a format Excel doesn’t support.

  • The data is incompatible with the Excel internal representation of the XSD data type. To fix this problem, check each data type declaration to make sure your XML data is valid according to the XML schema.

XML parse error

The XML parser can’t open the specified XML file. Make sure the XML file doesn’t have syntax errors, and that the XML is well-formed.

Can’t find an XML Map that corresponds to the data

This problem can occur when you select more than one XML data file to import, and Excel can’t find a matching XML Map for one of the files. For the file named in the title bar of the dialog box, import an appropriate schema first, and then try importing the file again.

An XML table can’t be resized to accommodate data

You’re attempting to add rows by importing or appending data to the XML table, but there’s no room for the table to expand. An XML table can only expand from the bottom down. For example, there may be an object, such as a picture or another table, immediately below the XML table that prevents the XML table from expanding. Or, for the XML table to expand, it will exceed the Excel row limit of 1,048,576. To fix this problem, rearrange the tables and objects on the worksheet to allow the XML table to expand from the bottom down.

The specified XML file doesn’t refer to a schema

The XML file you’re trying to open doesn’t refer to an XML schema. To work with the XML data that’s in the file, Excel needs a schema based on the contents of the XML file. If that schema is incorrect or insufficient, remove it from your workbook. Then create an XML schema file and edit the XML data file so that the XML data file refers to the schema. For more information, see Map XML elements to cells in an XML Map.

Note: You can’t export the Excel inferred schema as a separate XML schema data file (.xsd). Although there are XML schema editors and other methods for creating an XML schema file, you may not have convenient access to them or know how to use them.

Follow these steps to remove the schema that Excel created from your workbook:

  1. Click Developer > Source.

    XML commands on the Developer tab

    If you don’t see the Developer tab, see Show the Developer tab.

  2. In the XML Source task pane, click XML Maps.

  3. In the XML Maps dialog box, click the XML Map Excel created, and click Delete.

Importing multiple XML files that use the same namespace but different schemas doesn’t work as expected

When you work with multiple XML data files and XML schemas, you typically create an XML Map for each schema, map the elements you want, and then import each XML data file to the appropriate XML Map. Using the Import command to open multiple XML files with the same namespace, you can only use one XML schema. When you use this command to open multiple XML files that use the same namespace but different schemas, you can get unexpected results. For example, data may get overwritten, or the files won’t open.

To import multiple XML files that use the same namespace but different XML schemas, try use the From XML Data Import command (click Data > From Other Sources). This command allows multiple XML files with the same namespace to use multiple XML schemas. Excel creates a unique XML Map for each XML data file you want to import.

Note: If you’re importing multiple XML files that don’t define a namespace, these XML files are treated as if they use the same namespace.

Show the Developer tab

If you don’t see the Developer tab, do the following to display it:

  • In Excel 2013 and Excel 2010:

    1. Click File > Options.

    2. Click the Customize Ribbon category.

    3. Under Main Tabs, check the Developer box, and click OK.

  • In Excel 2007:

    1. Click the Microsoft Office Button Office button image> Excel Options.

    2. Click the Popular category.

    3. Under Top options for working with Excel, check the Show Developer tab in the Ribbon box, and click OK.

See Also

Over view of XML in Excel

Map XML elements to cells in an XML Map

Export XML data

The XML file format is quite commonly used on the web, and there is a possibility that sometimes you may have to work with the data in the XML file.

Now you can’t use the XML file directly, as it’s not meant to be read by humans (but machines).

In such a case, it would help to know how to convert the XML file to Excel so you can easily work with the data and analyze it.

In this tutorial, I will show you two really simple ways to import an XML file into Excel using Power Query.

What is an XML File?

XML stands for Extensible Markup Language. An XML file can hold data in a format that can easily be read by apps and systems.

But it’s not as easy to read for humans, which is why we may have to transform it into a format that’s easier to use.

If it contains a lot of text data, then you can use a text editor to read the XML file, and if it contains data, then you can import that XML file into Excel and then work with the data.

XML is quite widely accepted as a file format to store and transmit data over the web.

A lot of popular file formats, such as Microsoft Office Open XML, LibreOffice, OpenDocument, XHTML, and SVG, also use the XML file format.

Most popular websites on the Internet have their sitemap in an XML format.

This is a file that contains the details of all the important pages and categories on a website. Here is an example of the sitemap from Forbes.

Now let’s see how to convert an XML file to Excel using Power Query.

Import XML File to Excel

If you already have an XML file (either downloaded on your system or a link to it on the web), you can easily convert it into data in an Excel file.

Thanks to Power Query (now called ‘Get & Transform’)

Import XML File that is Saved On your System

For the purpose of this tutorial, I’ll use an XML file that contains the sitemap for Forbes. You can download the file by going to this link, then right-click and save the file.

Once you have the XML file on your system, follow the below steps to get the XML file data into Excel:

  1. Open the Excel file where you want to get the data from the XML file
  2. Click the Data tabData tab in the ribbon in Excel
  3. In the ‘Get & Transform’ data group, click on the ‘Get Data’ optionClick on the Get Data drop down
  4. Go to the ‘From file’ option
  5. Click on ‘From XML’Click on From XML option
  6. In the input data dialog box that opens up, locate the XML file that you want to import and select it
  7. Click Import. This will import the XML file into power query and open the Navigator dialog box
  8. Select the data from the XML file that you want to import. In this case, I would click on ‘sitemap’ in the left paneClick on the Sitemap option in the left pane
  9. [Optional] Click on the Transform Data button, if you want to transform the data before loading it into Excel (such as change the column names or remove some columns)
  10. Click on Load

The above steps would insert a new worksheet in the Excel file, and load all the data from the XML file into the new worksheet.

XML data in the Excel file

The great thing about using Power Query to fetch the data from an XML file into Excel is that in case the XML file updates and there are new records in it, you don’t have to repeat the same process.

You can simply right-click on any cell in the table and refresh the query.

Click on Refresh

Import XML File into Excel using the web URL

In the above example, we first downloaded the XML file on the system and then imported the data into Excel.

In case you have a web URL that contains the XML file (such as this one – https://www.forbes.com/sitemap_index.xml), you don’t even need to download the file. you can connect Power Query to that URL and extract the XML data into Excel.

Below are the steps to connect power query do a web URL that contains the XML data and import that data into Excel:

  1. Open the Excel file where you want to import the data
  2. Click the Data tabData tab in the ribbon in Excel
  3. In the Get & Transform group, click on the ‘Get Data’ optionClick on the Get Data drop down
  4. Go to the ‘From Other Sources’ option
  5. Click on ‘From Web’Click on from Web
  6. In the ‘From Web’ dialog box, copy and paste the URL that has the XML dataEnter the URL from which you want to get the XML data
  7. Click OK. This will open the Navigator dialog box where you can choose which XML data to import
  8. Click on ‘sitemap’, which is the XML data that I want in ExcelSitemap in the left pane navigator
  9. [Optional] Click on the Transform Data button, if you want to transform the data before loading it into Excel (such as change the column names or remove some columns)
  10. Click on Load

The above steps would insert a new worksheet in the Excel file, and load all the data from the XML file into the new worksheet.

And again, in case the data updates in this URL, simply refresh the query to get the new data in Excel.

So these are two simple ways that you can use to convert an XML file into Excel.

If you have the XML file on your system, you can import the data easily using Power Query. And if you have a web URL of the XML file, then you can also fetch that data into Excel.

I hope you found this tutorial useful.

Other Excel tutorials you may also like:

  • 8 Ways to Reduce Excel File Size (that actually work)
  • How to Automatically Open Specific Excel File on Startup
  • How to Recover Unsaved Excel Files [All Options + Precautions]
  • Microsoft Excel Won’t Open – How to Fix it! (6 Possible Solutions)
  • How to Convert Excel to PDF Using VBA
  • Split Each Excel Sheet Into Separate Files (Step-by-Step)
  • Combine Data from Multiple Workbooks in Excel (using Power Query)

XML stands for eXtensible Markup Language and is a common data storage and transmission format. It’s widely used across the web and in many apps and software.

It’s a great data structure for computers to read, but it’s a bit less accessible for a human to read.

In this post we’ll take a look at how to import an XML file into Excel and turn it into a more friendly table format. Excel has support for XML files and it’s actually really easy to import and covert them to tables using power query.

You can download the example files used in this post here.

Video Tutorial

XML File Examples

You don’t need to look very far to find an example, Excel files are really just a collection of XML files in a zip folder.

Try it for yourself by taking any Excel file and changing the extension from .xlsx to .zip and then exploring the files in the zip folder. You’ll see a ton of XML files. You can open any of the XML files in your text editor of choice to view the inner workings of an Excel file.

Another common example can be found across the web. Most websites have a sitemap.xml file which is an XML file of the website’s link structure. This is literally a map of the website for bots like Google to crawl and index.

Check out the XML sitemap on one of my favourite Excel sites, https://www.vertex42.com/sitemaps/pages.xml. It lists all the pages on the site and includes information about when the page was last updated, how often the page is updated and how much weight search engines should give that page.

Create an XML Query

In this example we will use a simple XML file containing mock contact information with names, emails, cities and countries.

We can quickly create a new query that imports the XML file into Excel.

  1. Go to the Data tab in the ribbon.
  2. Select Get Data found in the Get & Transform Data section.
  3. Choose From File.
  4. Choose From XML.

This will open a file selection window and we can navigate to the location of the XML file and press the Import button.

Expand Fields in the Query Editor

The Navigator window will now open and we can see a preview of the data from the XML file. Notice that it’s in a nice table format? That’s automatically done by power query.

Since the Name and Email fields in the XML data contain sub-fields we see Table listed underneath the column headings in the preview. For example, the Name field contains a First and Last field for the first and last names of the person. If our data had a simple structure without any sub-fields, we could skip the query editor and press the Load button to directly load the data into the workbook.

To expand these tables out in the power query editor, press the Transform Data button.

In the query editor, click on the expand column toggle for the Name column which contains the Table elements. Choose the Expand option and press the OK button.

Repeat the process for the Email column as well. Depending on the data structure, we may need to do this several times.

Load the Data into a Table in the Workbook

Now our data is ready to be loaded into a table in the workbook.

Go to the Home tab in the query editor and press the the Close & Load button to load the data into a table in the workbook.

Conclusions

XML data is a very common format. You’re likely to come across it sooner or later if you work with data.

It can be hard to interpret what’s going on in an XML file, but luckily Excel can handle this type of data with ease.

In a few clicks, we can use power query to get our XML data into a nice table format.

About the Author

John MacDougall

John is a Microsoft MVP and qualified actuary with over 15 years of experience. He has worked in a variety of industries, including insurance, ad tech, and most recently Power Platform consulting. He is a keen problem solver and has a passion for using technology to make businesses more efficient.

Трюк №95. Загрузка документа XML в Excel

Если кто-либо пришлет файл XML, содержащий данные в таблицах, вам не придется читать весь текст и все угловые скобки с тегами. Можно загрузить этот документ напрямую в Excel, сообщить Excel, как следует отобразить этот документ, и работать с данными при помощи карт.

В последние несколько лет язык XML (Extensible Markup Language, букв, «расширяемый язык разметки») стал распространенным форматом обмена информацией, и нет ничего необычного в том, что люди и организации отправляют друг другу файлы XML. Простые структуры, лежащие в основе XML, делают обмен информацией чрезвычайно простым, причем неважно, используют ли все стороны одно и то же программное обеспечение и браузеры. Однако до недавних пор, хотя общие утилиты XML стали широко распространены, заполнить пробел между документами XML и пользовательским интерфейсом было еще достаточно трудно. Microsoft Excel упрощает эту задачу, по крайней мере, для данных в сетке таблицы.

В этом трюке используются возможности Excel, доступные только в Excel для Windows старше 2003 года. Более ранние версии Excel не поддерживают их; эти возможности не поддерживаются и в существующих, и планируемых версиях Excel для Macintosh.

Начнем с простого документа XML, приведенного в листинге 8.1.

// Листинг 8.1. Простой документ XML для анализа в Excel 2003-10-05 0596005385 Off1ce 2003 XML Essentia1s

34.95 200 Zork’s Books

2003-10-05 0596002920 XML in a Nutshell. 2nd Edition

90 Zork’s Books 2003-10-05 0596002378 SAX2

300 Zork’s Books 2003-10-05 0596005385 Office 2003 XML Essentials

10 Books of Glory 2003-10-05 0596002920 XML in a Nutshell, 2nd Edition

25 Books of Glory 2003-10-07 0596002378 SAX2

5 Books of Glory 2003-10-18 0596002378 SAX2

15 Title Wave 2003-10-21 0596002920 XML in a Nutshell. 2nd Edition

15 Books for You

Этот документ можно открыть непосредственно в Excel командой Файл → Открыть (File → Open). Откроется диалоговое окно (рис. 8.1).

Рис. 8.1. Открытие файла XML в Excel

Если вы выберете переключатель XML-список (As an XML list), то увидите предупреждение, что Excel создаст собственную схему для этого документа, не имеющего схемы (рис. 8.2).

Рис. 8.2. Предупреждение Excel об отсутствии ссылок на схему

Щелкнув кнопку ОК, вы увидите, какой способ Excel выбрал для представления информации в открываемом документе в виде электронной таблицы (рис. 8.3). Обратите внимание, что Excel ожидает встретить формат даты, который используется для элемента даты, поэтому даты, импортированные как 2003-10-05, будут отображаться как 10/5/2003.

Рис. 8.3. Данные XML, представленные как XML-список в Excel

Теперь, когда документ загружен в Excel, обрабатывать данные можно так же, как любые другие данные в Excel, — вставлять их в формулы, создавать именованные диапазоны, строить диаграммы на основе содержимого и т. д. Чтобы помочь вам, в Excel предусмотрено несколько встроенных возможностей анализа данных.

Раскрывающиеся списки в заголовках столбцов позволяют выбирать способ сортировки данных (по умолчанию данные выводятся в том порядке, в котором они записаны в исходном документе). Можно также включить отображение строки итогов Итог (Total); для этого можно воспользоваться панелью инструментов Список (List) или щелкнуть правой кнопкой мыши в любом месте списка и в контекстном меню выбрать команду Список → Строка итогов (List → Total Row). Когда строка итогов появится, выбрать вид итоговой информации можно будет в раскрывающемся меню (рис. 8.4).

Рис. 8.4. Выбор итогов для списка XML в Excel

Данные можно обновить, добавив при этом в обновляемую область информацию из документа XML с такой же структурой. Если у вас есть еще один документ с такой структурой, можете щелкнуть список правой кнопкой мыши, в контекстном меню выбрать команду XML → Импорт (XML → Import) и выбрать второй документ. Кроме того, после редактирования данные можно экспортировать обратно в файл XML, щелкнув список правой кнопкой мыши и выбрав в контекстном меню команду XML → Экспорт (XML → Export). Это превращает Excel в очень удобный инструмент редактирования простых XML-документов с табличной структурой.

Если данные достаточно простые, вы чаще всего можете доверить Excel выбор способа представления содержимого файла и использовать предусмотренные настройки по умолчанию. Если же данные усложняются, особенно если они содержат даты или текст, который выглядит как числа, то вы, возможно, захотите использовать схемы XML, чтобы указать Excel, как следует читать данные и какие данные подойдут к данной карте. Для нашего документа XML-схема может выглядеть, как в листинге 8.2.

// Листинг 8.2. Схема для данных о продаже книг

Обратите внимание, что элемент date определен как дата, а элемент ISBN определен как строка, а не как целое число. Если вы начнете с открытия этой схемы, а не документа, то заставите Excel загружать документ, сохранив ведущий нуль в ISBN.

На этот раз вы создадите список до загрузки документа XML, начав с пустого рабочего листа. Вам понадобится открыть область задач Источник XML (XML Source). Если она еще не открыта, нажмите сочетание клавиш Ctrl+Fl. Затем в раскрывающемся списке вверху области задач выберите Источник XML (XML Source) и вы увидите что-то похожее на рис. 8.6.

Рис. 8.6. Область задач Источник XML

Чтобы загрузить схему, щелкните кнопку Карты XML (XML Maps). Откроется диалоговое окно Карты XML (XML Maps) (рис. 8.7).

Рис. 8.7. Диалоговое окно Карты XML

Щелкните кнопку Добавить (Add), чтобы открыть схему, и выберите схему (рис. 8.8). Если схема не ограничивает документы одним начальным элементом, появится диалоговое окно с просьбой выбрать корневой элемент. Так как документы в этом примере начинаются с элемента sales, выберите «sales».

Рис. 8.8. Выбор XML-схемы

Когда вы щелкнете кнопку ОК, появится предупреждение о возможных сложностях с интерпретацией схем. XML-схема (XML Schema) — это огромная спецификация, поддерживающая чрезвычайно много структур, не отвечающих способу восприятия информации в Excel, поэтому в Excel есть некоторые ограничения.

В диалоговом окне Карты XML (XML Maps) Excel сообщит, что схема была добавлена к электронной таблице. Если вы щелкнете кнопку ОК, то вернетесь в главное окно Excel и в области задач Источник XML (XML Source) появится диаграмма, отображающая структуру схемы. Теперь, когда у вас есть структура, можно создать список. Самый простой способ сделать это, особенно с небольшими документами, как наш, — перетащить значок sales на ячейку А1.

Теперь, обустроив дом для данных, нужно заселить его. Можно щелкнуть кнопку Импорт XML-данных (Import XML Data) на панели инструментов Список (List) или щелкнуть правой кнопкой мыши список и в контекстном меню выбрать кнопку XML → Импорт (XML → Import). Если вы выберете файл, который уже открывали ранее (в листинге 8.1), то увидите результат, как на рис. 8.3. Обратите внимание на добавление ведущих нулей к значениям, которые теперь являются текстовыми, как и должно быть.

Элементы можно перетаскивать и по отдельности, если вы хотите поменять их местами, или помещать разные фрагменты информации в разные места электронной таблицы.

Поддержка XML-карт и списков в Excel означает, что можно создавать электронные таблицы, работающие с данными, которые поступают в отдельных файлах, с большей гибкостью, чем это было с предыдущими форматами, например CSV (с разделителями-запятыми) или форматом с разделительной табуляцией.

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

Конвертация файлов XML в форматы Excel

XML является одним из самых распространенных форматов для хранения данных и обмена ими между различными приложениями. С данными работает и программа Microsoft Excel, поэтому очень актуальным является вопрос конвертации файлов из стандарта XML в форматы Excel. Выясним, как произвести эту процедуру различными способами.

Процесс конвертации

XML-файлы написаны на специальном языке разметки чем-то похожим на HTML веб-страниц. Поэтому у этих форматов довольно сходная структура. В то же время, Эксель – это в первую очередь программа, имеющая несколько «родных» форматов. Самые известные из них: Книга Excel (XLSX) и Книга Excel 97 – 2003 (XLS). Выясним основные способы конвертации файлов XML в эти форматы.

Способ 1: встроенный функционал Excel

Программа Excel отлично работает с файлами формата XML. Она может открывать их, изменять, создавать, сохранять. Поэтому самый простой вариант поставленной перед нами задачи — это открыть данный объект и сохранить его через интерфейс приложения в виде документов XLSX или XLS.

  1. Запускаем Эксель. Во вкладке «Файл» переходим по пункту «Открыть».

Активируется окно открытия документов. Переходим в директорию, где хранится нужный нам документ XML, выделяем его и жмем на кнопку «Открыть».

После того, как документ открыт через интерфейс Эксель, опять переходим во вкладку «Файл».

Открывается окно, похожее на окно для открытия, но с некоторыми отличиями. Теперь нам нужно сохранить файл. С помощью инструментов навигации переходим в директорию, где будет храниться преобразованный документ. Хотя можно его оставить и в текущей папке. В поле «Имя файла» при желании можно его переименовать, но это тоже не обязательно. Для нашей задачи основным является следующее поле – «Тип файла». Кликаем по этому полю.

Из предложенных вариантов выбираем Книга Excel или Книга Excel 97-2003. Первый из них более новый, второй – уже несколько устаревший.

  • После того, как выбор произведен, жмем на кнопку «Сохранить».
  • На этом процедура конвертации файла XML в формат Excel через интерфейс программы окончена.

    Способ 2: импорт данных

    Вышеописанный способ подходит только для файлов XML с самой простой структурой. Более сложные таблицы при конвертации таким способом могут быть переведены некорректно. Но, существует ещё один встроенный инструмент Excel, который поможет корректно произвести импорт данных. Он расположен в «Меню разработчика», которое по умолчанию отключено. Поэтому, прежде всего, его нужно активировать.

      Перейдя во вкладку «Файл», кликаем по пункту «Параметры».

    В окне параметров переходим в подраздел «Настройка ленты». В правой части окна ставим галочку около пункта «Разработчик». Жмем на кнопку «OK». Теперь нужная функция активирована, а соответствующая вкладка появилась на ленте.

    Переходим во вкладку «Разработчик». На ленте в блоке инструментов «XML» жмем на кнопку «Импорт».

    Открывается окно импорта. Переходим в директорию, где располагается нужный нам документ. Выбираем его и жмем на кнопку «Импорт».

    Далее может открыться диалоговое окно, в котором говорится, что выбранный файл не ссылается на схему. В нем будет предложено создать программе схему самостоятельно. В этом случае соглашаемся и жмем на кнопку «OK».

    Далее открывается следующее диалоговое окно. В нем предлагается определиться открывать таблицу в действующей книге или в новой. Так как мы запустили программу без открытия файла, то можем оставить данную настройку по умолчанию и продолжить работу с текущей книгой. Кроме того, это же окно предлагает определить координаты на листе, куда будет импортирована таблица. Можно вписать адрес вручную, но намного проще и удобнее просто кликнуть по ячейке на листе, которая станет верхним левым элементом таблицы. После того, как адрес занесен в поле диалогового окна, жмем на кнопку «OK».

    После этих действий таблица XML будет вставлена в окно программы. Для того чтобы сохранить файл в формате Excel кликаем по иконке в виде дискеты в верхнем левом углу окна.

  • Открывается окно сохранения, в котором нужно определить директорию, где будет храниться документ. Формат файла на этот раз будет уже предустановлен XLSX, но при желании вы можете раскрыть поле «Тип файла» и установить другой формат Эксель – XLS. После того, как настройки сохранения выставлены, хотя в данном случае они могут быть и оставленными по умолчанию, жмем на кнопку «Сохранить».
  • Таким образом, конвертация в нужном для нас направлении будет совершена с максимально корректным преобразованием данных.

    Способ 3: онлайн-конвертер

    Тем пользователям, у которых по какой-то причине не установлена на компьютере программа Эксель, но нуждающимся в срочном преобразовании файла из формата XML в EXCEL, можно воспользоваться одним из множества специализированных онлайн-сервисов для конвертации. Одним из наиболее удобных сайтов подобного типа является Convertio.

    1. Переходим на данный веб-ресурс с помощью любого браузера. На нем можно выбрать 5 способов загрузки конвертируемого файла:
      • С жесткого диска компьютера;
      • Из онлайн-хранилища Dropbox;
      • Из онлайн-хранилища Google Drive;
      • По ссылке из интернета.

    Так как в нашем случае документ размещен на ПК, то жмем на кнопку «С компьютера».

    Запускается окно открытия документа. Переходим в ту директорию, где он размещен. Кликаем по файлу и жмем на кнопку «Открыть».

    Существует также альтернативный вариант добавления файла на сервис. Для этого нужно просто перетянуть его название мышкой из Проводника Windows.
    Как видим, файл добавился на сервис и находится в состоянии «Подготовлено». Теперь нужно выбрать необходимый нам формат для конвертации. Кликаем по окошку рядом с буквой «В». Открывается список групп файлов. Выбираем «Документ». Далее открывается перечень форматов. Выбираем «XLS» или «XLSX».

  • После того, как наименование нужного расширения добавлено в окошко, жмем на большую красную кнопку «Преобразовать». После этого, документ будет преобразован и доступен для загрузки на этом ресурсе.
  • Данный вариант может послужить хорошей подстраховкой на случай неимения доступа к стандартным инструментам для переформатирования по данному направлению.

    Как видим, в самом Экселе есть встроенные инструменты, позволяющие преобразовать файл формата XML в один из «родных» форматов этой программы. Простейшие экземпляры можно легко конвертировать через обычную функцию «Сохранить как…». Для документов с более сложной структурой существует отдельная процедура преобразования через импорт. Те пользователи, которые по какой-либо причине не могут воспользоваться данными инструментами, имеют возможность выполнить задачу с помощью специализированных онлайн-сервисов для конвертации файлов.

    Отблагодарите автора, поделитесь статьей в социальных сетях.

    Экспорт Excel в XML и наоборот

    Вы можете конвертировать файл Excel в файл данных XML или наоборот. Это позволяет обмениваться информацией между различными приложениями. Для начала откройте вкладку Developer (Разработчик).

    Вот данные, которые мы хотим преобразовать в файл XML:

    Сперва создадим схему, основанную на исходных данных в формате XML. Схема определяет структуру XML-файла.

      Excel для этой цели не подойдёт, поэтому откройте, к примеру, Блокнот и вставьте следующие строки:

    Примечание: Теги названы по именам столбцов, но вы можете дать им любое название. Например, вместо – .

    1. Сохраните файл как schema.xml.
    2. Откройте книгу Excel.
    3. Кликните по Source (Источник) на вкладке Developer (Разработчик). Откроется XML панель задач.
    4. Чтобы добавить карту XML, нажмите кнопку XML Maps (XML карты).Появится диалоговое окно XML Maps (Карты XML).
    5. Нажмите Add (Добавить).
    6. Выберите schema.xml и дважды кликните ОК.
    7. Теперь просто перетащите 4 элемента из дерева в XML панели задач на лист (строка 1).
    8. Нажмите кнопку Export (Экспорт) в разделе XML на вкладке Developer (Разработчик).
    9. Сохраните файл и нажмите Enter.

    Это экономит немало времени!

    Примечание: Для импорта XML-файла откройте пустую книгу. На вкладке Developer (Разработчик) нажмите кнопку Import (Импорт) и выберите XML-файл.

    Собрать данные из XML файлов в Excel и экспортировать

    Microsoft Excel – удобный инструмент для организации и структурирования самых разнообразных данных. Он позволяет обрабатывать информацию разными методами, редактировать массивы данных.

    Рассмотрим возможности использования его для формирования и обработки файлов веб-приложений. На конкретном примере изучим основы работы с XML в Excel.

    Как создать XML-файл из Excel

    XML – стандарт файла для передачи данных в Сети. Excel поддерживает его экспорт и импорт.

    Рассмотрим создание XML-файла на примере производственного календаря.

    1. Сделаем таблицу, по которой нужно создать XML файл в Excel и заполним ее данными.
    2. Создадим и вставим карту XML с необходимой структурой документа.
    3. Экспортируем данные таблицы в XML формат.
    1. Наша таблица – производственный календарь.
    2. Создаем в любом текстовом редакторе (например, «Блокнот») желаемую карту XML структуры для генерации файла сохраним. В данном примере буде использовать следующую карту структуры:
  • Открываем инструмент «Разработчик». Диалоговое окно «Источник» на вкладке XML.
  • Если программа Excel не видит карт XML, их нужно добавить. Жмем «карты XML». И указываем путь к нашему файлу с выше указанной схемой карты созданной в текстовом редакторе.
  • Добавить ОК.
  • В правой колонке появляются элементы схемы. Их нужно перетащить на соответствующие названия столбцов таблицы.
  • Проверяем возможен ли экспорт.
  • Когда все элементы будут сопоставлены, щелкаем правой кнопкой мыши по любой ячейке в таблице – XML – экспорт.
  • Сохраняем в XML файл.

    Другие способы получения XML-данных (схемы):

    1. Скачать из базы данных, специализированного бизнес-приложения. Схемы могут предоставляться коммерческими сайтами, службами. Простые варианты находятся в открытом доступе.
    2. Использовать готовые образцы для проверки карт XML. В образцах – основные элементы, структура XML. Копируете – вставляете в программу «Блокнот» — сохраняете с нужным расширением.

    Как сохранить файл Excel в формате XML

    Один из вариантов:

    1. Нажимаем кнопку Office. Выбираем «Сохранить как» — «Другие форматы».
    2. Назначаем имя. Выбираем место сохранения и тип файла – XML.

    Если выдает ошибку, книгу можно сохранить в виде таблицы XML 2003 либо веб-страницы. С этими форматами проблем, как правило, не возникает.

    1. Скачать конвертер XLC в XML. Либо найти сервис, с помощью которого можно экспортировать файл онлайн.
    2. Скачать с официального сайта Microsoft надстройку XML Tools Add-in. Она в бесплатном доступе.
    3. Открываем новую книгу. Кнопка Office – «Открыть».

    Как открыть XML файл в Excel

    1. Меняем формат на «файлы XML». Выбираем нужный файл. Жмем «Открыть».
    2. Способ открытия – XML-таблица. ОК.
    3. Появляется оповещение типа

    Жмем ОК. С полученной таблицей можно работать, как с любым файлом Excel.

    Как преобразовать файл XML в Excel

    1. Меню «Разработчик» — вкладка «Импорт».
    2. В диалоговом окне выбираем файл XML, который хотим преобразовать.
    3. Нажимаем «Импорт». Программа Excel предложит самостоятельно создать схему на основе полученных данных. Соглашаемся – ОК. Откроется окно, где нужно выбрать место для импортируемого файла.
    4. Назначаем диапазон для импорта. Лучше брать с «запасом». Жмем ОК.

    Созданную таблицу редактируем и сохраняем уже в формате Excel.

    Как собрать данные из XML файлов в Excel

    Принцип сбора информации из нескольких XML-файлов такой же, как и принцип преобразования. Когда мы импортируем данные в Excel, одновременно передается карта XML. В эту же схему можно переносить и другие данные.

    Каждый новый файл будет привязываться к имеющейся карте. Каждому элементу в структуре таблицы соответствует элемент в карте. Допускается только одна привязка данных.

    Чтобы настроить параметры привязки, откройте в меню «Разработчик» инструмент «Свойства карты».

    1. Каждый новый файл будет проверяться программой Excel на соответствие установленной карте (если поставим галочку напротив этого пункта).
    2. Данные могут обновляться. Либо новая информация добавится в существующую таблицу (имеет смысл, если нужно собрать данные из похожих файлов).

    Это все ручные способы импорта и экспорта файлов.

    Excel «Из импорта данных XML» не будет добавлять новые столбцы

    В Excel 2010 имеется потрясающая функция «Данные из других источников» -> «Из импорта данных XML», позволяющая извлекать XML из веб-службы, кодирование не требуется. Прекрасно работает, но мой сервис добавил новую колонку в конце. Обновление соединения в Excel не добавляет новый столбец. Фактически, при создании второго соединения с точно таким же URL-адресом в той же электронной таблице новый столбец также не будет отображаться (хотя то же самое будет сделано в другой книге Excel). Очевидно, Excel как-то кеширует столбцы.

    Я нашел эту ссылку который описывает возможный обходной путь путем ручного взлома файла Excel; но это было 3 года назад. Конечно, сейчас есть лучший способ.

    Любой совет? Вы можете повторить это, просто сохранив следующий XML-файл в виде текстового файла, импортировав его в Excel, затем отредактировав файл и добавив новый столбец.

    Параметры:

    • вкладка «Разработчик Excel 2010» (см. вопрос Excel Добавить Поле для карты XML ) ( search )
    • Excel 2007 (возможно, другие). Похоже, что решение было разработано с использованием VBA на форуме. сообщение: Вопрос XML — схема обновления /Картография ( архив ) ( архив программно с использованием функции отображения XML страница, на которой размещаются ссылки ). Код VBA приведен ниже.
    • Excel 2003 Панель инструментов XML для Excel 2003
    • ALL: ниже представлен обходной путь, который не нарушает формулы.

    Я не пробовал код VBA из связанного поста на форуме и включен ниже. Я надеюсь, что это работает для вас. Тем не менее, обходной путь, представленный ниже, кажется простым и не нарушает формул, ссылающихся на данные внутри сопоставления. Таким образом, я бы использовал это, если только это не работает для вас, или если ваше отображение сложное, или вы ожидаете, что вам потребуется полуавтоматическое обновление несколько раз (хотя обходной путь ниже занимает очень мало времени).

    Официального решения для Excel 2007 не существует. Похоже, существует два отдельных официальных решения: одно для Excel 2003 (надстройка) и одно для Excel 2010 (вкладка «Разработчик»).

    Вопрос Excel Добавить поле в Xml Карта предлагает три метода, которые могут работать.

    • Первым был Набор инструментов XML для Excel 2003 который может сделать это в Excel 2003. Комментарий к этому решению указал, что у него есть некоторые проблемы /проблемы и могут или не могут быть функциональными для вас. Ты можешь приходится использовать более старую версию в Excel или даже более старую операционную система.
    • Второй метод — «отредактировать файл .xls».
    • Третий — использовать вкладку «Разработчик Excel 2010».
    • Обходной путь представлен ниже (возможно, я выбрал простые одноразовые обновления, которые не должны повторяться, а сопоставление простое).
    • Сохраните лист в виде электронной таблицы XML. Отредактируйте схему, записанную в конце файла. Учитывая, что это XML, он целиком в тексте. Схема проста для понимания. Добавить столбец так же просто, как просто скопировать и вставить (с изменениями) несколько строк XML-текста. При использовании этого метода, вероятно, проще всего сделать копию вашего рабочего листа, удалить и заново создать карту и карту, а затем вырезать и вставить. Пример XML:

    (SO-форматирование требует пустой текст)

    Обходной путь: [добавлены /вставлены /удалены столбцы (столбцы)] (легко для простых сопоставлений, например, одной большой таблицы):

    1. Сделайте резервную копию своего листа.
    2. Удалите карту XML . Не отображение на листе. Просто карта XML.
    3. Пересоздайте карту. Теперь у него будет новая XML-схема.
    4. Если у вас есть формула /данные, которые будут перезаписаны дополнительными столбцами: вставьте достаточно столбцов сразу справа от текущей области налист, который содержит сопоставленные данные XML.
    5. Если есть какие-либо столбцы, которые были вставлены между старыми столбцами, вставьте в лист столбец, куда они пойдут. Да, это верно в области сопоставленных данных XML, и общее имя столбца будет временно назначено.
    6. Удалите все столбцы, которые не существуют в новом XML.
    7. Перетащите элементы из новой сопоставленной таблицы в верхний левый угол текущего сопоставления (или иным образом воссоздайте сопоставление на листе непосредственно над сопоставлением, которое вы не удалили ) .
    8. Вручную измените все заголовки, которые были обновлены (если ваши данные были помечены как имеющие заголовки).
    9. Повторите шаги с 4 по 8 для всех отдельных сопоставлений, которые есть в вашей книге. Обычно у меня есть только одно большое сопоставление, на которое я ссылаюсь, а не несколько маленьких сопоставлений.
    10. Обновите данные XML.

    Ваши формулы не должны были изменяться, и ссылки на ячейки в отображенных данных XML должны оставаться правильными. Чтобы убедиться, что вы правильно вставили все столбцы на шаге 3, перед внесением любых других изменений (т. Е. На шаге 1a) вы можете создать строку над сопоставлением XML, скопировать и вставить только значения из верхней строки. Обновив данные XML на шаге 10, вы можете убедиться, что старые заголовки строк соответствуют новому месту размещения.

    Примечание. Шаги 3 и 4 можно поочередно выполнить, сделав более сложное отображение элементов XML. Мне проще вставлять столбцы и сохранять соответствие 1-1 с элементами XMl.

    Это работало на моей машине через несколько испытаний и оставило формулы, ссылающиеся на область, как правильные. Файл, в котором вы можете экспериментировать, называется SO-XML mapping.xml и включен в приведенный ниже пример файла ( и здесь). )

    Учет общих изменений столбцов в некоторых таблицах данных, полученных из источника (или с использованием нескольких источников взаимозаменяемо):

    Бывают случаи, когда имеющиеся у вас данные не предоставляются динамически чем-то вроде карты XML или когда вы не хотите суетиться, вспоминая вставленные столбцы. Обходным путем для решения этой проблемы является создание собственного сопоставления столбцов данных в таблице (листе) на рабочем листе, в которой вы контролируете расположение столбцов. Вы можете сделать это, создав таблицу, которая косвенно ссылается на данные, которые вы импортировали /скопировали на другой лист. использование косвенного отображения, подобного этому, также может использоваться для простого переключения между двумя или более различными наборами данных в качестве входных данных для любых установленных вами формул.

    При косвенном сопоставлении используется INDIRECT() для ссылки на лист, содержащий исходные данные. Все ваши формулы затем указывают на этот косвенный лист вместо исходных данных. Содержимое столбцов в косвенном листе организовано в фиксированных местоположениях с данными, извлеченными из столбца в исходных данных, который соответствует указанному заголовку столбца. Затем, если внесены изменения в организацию столбцов в исходных данных, вы можете просто создать новый лист с альтернативно отформатированными данными или поместить его на лист, где были исходные данные, и изменить заголовки столбцов, которыми вы являетесь. используя для ссылки. Если вы переключаетесь между несколькими наборами данных, вы можете полностью изменить исходные данные, используя одну ячейку.

    Этот лист косвенного сопоставления позволяет фиксировать столбцы в ваших формулах (за пределами косвенного листа) вместо того, чтобы беспокоиться о возможной реорганизации исходных данных. Кроме того, он позволяет вам иметь два или более набора данных, которые автоматически переключаются в одну и ту же организацию столбцов при переключении между ними. Вы можете сделать это, даже если наборы данных имеют разные заголовки, используемые для одних и тех же фактических данных (просто есть строка заголовков, которая используется, когда альтернативный набор (ы) данныхвыбран (ы).

    Это, вероятно, легче показать, чем объяснить в посте, подобном этому. Таким образом, вот пример, который выбирает данные из пяти различных листов .

    В этом примере все ваши формулы будут ссылаться на косвенную страницу. В этом примере предполагается, что все файлы находятся в каталоге C: . К сожалению, для использования сопоставлений XML требуется полный путь к файлу, а C: — это место с наибольшей вероятностью на большинстве компьютеров с Excel.

    VBA-код от KMKfan 16 ноября 2009 г .:

    Комментарий в посте был:

    Вот обновление для этого кода. Этот код допускает несколько XML карты для обновления в той же книге, что и карты xsd и xml имеют одно и то же имя (то есть: исходная карта «MyMap» основана на MyMap.xsd. Должно быть очень полезно, если вы используете XML для отчетности и решите добавить часть данных для захвата. Вы можете обновить существующий сопоставление автоматически и нужно только вручную обновить новые данные элементы.

    Выделите импортированные данные и удалите заполненные строки. Затем выберите ячейку, в которую хотите вставить данные, и заново создайте соединение, перейдя в «Данные» -> Из импорта данных XML. Когда он воссоздает соединение, он должен добавить ваш дополнительный столбец. (Если вы попытаетесь обновить таблицу данных, которая в данный момент существует, она не добавит ваш столбец.)

    What Is Excel Open XML File?

    With Excel data, we can convert the data into XML format.

    Data is the most important part of making decisions but it is important to know how we can import data from different sources. The source file varies from one situation to another.

    We are familiar with common file extensions: “Text file and Excel file.” But several other sources are also available. This article will show us how to open Excel data into XML format and import XML data into Excel with neat formatting.

    Table of contents
    • What Is Excel Open XML File?
      • What Is XML File?
      • Example Of Converting Excel Data To XML File Format
      • Import XML Data Into Excel
      • Important Things To Note
      • Frequently Asked Questions (FAQs)
      • Recommended Articles
    • XML stands for eXtensible Markup Language. It is a language that can be read only by computers.
    • The XML files follow a certain script, so we need to follow a mandatory line of codes.
    • When we open our XML file, it will open with TEXT File only, but remember, the format will be in XML Schema.
    • We need to create at least two schema examples to apply the same logic to the whole data and export it as an XML file.

    What Is XML File?

    EXtensible Markup Language of storing data in the XML format. Like all the other external database rules, XML, too, has its own standard set of actions.

    The following are the rules of the XML file:

    • The first line of the data should always include the below line of code.
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    • XML format has the head and tail of the table name.
    <TableName>
    
              Column1<Value>Column1
    
              Column2<Value>Column2
    
    <TableName>
    
    <TableName>
    
              Column1<Value>Column1
    
              Column2<Value>Column2
    
    <TableName>
    
    

    Like this, we can create an XML table to convert the excel data into an XML table format. Now we will see how to open excel data into XML format.

    Example Of Converting Excel Data To XML File Format

    For example, look at the below data in the Excel worksheet.

    First_Name Last_Name City Country
    James Butt New Orleans Orleans
    Josephine Darakjy Brighton Livingston
    Art Venere Bridgeport Gloucester
    Lenna Paprocki Anchorage Anchorage
    Donette Foller Hamilton Butler
    Simona Morasca Ashland Ashland
    Mitsue Tollner Chicago Cook
    Loeta Dilliard San Jose Santa Clara
    Sage Wieser Sioux Falls Minnehaha
    Kris Marrier Baltimore Baltimore City
    Minna Amigon Kulpsville Montgomery
    Abel Maclead Middle Island Suffolk

    We need to convert this into an XML excel formatExcel has made it very easy for us to import the data in XML to excel in the form of tables or databases. XML is basically an external data and it can be imported to excel from the data tab under the «get external data tab from data from other sources» section.read more like the below one.

    Excel open xml Example 1-1

    Here, we need to create two sample lines formatting for our data. As we have discussed, our rules for creating a mandatory line of code are below.

    <?xml version=”1.0″ encoding=”UTF-8″?>

    <dataset>

    Next, we need to enter the table name as per our wish, and the table name is <EmpRecord>

    After the table name, we need to enter the column header name, <FirstName> next; we need to include the name and end this with the column header again.

    Like this, we need to prepare a schema of XML data. For the above data, we have created the schema. Then, we can copy and paste the schema.

    <?xml version="1.0" encoding="UTF-8"?> 
    
    <dataset>
    
             <EmpRecord>
    
    <FirstName>James</FirstName>
    
    <LastName>Butt</LastName>
    
    <City>New Orleans</City>
    
    <Country>Orleans</Country>
    
             </EmpRecord>
    
             <EmpRecord>
    
    <FirstName>Josephine</FirstName>
    
    <LastName>Darakjy</LastName>
    
    <City>Brighton</City>
    
    <Country>Livingston</Country>
    
            </EmpRecord>
    
    </dataset>
    
    

    We have created two samples. So, by using this, we can apply the same schema to our Excel file and extract data in the same format (XML) as provided above.

    We must copy the above code to a text file and save the file as “XML.”

    Excel open xml Example 1-2

    We must follow the below steps to open the Excel data into XML format.

    • Step 1: In the data workbook, we must go to the “Developer” tab and click on “Source.”

    Excel open xml Example 1-3

    • Step 2: This will open up below the “XML Source” window to the right of the worksheet, and click on “XML Maps.”

    Excel open xml Example 1-4

    • Step 3: This will open up the “XML Maps” window, then click on the “Add” button to choose the XML schema file.

    Excel open xml Example 1-5

    • Step 4: Now, choose the already saved XML file with the schema.

    Excel open xml Example 1-6

    • Step 5: Click on “Open.” It will ask for our confirmation.

    Excel open xml Example 1-7

    • Step 6: We need to click on “OK” two more times to get the schema headers to the left.

    Excel open xml Example 1-8

    • Step 7: Now, drag and drop the first column header “FirstName” from the XML source to the actual table in the worksheet.

    Excel open xml Example 1-9

    As a result, this will apply the “FirstName” column schema to the data table column.

    Excel open xml Example 1-10

    Now, we must repeat the same for the remaining columns. Drag and drop respective schema columns to individual columns of the data table.

    Excel open xml Example 1-11

    So, all the XML schema columns are applied. Then, under the “Developer” tab excelEnabling the developer tab in excel can help the user perform various functions for VBA, Macros and Add-ins like importing and exporting XML, designing forms, etc. This tab is disabled by default on excel; thus, the user needs to enable it first from the options menu.read more, click on the “Export” option.

    Developer Example 1-12

    It will ask us to save the file in the desired folder. We must give it a name and save it.

    Export Example 1-13

    After choosing the folder, we must click on “Export.” The data will be extracted as the “XML Data” file.

    Now open the file, and all the rows are in the XML format.

    Notepad Example 1-14

    Like this, we can extract or open the Excel data to the XML file.

    Import XML Data Into Excel

    IImporting an XML file to Excel requires following certain steps. First, follow the below steps to import data from an XML file.

    1. Firstly, under the “Data” tab, we must click on “Get Data” → “From File” and choose “From XML.”

      Excel open xml Example 1-15

    2. Consequently, this will ask to choose the file from the stored location. Therefore, we need to select the file.

      Excel open xml Example 2

    3. Click on “Import.” It will import the data to an Excel file.

      Excel open xml Example 1-16
      Like this, we can work with “XML files” in Excel.

    Important Things To Note

    • XML language is a computer language but it is not read by humans.
    • XML stands for eXtensible Markup Language.
    • We can import XML files in excel using the Import option under the Data tab.

    Frequently Asked Questions (FAQs)

    1. What is XML file?

    XML, eXtensible Markup Language is a language read by computer to define text. XML is just like HTML. We can import XML files in excel.

    2. How to import XML file in excel?

    We can easily open XML file in excel using the below steps:

    • Step 1: Go to Data → Get Data → From File → From XML

    • Step 2: The Import Data window opens.

    • Step 3: Select the file and click Import.

    The XML file will be imported.

    3. What are some important points to remember while using XML in excel?

    While using XML in excel, it is important to know that
    XML has mandatory code lines.
    Whenever we import XML file, it will open with TEXT File only, but the format is in XML Schema.

    Recommended Articles

    This article has been a guide to Excel Open XML File. Here, we discuss exporting Excel data into XML format and importing XML data into Excel. You may learn more about Excel from the following articles: –

    • MS Excel Uses
    • Connections in Power BI
    • Repair in Excel
    • ENVIRON in VBA

    XML is a common file type for storing and transferring data. In this article, we are going to show you how to import XML files into Excel using two methods: First is a more «direct method» and the other is the Power Query approach.

    Download Workbook

    Let take a closer look at how you can import XML files into Excel.

    Direct importing

    This method works in Excel versions 2007 or newer. You need to make the Developer tab visible in the Ribbon to use this feature. The XML section in the Developer menu allows you to import, export and manage the XML files.

    How to import XML files into Excel 01

    Once the Developer tab is enabled, click the Import button in the XML section. Select your XML file in the File dialog, and click Import.

    If you have not defined a schema beforehand, Excel will give you a warning and offer to create one for you.

    How to import XML files into Excel 02

    If you do not have a schema file listed with the XSD extension, click the OK button to let Excel do this. If, for some reason Excel fails at this step, try the other approach below.

    Next, Excel will ask you where you want to import the workbook. You can select either a cell in an existing worksheet or create a new one.

    How to import XML files into Excel 03

    Clicking the OK button completes the importing process. Once the XML is imported, you can manage it from the same section, and update the data if the resource file is changed. Refresh (update) buttons can be found under both the Data or Table Design tabs of the Ribbon, as well as the right-click menu of the table.

    How to import XML files into Excel 04

    Importing XML files by using Power Query

    Power Query is a powerful tool for importing and querying data, supported in Excel versions 2010 or newer. If you are using the 2010 or 2013 versions, you can download it as an add-in. Excel has implemented this feature into the base version starting with the 2016 version.

    1. If you’re using Excel with a Microsoft 365 subscription, follow Data > Get Data > From File > From XML.
      If you’re using Excel 2013 or earlier, follow Power Query > From File > From XML.
      How to import XML files into Excel 05
    2. Select your file under Import Data and click Import.
    3. Navigator displays a preview of your XML
    4. If you are satisfied with the preview, click the Load button to import the data.
      If you want to query data before adding into your spreadsheet, click Transform Data to open Power Query window.
      How to import XML files into Excel 06

    You can access Power Query window any time by right-clicking the query in the Queries & Connections pane.

    How to import XML files into Excel 07

    Convert XML Files to Excel – 5 Methods to Import

    To Import XML data to Excel you can use any of these listed methods.

    1. VBA to import XML to Excel
      1. Quick VBA to Convert XML into Excel
      2. VBA to read each nodes in XML
      3. VBA to Import XML from any website
    2. Directly Open XML in Excel.
    3. Data Import to Convert XML to XLSX

    Lets review one by one & get free Excel macro code also to do this.

    1. VBA Read XML file into Excel

    1.1 Quick VBA To Convert XML to Excel

    This methods import and open XML file in Excel from local path, but it is slightly different from the previous methods.

    This does a plain import in quick way.

    Public Sub Convert_XML_To_Excel_From_Local_Path()
        Dim xml_File_Path As String
        Dim wb As Workbook
        
        'Load XML Data into a New Workbook - Code from Officetricks.com
        Application.DisplayAlerts = False
         xml_File_Path = ThisWorkbook.Sheets(1).Cells(2, 1)
         Set wb = Workbooks.OpenXML(Filename:=xml_File_Path)
    
        'Copy Content from New workbook to current active Worksheet
         wb.Sheets(1).UsedRange.Copy ThisWorkbook.Sheets("Sheet2").Range("A1")
         
         'Close New Workbook & Enable Alerts
         wb.Close False
         Application.DisplayAlerts = True
    End Sub

    1.2 Advanced method to Read each node in XML file using VBA

    This VBA code will import XML to Excel by reading each element or node in it, using object model.

    If it is not just an plain import & you want to process each XML node in code, then this is the most preferred method.

    Public Sub Convert_XML_To_Excel_Through_VBA()
        'Code from Officetricks.com
        'Add referece from Menu: "Tools -> References -> Microsoft XML Vn.0"
        Dim iRow As Integer, iCol As Integer
        Dim xmlDoc As MSXML2.DOMDocument, xmlRoot As MSXML2.IXMLDOMNode
        Dim xmlNodes As MSXML2.IXMLDOMNode, xmlData As MSXML2.IXMLDOMNode
        Set xmlDoc = New MSXML2.DOMDocument
        
        'Load & Wait till complete XML Data is loaded
        xmlDoc.async = False
        xmlDoc.validateOnParse = False
        xmlDoc.Load ("D:sitemap.xml")
        
        'XML Loaded. Now Read Elements One by One into XML DOM Objects
        Set xmlRoot = xmlDoc.DocumentElement
        Set xmlNodes = xmlRoot.FirstChild
        
        'Read XML Data and Load into Excel Sheet by each Node and Chile Node
        iRow = 0
        For Each xmlNodes In xmlRoot.ChildNodes
            iRow = iRow + 1
            iCol = 0
            
            For Each xmlData In xmlNodes.ChildNodes
                iCol = iCol + 1
                ThisWorkbook.Sheets(2).Cells(1, iCol) = xmlData.BaseName
                ThisWorkbook.Sheets(2).Cells(iRow, iCol) = xmlData.Text
            Next xmlData
        Next xmlNodes
    End Sub

    Before executing the code above, just change the path of the input file in the line, xmlDoc.Load.

    By this method, you will be able to import multiple XML  files into Excel.

    1.3 Import XML into Excel using VBA from Website

    The above method is used to load data from a local file. Use the below method if you have to import XML data to Excel from a website URL directly.

    Public Sub Import_XML_From_URL()
        'Clear & Setup Output Sheet - Code from Officetricks.com
        ThisWorkbook.Sheets(2).Activate
        ThisWorkbook.Sheets(2).Cells.Select
        Selection.ClearContents
        
        'Switch Off Alert Messages while Importing.
        Application.DisplayAlerts = False
        
        'VBA Command To Import XML File from Website to Excel
        ThisWorkbook.XmlImport URL:="XML_File_Download_URL", ImportMap:= _
            Nothing, Overwrite:=True, Destination:=ThisWorkbook.Sheets(2).Range("$A$1")
        
        Application.DisplayAlerts = True
    End Sub

    All the methods discussed above can be used to automate the process of converting XML to Excel file from a local computer or from a Website URL.

    To convert XML file to Excel using menu options, follow these simple steps.

    1. Open a Excel workbook (xls or xlsx).
    2. Click ‘File’ menu & choose ‘Open’ (shortcut – ‘Alt+F+O’).
    3. Browse folder path & choose XML file.
    4. Click ‘Open’ or press ‘Enter’.
    5. Choose ‘As an XML table’ in popup menu & click ‘OK’.
    6. Click ‘OK’ when Excel notify that a schema will be created based on XML source data.

    Now, the system will import XML to Excel in active worksheet.

    But, wait. We do have more easy methods & even few VBA codes do perform this task.

    3. Data Import XML to Excel – Menu Option

    To view XML in proper readable format, you can open XML files in Excel using the “Data Import” feature as explained below.

    1. Click ‘Data’ menu & choose ‘From Other Sources’ (shortcut – ‘Alt+A+F+O’)
    2. Select “From XML Data Import”.
    3. Choose XML path and file in ‘Select Data Source’ window.
    4. Excel will notify about schema creation by itself. Click OK.
    5. Choose target cell address to import XML data.
    6. Click ‘OK’.

    Usually in manual options, Excel itself will guide you to further steps to import XML to Excel. These option are built in options of Microsoft XML converter.

    It is also possible to import data in XML to Excel through macro Code. We have explained 3 different methods in this article to this through VBA.

    View XML Maps – Data mapping using Excel

    Excel will create a schema by itself once your import XML into Excel. To view the XML maps added to the Excel workbook, follow these steps.

    1. Right click on imported XML table.
    2. Select ‘XML’ in the popup menu & choose “XML Source”.
    3. Sidebar on right hand side will appear with source details.
    4. Edit Map field details in this sidebar.
    5. Click on  ‘XML Maps’ to view list of maps linked.
    6. Rename, Add, Delete, Assign map schema details in this window.

    The same option is also available in Developer Tab “Document Panel” from the Excel Menu. Use this option to assign a new schema or map to the imported XML file.

    Note: Similar to editing importing XML, you can create a XML file from Excel directly, by saving it in XML format, right from the ‘File’ menu ‘Save As’ Option.

    Import Sitemap to Excel

    Bloggers, Web Admin, SEO & Marketing people scan through sitemaps from lot of websites to improve the performance of their pages in search engine result pages. They can use the techniques in this page to import Sitemap from a Website and process all the links within that Domain.

    We have completed few quick steps about Extensible Markup Language or XML to Excel converter. This file format is used to exchange data between computer applications across Internet, LAN or  apps within same Computer.

    This file can be opened in any Internet browsers (Firefox, Chrome, IE, Opera etc.,) or a Text editor directly to view it’s content since it is not a encoded format. But, to view it in a readable format, this article will help more.

    Other Reference: Microsoft Answers on Importing XML data

    By this, you can create your own Excel XML viewer. We have summarized 2 manual methods & 3 different methods using VBA. Be it on-demand process or automation, this complete guide about converting a XML file to Excel will be a handy quick reference.

    XML in Excel

    XML in Excel (Table of Contents)

    • Definition of XML & XSD
    • How to Import XML File in Excel?

    Introduction to Extensible Markup Language (.XML)

    Designed for storing and transporting data. It is a markup language similar to HTML. XML File appears as below mentioned, where it is a note to John from Craig.

    XML File type & structure appears as below mentioned:

    <note>
    <to> John</to>
    <from> Craig</from>
    <heading>Reminder</heading>
    <body>Don’t forget me this weekend!</body>
    </note>

    • XML is just a piece of information wrapped in tags, just like the above-mentioned note.
    • Usually, most of the XML applications work as expected even if you add new data (or it is removed).
    • XML Simplifies tasks like data transport, data sharing, data availability & platform changes.
    • The XML standard is a flexible & easy way to create information formats.
    • XML helps out in electronically sharing structured data via the public Internet or through a corporate network.
    • XML is a hierarchical structure.

    Definition of XML & XSD

    • XML Schema language is also referred to as XML Schema Definition (XSD).
    • XSD defines the structure of the XML file, which needs to be created and also it indicates where the columns need to be mapped in the tabular excel data.
    • It is also referred to as Extensible Stylesheet Language Transformation (XSLT) or (.xslt file).
    • XSD implement data type and validation to file.
    • XSD allows you to create elements, Data relationships & Data validation is defined in XML.
    • XML data files (.xml), which contains custom tags and structured data.

    How to Import XML File in Excel?

    You can import the XML file in Excel from the source option in the Developer tab. If the Developer tab is not available in the Ribbon, you need to add the developer tab with the mentioned steps or procedure.

    Go to “File” and select “Options.” and select “Customize the Ribbon”, or you can right-click on the Home tab and select “Customize Ribbon”, as shown below.

    In Excel Options –

    Excel Options -XML

    When you return to the main Excel page, you will see the Developer tab next to the view tab at the top. In that, if you need to select the source tool to map elements in your XML to your spreadsheet.

    Developer Tab -XML

    Let’s check out the steps available to convert an excel file to an XML data file & vice versa.

    Step 1 – To Convert your Spreadsheet into XML, you need a Markup Schema

    This markup schema defines each field that you’ll use in your XML file, i.e. the structure of the XML file. We have to do this outside Excel, in the other filetype.

    In the below-mentioned spreadsheet, I have four types of column & information, i.e. Car makes, Car model, its year of manufacture, and at last, Car cost or value. So, in our Excel schema will have four different tags, and we need to create them.

    XML Spreadsheet

    In the above spreadsheet, it contains four columns, each of which will become an element. The car data in the above cells of excel are not independent. For example, I have four cells in a row; all that row data is related to each other, it provides details about a car type and its information, i.e., the brand name, model name, and year of purchase it is cost or value at present.

    Open Notepad and add the following two lines; they are the standard pieces of information that XML files need at the beginning. (Note: It is optional ).

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <data-set xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    Notepad - Codes

    The element is declared from line three onwards. The record tags, i.e. < >, defines a single record described in our spreadsheet. Whereas other tags define the relevant pieces of information under that for that record. i.e.

    <record>
    <Make>Toyota</Make>
    <Model>Fortuner</Model>
    <Year>2010</Year>
    <Value>949999</Value>
    </record>

    Finally, add the closing </record> tag at the end of the file in the note pad.

    NOTE: The tags (< >) in the above notepad under the record refers to the column names; you have an option to give them any name you want apart from the original name mentioned in the excel tabular data! For example, instead of ‘’Value”, you can use “Cost”.

    I just added the first-row data for the explanation purpose. You can add as many rows, based on your choice. Again, you can start with <record>, after the </record> tag. Once you entered the data in the notepad, you can save it as test.xml in the file name and save it on the desktop.

    Save File name

    Later, you can create a new excel file with filename XML.xlsx

    As you have noticed, we entered one car detail (one record) in the XML file (NOTEPAD). Now, you have created a markup schema and saved it on your desktop.

    Step 2 – How to Add this Markup Schema to New Excel File

    In the Developer tab, click on Source in the XML section.

    XML 5

    XML window pane appears; click on XML Maps.

     XML Source

    XML Maps window appears; in that, Click Add in the resulting window.

    XML Maps

    Then you can navigate to your XML file on the desktop, which you saved as Abc.xml, and you can select it.

    Select XML Source

    Due to excel version issues in my system, I am uploading other .xml file with another option. The other option in the developer tab is to select Import in the Home tab.

    Import XML file

    Once you select a .xml file on the desktop, a popup appears; click Ok.

    Excel Schema

    Now to import this excel data, right-click on the XML file name and select the MAP Element option.

    Map Element

    Then you will see the following popup, select the location to where you want your data.

    XML Source 1

    Then you will see the table headers in your excel sheet.

    XML 7

    Now under the developer tab, click on Import.

    developer import

    It will open a window to select the file.

    Import XML file 1

    Output:

    ABCD

    Another popup appears asking for cell reference, where you want the data to be placed.

    import data 1

    The import .xml file type appears as shown earlier. Similarly, the Export feature in the developer option will be available in your spreadsheet contains XML file data; otherwise, an export option will be greyed out.

    Export File 2

    Here, I opened an excel file containing XML file data; I can export it and save it as a .xml file type anywhere with an export option in the Developer tab.

    Export File 1

    Things to Remember About XML in Excel

    • Every bit of data you enter has to start and end with an identical tag, i.e. start with < Record> Data </Record> (End with).
    • Tag names are case sensitive, i.e. capitalization in the end tag should be the same as the beginning tag.
    • The XML file should always begin and end with a root tag. There can only be one root tag in a file. In the example above, the root tag is <Record>.
    • You can have an empty tag, i.e. you can mention or put the slash at the end of the tag instead of the beginning: <Record> </Record>.

     Recommended Articles

    This is a guide to XML in Excel. Here we discuss How to Import & Export XML Data files along with practical examples and downloadable excel template. You can also go through our other suggested articles –

    1. Database Function in Excel
    2. Excel Hacks
    3. Excel Import Data
    4. Power Query in Excel

    Data is the bloodstream of any business entity. Businesses use different programs and formats to save the data depending on the business data storage requirements. You could have a payroll program powered by a database engine, you could have data in a CSV file or even from a website that you would like to analyse in Excel. This article shows you how you can achieve the above.

    What is external data source?

    External data is data that you link/import into excel from a source that resides outside excel.

    Examples of external include the following

    • Data stored in a Microsoft Access database. This could the information from a custom application i.e. Payroll, Point of Sale, Inventory, etc.
    • Data from SQL Server or other database engines i.e. MySQL, Oracle, etc. – This could be information from a custom application
    • From a web site/web service – this could be information from a Web services i.e. currency exchange rates from the internet, stock prices, etc.
    • Text file i.e. CSV, tab separated, etc. – this could be information from a third party application that does not provide direct links. Such data could include bank payments exported to comma separated file CSV, etc.
    • Other types i.e. HTML data, Windows Azure Market Place, etc.

    Website(XML data) external data source example

    In this example to import XML into Excel, we will assume we are trading the Euro currency and would like to get the exchange rates from the European Central Bank web service. The currency exchange rate API link is http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml

    • Open a new workbook
    • Click on the DATA tab on the ribbon bar
    • Click on “From Web” button
    • You will get the following window

    How to Import XML Data into Excel

    1. Enter http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml in the address
    2. Click on Go button, you will get the XML data preview
    3. Click on Import button when done

    You will get the following options dialogue window

    Connecting Microsoft Excel to External Data Sources

    • Click on OK button
    • You will get the following Excel import XML data

    Steps to Import XML Data into Excel

    Let’s take another example on how to import XML file in Excel, this time you have local XML not in form of web link. You can download XML File below.

    Download the XML File

    Here is a step by step process on how to open XML file in Excel:

    Step 1) Create a new workbook in Excel

    • Open a new workbook
    • Click on the DATA tab on the ribbon bar
    • Click on “From Other Source”

    How to Import XML to Excel

    Step 2) Select the XML as Data source

    • Then click on “From XML Data Import”

    Steps for connecting Microsoft Excel to External Data Sources

    Step 3) Locate and select the XML file

    • Now select the XML File to Excel sheet

    You will get the options dialogue window as above example

    • Click on OK button
    • You will get the following data

    How to Connect Microsoft Excel to External Data Sources

    Summary

    Excel has powerful features that allow us to analyse numeric data and create visual reports such as charts. You can take advantage of external data importation to create your own custom reports that meet your business reporting requirements.

    Понравилась статья? Поделить с друзьями:
  • Xml for excel 2013
  • Xml for excel 2010
  • Xml for excel 2007
  • Xml file open in word
  • Xml file for excel