Làm cách nào để chuyển đổi dữ liệu XML sang Excel trong Python?

Các tính năng cơ bản của thư viện bao gồm tạo nhiều trang tính được đặt tên trong một sổ làm việc và tạo các hàng ô trong các trang tính này. However, there are more possibiliteis to create complex excel based reports

Cell referencing

Trình phân tích cú pháp có thể lưu trữ các vị trí của ô theo cấu trúc giống như từ điển. Sau đó, nó có thể được tham chiếu để tạo các công thức phức tạp. Each value of the cell is preprocessed using string format with stored values. This means that these values can be referenced using { and } brackets

Current row and column

There are two basic values that can always be used, i. e. row and col which return current row number and column name


    
        {col}{row}
    

...

sẽ tạo một sổ làm việc có văn bản “A1” được bao gồm trong ô A1 của trang tính. Using template languages, you can create more complicated constructs, like (using django template system)

...
{% for e in list %}

    "date" date-fmt="%Y-%m-%d">{{ e|date:"Y-m-d" }}
    =TEXT(A{row}, "ddd")

{% endfor %}
...

would create a list of rows with a date in the first column and weekday names for these dates in the second column (provided list context variable contains a list of dates)

ô được chỉ định

Cũng có thể lưu trữ ô có thể lưu trữ tên của các ô được chỉ định trong một biến giả (như trong từ điển). Người ta phải sử dụng thuộc tính ref-id của thẻ ô và sau đó sử dụng lại giá trị của thuộc tính này trong phần còn lại của đầu vào xml. Điều này rất hữu ích trong các công thức. Một ví dụ đơn giản sẽ là tham chiếu đến một ô khác trong một công thức như thế này

...
"mycell">This is just a test
...
={mycell}
...

sẽ tạo ra một công thức excel tham chiếu đến một ô có dòng chữ “đây chỉ là bản thử nghiệm”, bất kể địa chỉ ô này là gì

Một ví dụ phức tạp hơn sử dụng công cụ mẫu django để tạo tóm tắt có thể trông như thế này

...
{% for e in list %}
    
        "{% if forloop.first %}start{% elsif forloop.last %}end{% endif %}">
            {{ e }}
        
    
{% endfor %}

    Summary
    =SUM({start}:{end})

...

Danh sách các ô

Tham chiếu một ô duy nhất có thể khó khăn khi xử lý các báo cáo phức tạp. Đặc biệt là khi tạo tóm tắt dữ liệu được phân bổ theo trang tính không đều. xml2xlsx can append a cell to a variable-like list, as in ref-id attribute, to reuse it as a comma concatenated value. Instead of ref-id, one has to use ref-append attribute

This is a simple example to demonstrate the feature

...

    
        1
        2
    
    3
    =SUM({mylist})

This will generate an Excel sheet with A3 cell containing formula to sum A1, B1 and A2 cells (=SUM(A1, B1, A2))

Referencing limitations

Hoàn toàn có thể tham chiếu một ô trong một trang tính khác bằng cả ref-id và ref-append. Tuy nhiên, có một hạn chế đó. Vì xml2xslx là trình phân tích cú pháp tuyến tính nên bạn chỉ được phép tham chiếu các phần tử đã được phân tích cú pháp. Điều này có nghĩa là bạn phải tạo các trang tính theo thứ tự phù hợp (các trang tính tham chiếu đến các trang tính khác phải được tạo sau khi các ô được tham chiếu được phân tích cú pháp)

Ví dụ sau sẽ không hoạt động

...
"one">
    {mycell}

"two">
    "mycell">XYZ

...

Tuy nhiên, có thể làm cho ví dụ này hoạt động và giữ nguyên thứ tự trang tính bằng cách sử dụng thuộc tính chỉ mục

Đây là cách tệp XML của tôi trông như thế nào. -

