Как конвертировать xsd в excel

У меня есть файл XSD, и мне нужно преобразовать его в файл MS Excel.
XSD находится ниже.

<?xml version="1.0" encoding="ISO-8859-1" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="shiporder">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="orderperson" type="xs:string"/>
      <xs:element name="shipto">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="name" type="xs:string"/>
            <xs:element name="address" type="xs:string"/>
            <xs:element name="city" type="xs:string"/>
            <xs:element name="country" type="xs:string"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="item" maxOccurs="unbounded">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="title" type="xs:string"/>
            <xs:element name="note" type="xs:string" minOccurs="0"/>
            <xs:element name="quantity" type="xs:positiveInteger"/>
            <xs:element name="price" type="xs:decimal"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
    <xs:attribute name="orderid" type="xs:string" use="required"/>
  </xs:complexType>
</xs:element>

</xs:schema>

просьба помочь мне, я действительно не знаю как и с чего начать.

4 ответов


этот ответ одинаково для вас, а также @Alex, @Michael и @42. Я иллюстрирую его с помощью Excel 2010, поэтому, если вы находитесь в другой версии, я оставлю вам возможность внести необходимые изменения.

во-первых, убедитесь, что вкладка Разработчик показывает (нажмите вкладку Файл, Параметры).

Excel 2010 options for Developer tab

теперь вам нужно создать источник XML из вашего XSD: перейдите на вкладку Разработчик; в группе XML переключите кнопку Источник, чтобы показать задачу источник Xml панели; нажмите кнопку карты XML.

Excel showing key UI elements for creating an XML map

Нажмите кнопку Добавить в приглашении; укажите файл XSD; затем нажмите кнопку ОК, чтобы вернуться к главному экрану.

Excel showing XSD loaded in an XML map

затем вы можете перетащить свой shipOrder в ячейку на листе, чтобы закрепить сгенерированную сопоставленную таблицу.

Excel showing mapped XSD

далее, Вы можете использовать импорт, чтобы получить ваши данные XML в электронную таблицу, и экспорт, чтобы получить его. Есть несколько дополнительные вещи, на которые стоит обратить внимание; Читать эта статья на сайте Microsoft; обратите особое внимание на проблемы с экспортом XML-данных (ошибка XML-карты в моей книге не экспортируются). Это из-за 1 ко многим кардинальности между shiporder и item. Вы можете попытаться справиться с этим, используя сопоставленные диапазоны — я оставлю все это на вас. Лучше всего было бы вам прочитать онлайн-справку для раздела разработчика XML…


на MS Excel ->File ->Open. Выберите файл xsd.

вам будет предложено, как вы хотели бы открыть файл. Вы можете выбрать опцию «в качестве таблицы XML». Сохраните файл в формате Excel.

2

автор: Ashwath Padmashali


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

вы можете редактировать данные по мере необходимости. Все остальное потребует некоторой обработки.


выберите весь текст XSD в текстовом редакторе, скопируйте его в буфер обмена, щелкните ячейку в электронной таблице Excel и выполните вставку. Ваши данные XSD теперь будут в вашей электронной таблице.

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


This answer is equally for you as well as @Alex, @Michael and @forty-two. I am illustrating it using Excel 2010, so if you’re on another version, I’ll leave it up to you to make the necessary adjustments.

First thing, make sure the developer tab shows (Click the File tab, Options).

Excel 2010 options for Developer tab

You now have to create an XML source from your XSD: click the Developer tab; in the XML group, toggle Source button to show the Xml Source task pane; then click the XML Maps button.

Excel showing key UI elements for creating an XML map

Click Add button at the prompt; point to the XSD file; then click OK to go back to the main screen.

Excel showing XSD loaded in an XML map

Then you can drag and drop your shipOrder to a cell in a worksheet, to anchor the generated mapped table.

Excel showing mapped XSD

