【问题标题】:Writing multi-line strings into cells using openpyxl使用 openpyxl 将多行字符串写入单元格
【发布时间】:2021-10-25 21:17:42
【问题描述】:

我正在尝试将数据写入具有多个换行符的单元格(我相信 \n),生成的 .xlsx 已删除换行符。 有没有办法保留这些换行符?

【问题讨论】:

    标签: python openpyxl


    【解决方案1】:

    为 openpyxl >= 2 更改样式的 API。以下代码演示了现代 API。

    from openpyxl import Workbook
    from openpyxl.styles import Alignment
    
    wb = Workbook()
    ws = wb.active # wb.active returns a Worksheet object
    ws['A1'] = "Line 1\nLine 2\nLine 3"
    ws['A1'].alignment = Alignment(wrapText=True)
    wb.save("wrap.xlsx")
    

    【讨论】:

    • 是的,API 已更改,您的代码可以正常运行。谢谢!
    【解决方案2】:

    免责声明:这在 Openpyxl 的最新版本中不起作用。查看其他答案。

    openpyxl 中,您可以设置wrap_text 对齐属性来换行多行字符串:

    from openpyxl import Workbook
    
    workbook = Workbook()
    worksheet = workbook.worksheets[0]
    worksheet.title = "Sheet1"
    
    worksheet.cell('A1').style.alignment.wrap_text = True
    worksheet.cell('A1').value = "Line 1\nLine 2\nLine 3"
    
    workbook.save('wrap_text1.xlsx')
    

    XlsxWriter 模块也可以做到这一点。

    这是一个小的工作示例:

    from xlsxwriter.workbook import Workbook
    
    # Create an new Excel file and add a worksheet.
    workbook = Workbook('wrap_text2.xlsx')
    worksheet = workbook.add_worksheet()
    
    # Widen the first column to make the text clearer.
    worksheet.set_column('A:A', 20)
    
    # Add a cell format with text wrap on.
    cell_format = workbook.add_format({'text_wrap': True})
    
    # Write a wrapped string to a cell.
    worksheet.write('A1', "Line 1\nLine 2\nLine 3", cell_format)
    
    workbook.close()
    

    【讨论】:

    • 感谢您的帮助。您是否知道带有示例的 python openpyxl 的好文档?
    • 最新的 OpenPyXL 文档是 here。但是,我通过阅读代码(并且对我要查找的内容有一个大致的了解)弄清楚了上面的语法。 XlsxWriter 有详细的docsexamples
    • 我在 XlsxWriter 和 openpyxl 模块上都得到了重复。 (例如 - 当我写“line1 \n line2”时,我得到“line1 \n line2 line1 \n line2”
    • unresolved_external:屏幕截图显示该示例生成了正确的输出。如果您有其他问题或新问题,请使用一个演示它的小工作示例开始一个新的 StackOverflow 问题。
    • 我这样做了,但单元格中的输出仍然只是一个带有“\n”的字符串,而不是一个拆分为多行的字符串。知道为什么吗?
    【解决方案3】:

    只是一个附加选项,您可以使用文本阻止“”“我的单元格信息在这里”“”以及文本换行布尔值对齐并获得所需的结果。

    from openpyxl import Workbook
    
    wb= Workbook()
    sheet= wb.active
    sheet.title = "Sheet1"
    
    sheet['A1'] = """Line 1
    Line 2
    Line 3"""
    
    sheet['A1'].alignment = Alignment(wrapText=True)
    
    wb.save('wrap_text1.xlsx')
    

    【讨论】:

      【解决方案4】:

      以防万一有人在寻找我们迭代所有单元格以应用包装的示例:

      小型工作示例:

      import pandas as pd
      from openpyxl import Workbook
      from openpyxl.styles import Alignment
      from openpyxl.utils.dataframe import dataframe_to_rows
      
      # create a toy dataframe. Our goal is to replace commas (',') with line breaks and have Excel rendering \n as line breaks.
      df = pd.DataFrame(data=[["Mark", "Student,26 y.o"],
                              ["Simon", "Student,31 y.o"]], 
                        columns=['Name', 'Description'])
      
      # replace comma "," with '\n' in all cells
      df = df.applymap(lambda v: v.replace(',', '\n') if isinstance(v, str) else v)
      
      # Create an empty openpyxl Workbook. We will populate it by iteratively adding the dataframe's rows.
      wb = Workbook()
      ws = wb.active # to get the actual Worksheet object
      
      # dataframe_to_rows allows to iterate over a dataframe with an interface
      # compatible with openpyxl. Each df row will be added to the worksheet.
      for r in dataframe_to_rows(df3, index=True, header=True):
          ws.append(r)
      
      # iterate over each row and row's cells and apply text wrapping.
      for row in ws:
        for cell in row:
          cell.alignment = Alignment(wrapText=True)
      
      # export the workbook as an excel file.
      wb.save("wrap.xlsx")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-09
        • 1970-01-01
        • 2012-07-19
        • 2018-12-03
        • 2015-11-28
        • 1970-01-01
        • 1970-01-01
        • 2015-02-15
        相关资源
        最近更新 更多