b’xfa:datafrm:FormSchVfrm:AuthCapital100000.0frm:CINU74140DL2004PTC128960frm:CmpnyAddresscdt:FirstLine9, CSC, DDA MARKET, A-BLOCKcdt:SecondLineSARASWATI VIHARDELHIDLINDIA110034[email protected]frm:WhetherListedNOfrm:FnclYrEndDt2008-03-31frm:AGMHeldYESfrm:AGMDate2008-09-16frm:DueAGMDate2008-09-30frm:WhetherExtnNOfrm:AuthCapOfCmp100000.00frm:AuthNominalAmtPerES10frm:AuthCapESN10000.00frm:AuthCapESV100000.00frm:AuthCapPSN0.00frm:AuthCapUCSN0.00frm:IssuedCapOfCmp100000.00frm:IssuedNominalAmtPerES10frm:IssuedCapESN10000.00frm:IssuedCapESV100000.00frm:IssuedCapPSN0.00frm:SubsCapOfCmp100000.00frm:SubsNominalAmtPerES10frm:SubsCapESN10000.00frm:SubsCapESV100000.00frm:SubsCapPSN0.00frm:PaidupCapOfCmp100000.00frm:PaidupNominalAmtPerES10frm:PaidupCapESN10000.00frm:PaidupCapESV100000.00frm:PaidupCapPSN0.00frm:TotalDevntrOfCmp0.00frm:NonConvDebNum0.00frm:PartlyConvDebNum0.00frm:FullyConvDebNum0.00frm:IndbtAmt0.00frm:CntrlStGovt0.00frm:GovtCmp0.00frm:PubFinCmp0.00frm:NtnOthBnk0.00frm:MutFunds0.00frm:VenCap0.00frm:FrgnHld0.00frm:BodCorp0.00frm:DirRelDir100.00frm:Oth50ShHld0.00frm:Others0.00frm:TtlNoShrHld2frm:NoMDirOrDir2frm:DetailsOfMGSecorManInfofrm:DetailsOfMGSecorManager00662584VEERA WASIRDirector2004-09-10500050.00000000YES2008-09-16frm:DetailsOfMGSecorManager01667486GURMIT SINGHDirector2004-09-10500050.00000000YES2008-09-16frm:NoMDirOrDirtoCease0frm:DateDeclaration2008-07-29frm:DesignationDIRTfrm:DINMembrNoNew00662584frm:CharteredorCostorCompanyCAfrm:AssociateorFellowASSfrm:MembershipnumberorCertificate504311frm:HTFNOfrm:FormIdFormSchVfrm:VersionNo9frm:AttachmentNames2037.pdf,2900.pdffrm:DetailsOMGtoCeaseInfofrm:DetailsOfMGtoCeasefrm:DetailsOfMGtoCeasefrm:DetailsOfMGtoCeasefrm:DetailsOfMGtoCeasefrm:WhtrListOfAttachmtYESfrm:BoardResNo1srn:SRNsrn:BusinessDateusr:UserTypesig:SerialNosig:SourceCA2008-09-302008-09-16VEERA WASIR CONSULTANTS PRIVATE LIMITED2008-03-319100.00U74140DL2004PTC1289602008-09-162008-09-302008-09-16Annual Return.pdf:2037:List of Shareholders.pdf:2900VEERA WASIR CONSULTANTS PRIVATE LIMITEDPRIVNGOV0251;1;3;[object RDN cn=(n)Code Solutions - A Division of GNFC LTD., c=IN, o=India PKI, ou=(n)Code Solutions CA];[object RDN cn=VEERA WASIR 562242, c=IN, o=(n)Code Solutions CA, ou=Class IIa, Director];Sign1;4176C1B12;2;3;[object RDN cn=Tata Consultancy Services Certifying Authority, c=IN, l=Hyderabad, st=AP, o=India PKI, ou=TCS CA, [email protected]];[object RDN cn=Dheeraj Sharma, c=IN, l=New Delhi, st=Delhi, o=Tata Consultancy Services - Certifying Authority, ou=Corporate Professionals - Registration Authority, Individual - Others, Class 2 Certificate, [email protected]];Sign2;07D810A101611D2381B229YES0NOfrm:FormSchVfrm:AuthCapitalfrm:CINfrm:CmpnyAddresscdt:FirstLinefrm:WhetherListedfrm:FnclYrEndDtfrm:AGMHeldfrm:DueAGMDatefrm:WhetherExtnfrm:AuthCapESNfrm:AuthCapPSNfrm:AuthCapUCSNfrm:IssuedCapESNfrm:IssuedCapPSNfrm:SubsCapESNfrm:SubsCapPSNfrm:PaidupCapESNfrm:PaidupCapPSNfrm:IndbtAmtfrm:TtlNoShrHldfrm:DateDeclarationfrm:Designationfrm:FormIdfrm:VersionNofrm:AttachmentNamessrn:SRNsrn:BusinessDateusr:UserTypedd:groupdd:groupsig:SerialNosig:SourceCAtms:ContentIdtms:DocumentTimestamptms:CertSerialNumtms:CertSubjectDNtms:CertIssuerDNpay:PaymentModepay:PaymentTypepay:PaymentStatuspay:AmountPaidatc:ContentIdatc:MimeTypeatc:PageCountfee:NormalFeefee:FormIdfee:NormalFee

I’ve just run your programme here, with your example XML file. I’ve
running this version of your code.

 from pprint import pprint
 import xmltodict
 import pandas as pd

 # open the input xml file and read data in form of python dictionary 
 # using xmltodict module
 with open(r"foo2.xml") as xml_file:
     data_dict = xmltodict.parse(xml_file.read())
         # xml_file.close()
         # df=pd.DataFrame()
     df=pd.json_normalize(data_dict)
     df.to_csv('data.csv')

 pprint(data_dict)

It certainly produces a CSV file, and also prints (using

...
{% for e in list %}

    "date" date-fmt="%Y-%m-%d">{{ e|date:"Y-m-d" }}
    =TEXT(A{row}, "ddd")

{% endfor %}
...
0) a
nice dump of the data in
...
{% for e in list %}

    "date" date-fmt="%Y-%m-%d">{{ e|date:"Y-m-d" }}
    =TEXT(A{row}, "ddd")

{% endfor %}
...
1. That is a deeply nested
...
{% for e in list %}

    "date" date-fmt="%Y-%m-%d">{{ e|date:"Y-m-d" }}
    =TEXT(A{row}, "ddd")