Next, you may use Import to get your XML data into the spreadsheet, and Export to get it out. There are a couple of additional things to pay attention to; read this article on Microsoft’s site; pay particular attention to the issues with exporting XML data (error XML maps in my workbook are not exportable). This is because of the 1 to many cardinality between shiporder and item. You can try to handle it using mapped ranges — I’ll leave this all up to you. The best would be for you to read the online help for the XML developer section…

Excel for Microsoft 365 Excel 2021 Excel 2019 Excel 2016 Excel 2013 Excel 2010 Excel 2007 More…Less

It is important to understand how XML Schema Definition (XSD) data types are handled when you import or export XML data, so that the data is appropriately converted according to your needs.

What do you want to do?

  • Learn how Excel handles XSD data types when you import XML data

  • Learn how Excel display formats map to XSD data types when you export XML data

Learn how Excel handles XSD data types when you import XML data

Important: If an XML schema file (.xsd) does not define a specific data type attribute for an element (such as xsd:decimal), then Excel formats the cell as text by default when the XML data is imported. Formatting as text ensures that the characters stored in the cell are exactly the same as the data that is stored in the XML file (.xml). For example, leading zero (0) values in an ID or credit card field are removed when they are formatted as a number, but not removed when they are formatted as text. However, data that is formatted as text does not evaluate. If you want the data to evaluate because it contains a formula, you must explicitly provide a numeric data type attribute, such as xsd:decimal or xsd:integer.

The following table lists the display formats that are applied when an item with a particular XSD data type is imported into an Excel worksheet. Data with an XSD format listed in the Unsupported formats column are imported as text values.

XSD data type

Excel display format

Unsupported formats

time

h:mm:ss

hh:mm:ssZ
Hh:mm:ss.f-f

dateTime

m/d/yyyy h:mm

yyyy-mm-ddThh:mm:ssZ
yyyy-mm-ddThh:mm:ss+/-hh:mm
yyyy-mm-ddThh:mm:ss.f-f
Years outside of the range 1900 to 9999

date

Date *3/14/2001

yyyy-mm-ddZ
yyyy-mm-dd+/-hh:mm
Years outside of the range 1900 to 9999

gYear

Number, no decimals

yyyy+/-hh:mm
Years outside of the range 1900 to 9999

gDay
gMonth

Number, no decimals

gYearMonth

Custom mmm-yy

yyyy-mm+/-hh:mm
Years outside of the range 1900 to 9999

gMonthDay

Custom d-mmm

anytype
anyURI
base64Binary
duration
ENTITIES
ENTITY
hexBinary
ID
IDREF
IDREFS
language
Name
NCName
NMTOKEN
NMTOKENS
normalizedString
NOTATION
QName
string
token

Text

boolean

Boolean

decimal
float
double

General

Leading and trailing zeros (0) are dropped.
Negative (-) and positive (+) signs are respected, although only negative signs are displayed.
Excel stores and calculates with 15 significant digits of precision.

byte
int
integer
long
negativeInteger
nonNegativeInteger
nonPositiveInteger
positiveInteger
short
unsignedByte
unsignedInt
unsignedLong
unsignedShort

General

Top of Page

Learn how Excel display formats map to XSD data types when you export XML data

When you export XML data, the exported data will match the data that is displayed in the worksheet, under the following circumstances:

  • The Excel display format is Text.

  • You have not changed the display format of the data.

If you change the display format of a cell that has numeric, date, or time data, then the underlying value of the cell is exported. For example, if you apply a Percentage display format to a cell that results in the display of 51.50%, the cell’s value will be exported as .515.

Top of Page

Need more help?

You can always ask an expert in the Excel Tech Community or get support in the Answers community.

Need more help?

Вопрос:

У меня есть XSD файл, и мне нужно его преобразовать в файл MS Excel.
XSD находится ниже.

<?xml version="1.0" encoding="ISO-8859-1" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="shiporder">
<xs:complexType>
<xs:sequence>
<xs:element name="orderperson" type="xs:string"/>
<xs:element name="shipto">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="item" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="note" type="xs:string" minOccurs="0"/>
<xs:element name="quantity" type="xs:positiveInteger"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="orderid" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>

</xs:schema>

Помогите мне, я действительно не знаю, как и с чего начать.

Лучший ответ:

Этот ответ одинаково для вас, а также @Alex, @Michael и сорок два. Я иллюстрирую это с помощью Excel 2010, поэтому, если вы используете другую версию, я оставлю это для вас, чтобы внести необходимые корректировки.

Во-первых, убедитесь, что на вкладке разработчика отображается вкладка (вкладка “Файл”, “Параметры” ).

Excel 2010 options for Developer tab

Теперь вам нужно создать источник XML из своего XSD: щелкните вкладку “Разработчик”; в группе XML, переключите кнопку “Источник”, чтобы отобразить панель задач “Xml Source”; затем нажмите кнопку “Карты XML”.

Excel showing key UI elements for creating an XML map

Нажмите кнопку “Добавить” в приглашении; указать на файл XSD; затем нажмите “ОК”, чтобы вернуться на главный экран.

Excel showing XSD loaded in an XML map

Затем вы можете перетащить ваш shipOrder в ячейку на листе, чтобы привязать сгенерированную сопоставленную таблицу.

Excel showing mapped XSD

Затем вы можете использовать “Импорт”, чтобы получить данные XML в электронной таблице и “Экспорт”, чтобы получить его. Есть еще несколько вещей, на которые нужно обратить внимание; прочитайте эту статью на сайте Microsoft; обратите особое внимание на проблемы с экспортом XML-данных (XML-карты ошибок в моей книге не экспортируются). Это из-за 1-х многих мощностей между shiporder и item. Вы можете попытаться справиться с этим, используя сопоставленные диапазоны – я оставлю все это до вас. Лучше всего было бы прочитать интерактивную справку для раздела разработчиков XML…

Ответ №1

Перейдите к MS ExcelFileOpen. Выберите файл xsd.

Вам будет предложено открыть файл. Вы можете выбрать опцию “Как таблица XML”. Сохраните файл в формате excel.

Ответ №2

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

Затем вы можете редактировать данные по мере необходимости. Для чего-то еще потребуется некоторая обработка.

Ответ №3

Выберите весь текст XSD в текстовом редакторе, скопируйте его в буфер обмена, щелкните ячейку в электронной таблице Excel и выполните вставку. Ваши данные XSD теперь будут в вашей таблице.

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

Today something about XML in Excel. We will learn how to use XSD files in the Excel application.

Downloading Xml Tools

Firstly, you will have to download the XML TOOLS ADD-IN. After downloading the add-in, start Excel, click on the FILE tab, go to OPTION and then click the ADD-INS category.

xsd XMLTOOL.XLA

Click on EXCEL ADD-INS and then click GO. In the dialog box, click BROWSE and locate the XMLTOOL.XLA file. Select it and click OK.

xsd XMLTOOLS

Enter the data.

Converting xsd to Excel

On the Add-Ins tab, in the menu commands group, click the arrow next to XML Tools and then click Convert a Range to an XML list.

xsd xmltools ribbon

Enter the cell range of the data that you want to convert as an absolute reference in the text box.

Under Use first row as column names, select No if the first row contains data or Yes if the first column contains a header and click OK.

On the Developer tab, in the XML group, click Export.

xsd xml export

In the dialog box, type a name in the File Name field.

xsd xml map properties

Click OK.

Select any cell in the EXCEL table.

On the ADD-INS tab, in the Menu commands group, click the arrow next to the XML Tools and then click Create XSD file for the XML Schema.

In Notepad, click File and Save AS.

Note: The imported XSD file may not retain all the data formatting and structure of the original file. The data may be rearranged or reformatted to fit into the cells of the Microsoft Excel worksheet. If you need to retain the original structure of the XSD file, you may need to save the data as a separate XML file, or use a specialized XML editor to view and work with the data.

Further reading: 
How to open XML files in Excel?

Понравилась статья? Поделить с друзьями:
  • Как конвертировать xps в word
  • Как конвертировать xps в excel
  • Как конвертировать xml файл в файл word
  • Как конвертировать xml в word онлайн
  • Как конвертировать xlsx в excel