简体   繁体   English

Python:从几个 xlsx 文件创建几个 xml 文件

[英]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:我发现了如何使用以下代码从单个 xlsx 文件创建单个 xml 文件:

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?我现在如何从多个具有相同结构的 XLSX 文件创建多个 XML 文件?

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"...我有“convert_file.xlsx”/“convert_file_2.xlsx”/“convert_file_3.xlsx”......并且想要获得“result_file.xml”/“result_file_2.xml”/“result_file_3.xml”......

I suggest using pathlib and something like:我建议使用 pathlib 和类似的东西:

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编辑:包括将文件扩展名从 .xlsx 更改为 .xml 的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM