Python: openpyxl change font to bold

后端 未结 2 1995
青春惊慌失措
青春惊慌失措 2021-01-02 02:08

I\'m using Python version 3.6 and the latest version of the openxlpy module (v2.4.8) on Windows.

I want to change certain font to bold in a cell, but I don\'t want a

相关标签:
2条回答
  • 2021-01-02 02:51

    Answers post title but not ops specific question.

    from openpyxl.workbook import Workbook
    from openpyxl.styles import Font
    wb = Workbook()
    ws = wb.active
    ws['B3'] = "Hello"
    ws['B3'].font = Font(bold=True)
    wb.save("BoldDemo.xlsx")
    

    0 讨论(0)
  • 2021-01-02 02:56

    I do not think openpyxl has implemented any handling for intracell style differences. If you take a file that has multiple styles in one cell, import it in openpyxl and save it new file, without changing the cell, the new file will lose its formatting.

    >>>import openpyxl
    >>>path = 'test.xlsx'
    >>>book = openpyxl.load_workbook(path)
    >>>book.active['a1']
    >>>book.active['a1'].value
    'not bold line\nbold line\nnot bold line\n'
    >>>print(_)
    not bold line
    bold line
    not bold line
    
    >>>book.save(path)
    

    From here you have a couple options.

    1. Use another lib for handling xlsx. I will refrain from talking about using alternative libraries because I'm presuming you are using openpyxl for a reason.

    2. Create your own markdown and use a custom script to add the formatting after editing and saving the file with openpyxl. You can find the spec for Office Open XML File Formats here. Here is a also a great article about parsing xlsx files and xml.

    3. edit the codebase for openpyxl.

    4. If the steps above are not achievable/desirable, try to contact the openpyxl maintainers, or hire help :/

    0 讨论(0)
提交回复
热议问题