How to edit core properties of .xlsx file with Python?

强颜欢笑 提交于 2019-12-11 15:19:44

问题


I'm attempting to populate some of the core property fields for Excel files (namely the subject, category, and title fields) and am having trouble finding a way to do so.

I was able to accomplish this with .docx files using the docx module like so:

doc = docx.Document(file)

name = doc.tables[1]._cells[43].text
data = doc.tables[0]._cells[1].text
numbers = re.findall('\d{9}', data)

doc.core_properties.title = numbers[0]
doc.core_properties.category = numbers[1]
doc.core_properties.subject = name

doc.save(file)

Is there a similar way to do this with .xlsx files or am I out of luck?


回答1:


Try openpyxl module to get and set properties interatively.

    import openpyxl
    fh = openpyxl.load_workbook("results.xlsx")

    obj = fh.properties   #To get old properties
    print obj   # print old properties

    fh.properties.title = "newTitle"          # To set title
    fh.properties.category = "newCategory"    # To set category
    fh.properties.subject = "newSubject"      # To set subject

    ##similarly you can set other fields ##

    new_obj = fh.properties   #Now get new properties
    print new_obj   # print new properties

    fh.save("results.xlsx")


来源:https://stackoverflow.com/questions/52120125/how-to-edit-core-properties-of-xlsx-file-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!