{% endfor %}
...
2.
Here’s the start.

 { 'xfa:datasets': { '@xmlns:xfa': 'http://www.xfa.org/schema/xfa-data/1.0/',
                     'dd:dataDescription': [ { '@dd:name': 'FormSchV_Dtls',
                                               '@xmlns:dd': 'http://ns.adobe.com/data-description/',
                                               'frm:FormSchV_Dtls': { '@xmlns:frm': 'http://www.mit.gov.in/eGov/BackOffice/schema/Form',
                                                                      'atc:Attachments': { '@dd:maxOccur': '-1',
                                                                                           '@dd:minOccur': '0',
                                                                                           '@xmlns:atc': 'http://www.mit.gov.in/eGov/BackOffice/schema/AttachmentDetails',
                                                                                           'atc:ContentId': None,
                                                                                           'atc:MimeType': None,
                                                                                           'atc:PageCount': None},
                                                                      'fee:FeeDetails': { '@dd:minOccur': '0',
                                                                                          '@xmlns:fee': 'http://www.mit.gov.in/eGov/BackOffice/schema/FeeDetails',
                                                                                          'fee:AddlnFee': { '@dd:minOccur': '0',

and so on

Have you tried opening the CSV in some spreadsheet program such as
Excel? Does it look like what you expect?

You say data’s missing, but we have no idea what you expect to see or
what is missing.

...
{% for e in list %}

    "date" date-fmt="%Y-%m-%d">{{ e|date:"Y-m-d" }}
    =TEXT(A{row}, "ddd")

{% endfor %}
...
3 is not magic. It translates XML into a nested data structure
much as one might get from a format like JSON.
(xmltodict)[xmltodict · PyPI]. Their second example
suggests you might get more understandable result from
...
{% for e in list %}

    "date" date-fmt="%Y-%m-%d">{{ e|date:"Y-m-d" }}
    =TEXT(A{row}, "ddd")

{% endfor %}
...
3 with
the
...
{% for e in list %}

    "date" date-fmt="%Y-%m-%d">{{ e|date:"Y-m-d" }}
    =TEXT(A{row}, "ddd")

{% endfor %}
...
5 parameter. I haven’t tried that.

CSV files (and pandas DataFrames) are inherently fairly flat data
structures, a mapping of column names to indexed values.

To convert one to the other requires deciding what data within the XML
should become data, and in what form.

Until you actually inspect the XML you can’t just wave a wand to
“generate a CSV” from it. They’re fundamentally different shapes, and
some manipulation will be needed.

Cheers,
Cameron Simpson cs@cskk. id. au

Thank you for helping me with this

Actually, I have a PDF file which is basically a form and i want to extract all the field names as a column name and the information associated with them and then save them into an excel file. After further investigation, I discovered that it is an XFA-based PDF. Then the below code is used to extract the XML from the XFA-based PDF

import PyPDF2 as pypdf

def findInDict(needle, haystack):
    for key in haystack.keys():
        try:
            value=haystack[key]
        except:
            continue
        if key==needle:
            return value
        if isinstance(value,dict):            
            x=findInDict(needle,value)            
            if x is not None:
                return x

pdfobject=open('pdf_file.pdf','rb')
pdf=pypdf.PdfFileReader(pdfobject)
xfa=findInDict('/XFA',pdf.resolved_objects)
xml=xfa[7].getObject().getData()

print(xml)

I attempted to convert the XML to CSV/Excel, but I was unable to do so due to UTF-8 (i guess). I then used a online converter to convert the XML to JSON and finally the JSON to CSV

Then I wrote the below code to convert the XML and JSON

import xmltodict
import json
xml_data = xml
data = xmltodict.parse(xml_data)
# using json.dumps to convert dictionary to JSON
json_data = json.dumps(data, indent = 2)
print(json_data)

I now want to modify this script so that I can just copy the PDF file into the folder where the script is located, and then, once it has been executed, the JSON file will be generated with the same name as the input file name

How to convert XML File to XLSX?

Here's how. .
Click the File menu and choose Save As
Click Browse (Windows) or On My Mac (Mac), then choose a folder. .
Type a name for your workbook
If you want to save the file as an Excel XLSX file, choose Excel Workbook from the "Save as type" or "File Format" menu. .
Click Save to save the file

How to convert XML into CSV in Python?

Cách chuyển đổi XML sang CSV trong Python – Hướng dẫn từng bước .
Phân tích tệp XML
Create a new CSV
Add a header to the CSV file, with the fields that should be included
For each xml element, extract the relevant fields and add new row to the CSV file

How to extract data from XML File using Python?

The way this works is that we. .
Load our XML document into memory, and construct an XML ElementTree object
We then use the find method, passing in an XPath selector, which allows us to specify what element we're trying to extract
If the element can't be found, None is returned

How to convert XML into CSV?

How to convert an XML Document to CSV File or Excel Spreadsheet .
Open the XML file and select all the text by clicking Ctrl + A then copy it by clicking Ctrl+C
Open Notepad ++ and paste the text from the previous step. .
From the top menu, open the Language sub-menu, then select XML