Home > database >  Python: Create several xml-files from several xlsx-files
Python: Create several xml-files from several xlsx-files

Time:07-09

I found out how to create a singe xml-file from a single xlsx-file using this code:

from openpyxl import load_workbook

wb = load_workbook("convert_file.xlsx",data_only=True)
ws = wb.active
sheetname_row_list:list =[]
    
for row in ws.iter_rows(min_row=2, max_row=7, min_col=1, max_col=6):
    row = [cell.value for cell in row]
    sheetname_row_list.append(row)

from yattag import Doc, indent
doc, tag, text = Doc().tagtext()

for row in sheetname_row_list:
        with tag("culumn0"):
            text(row[0])
        with tag("culumn1"):
            text(row[1])
        with tag("culumn2"):
            text(row[2])
        with tag("culumn3"):
            text(row[3])
        with tag("culumn4"):
            text(row[4])
        with tag("culumn5"):
            text(row[5])
            
result = indent(
        doc.getvalue(),
        indentation = '    ',
        indent_text = False
)

with open("result_file.xml","w") as f:
    f.write(result)

How can I now create several xml-files from several xlsx-files with all the same structure?

I have "convert_file.xlsx" / "convert_file_2.xlsx" / "convert_file_3.xlsx"... and want to get "result_file.xml" / "result_file_2.xml" / "result_file_3.xml"...

CodePudding user response:

I suggest using pathlib and something like:

from pathlib import Path

source_directory = Path('.')   # Pointing to the XLSX files
for filename in source_directory.glob('*.xlsx'):
   # Call to your conversion code
   ...
   resultname = f'{filename.stem.replace("convert", "result")}.xml'
   # Save to file using resultname
   ...

Happy coding.

Edit: Included a way of changing the file extension from .xlsx to .xml

  • Related