Search code examples
pythonxmlopenpyxlxlsxyattag

Python: Create several xml-files from several xlsx-files


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("column0"):
            text(row[0])
        with tag("column1"):
            text(row[1])
        with tag("column2"):
            text(row[2])
        with tag("column3"):
            text(row[3])
        with tag("column4"):
            text(row[4])
        with tag("column5"):
            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"...


Solution

  • 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