Перенос текста в ячейке в excel python

I have a Pandas dataframe that I am writing out to an XLSX using openpyxl. Many of the cells in the spreadsheet contain long sentences, and i want to set ‘wrap_text’ on all the contents of the sheet (i.e. every cell).

Is there a way to do this? I have seen openpyxl has an ‘Alignment’ option for ‘wrap_text’, but I cannot see how to apply this to all cells.

Edit:

Thanks to feedback, the following does the trick. Note — copy due to styles being immutable.

for row in ws.iter_rows():
    for cell in row:      
        cell.alignment =  cell.alignment.copy(wrapText=True)

asked Feb 14, 2017 at 0:34

DerRabe's user avatar

DerRabeDerRabe

2731 gold badge2 silver badges6 bronze badges

1

I have been using openpyxl>=2.5.6. Let us say we want to wrap text for cell A1, then we can use the below code.

from openpyxl.styles import Alignment

ws['A1'].alignment = Alignment(wrap_text=True)

answered Sep 25, 2018 at 9:08

SuperNova's user avatar

SuperNovaSuperNova

24.7k6 gold badges91 silver badges63 bronze badges

0

Presumably, when you iterate through your cells, the idea would be to apply the format at that.

for row in ws.iter_rows():
    for cell in row:
        cell.style.alignment.wrap_text=True

There is also a fair amount more detail into how to use the wrap text style here
Writing multi-line strings into cells using openpyxl

Hope this helps.

Community's user avatar

answered Feb 14, 2017 at 18:07

Allan B's user avatar

Allan BAllan B

3092 silver badges9 bronze badges

1

import os
import openpyxl
from openpyxl.styles import Alignment, Font
from openpyxl.cell import Cell
#format cells with word wrap and top alignment    
for row in ws2.iter_rows():  
    for cell in row:      
        cell.alignment = Alignment(wrap_text=True,vertical='top') 

answered Jun 3, 2020 at 13:32

user13577089's user avatar

Update alignment in openpyxl v3

Many of the answers set wrapText=True but clobber existing alignment options. This is no good.

Using openpyxl v3.0.4, I did the following:

import copy

for row in ws.iter_rows():
    for cell in row:      
        alignment = copy.copy(cell.alignment)
        alignment.wrapText=True
        cell.alignment = alignment

The original poster’s solution uses:

cell.alignment =  cell.alignment.copy(wrapText=True)

But this produced the following warning:

DeprecationWarning: Call to deprecated function copy (Use copy(obj) or cell.obj = cell.obj + other).
  cell.alignment =  cell.alignment.copy(wrapText=True)

answered Jul 28, 2020 at 18:49

Daniel Himmelstein's user avatar

Iterates all cells

  for rows in ws.iter_rows(min_row=1, min_col=1):
    for cell in rows:
      print('cell %s %s' % (cell.coordinate,cell.value))

* Tested with Python:3.4.2 — openpyxl:2.4.1 *

answered Feb 14, 2017 at 7:52

stovfl's user avatar

stovflstovfl

14.8k7 gold badges24 silver badges51 bronze badges

В 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 1nLine 2nLine 3"

workbook.save('wrap_text1.xlsx')

Изображение 149466

Это также возможно с помощью 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 1nLine 2nLine 3", cell_format)

workbook.close()

Python:
Is there a way to write multi-line strings into an excel cell with just the xlwt module? (I saw answers suggesting use of openpyxl module)

The sheet.write() method ignores the n escape sequence. So, just xlwt, is it possible? Thanks in advance.

asked Sep 16, 2013 at 7:24

user2782845's user avatar

I found the answer in the python-excel Google Group. Using sheet.write() with the optional style argument, enabling word wrap for the cell, does the trick. Here is a minimum working example:

import xlwt
book = xlwt.Workbook()
sheet = book.add_sheet('Test')

# A1: no style, no wrap, despite newline
sheet.write(0, 0, 'HellonWorld')

# B1: with style, there is wrap
style = xlwt.XFStyle()
style.alignment.wrap = 1
sheet.write(0, 1, 'HellonWorld', style)
book.save('test.xls')

While in cell A1 shows HelloWorld without linebreak, cell B1 shows HellonWorld (i.e. with linebreak).

answered Sep 16, 2013 at 7:45

ojdo's user avatar

ojdoojdo

7,9254 gold badges34 silver badges60 bronze badges

0

If you don’t use XFStyle and instead easyxf it’s done like this:

import xlwt

style_head = xlwt.easyxf('alignment: wrap True')

row = 1
cell = 1
book = xlwt.Workbook(encoding='utf-8')
sheet = book.add_sheet()
sheet.write(row, cell, 'cell value', style_head)

answered Jul 4, 2019 at 12:30

Sam_slo's user avatar

Sam_sloSam_slo

1211 gold badge1 silver badge9 bronze badges

1

There are a few things you could try:

  1. Windows handles new lines differently to Unix/Linux. While n (line feed) character is the standard Unix method and also used in Python, Windows requires a carriage return and line feed. You could therefore try replacing n with rn.
  2. If this does not work then try replacing them with the ascii characters {chr(13) and chr(10)} inside a formula.
  3. If this still doesn’t work then it may be worth trying this article which suggests a rather more long winded way of approaching the problem.

answered Sep 16, 2013 at 7:53

ChrisProsser's user avatar

ChrisProsserChrisProsser

12.4k6 gold badges36 silver badges44 bronze badges

Introduction¶

Normally styles apply to everything in an individual cell. However, rich text
allows formatting of parts of the text in a string. This section covers
adding rich-text formatting to worksheet cells. Rich-text formatting in
existing workbooks has to be enabled when loading them with the
rich_text=True parameter.

Rich Text objects can contain a mix of unformatted text and
TextBlock objects that contains an InlineFont style and a
the text which is to be formatted like this. The result is a
CellRichText object.

>>> from openpyxl.cell.text import InlineFont
>>> from openpyxl.cell.rich_text import TextBlock, CellRichText
>>> rich_string1 = CellRichText(
...    'This is a test ',
...    TextBlock(InlineFont(b=True), 'xxx'),
...   'yyy'
... )

InlineFont objects are virtually identical to the Font
objects, but use a different attribute name, rFont, for the name of the
font. Unfortunately, this is required by OOXML and cannot be avoided.

>>> inline_font = InlineFont(rFont='Calibri', # Font name
...                          sz=22,           # in 1/144 in. (1/2 point) units, must be integer
...                          charset=None,    # character set (0 to 255), less required with UTF-8
...                          family=None,     # Font family
...                          b=True,          # Bold (True/False)
...                          i=None,          # Italics (True/False)
...                          strike=None,     # strikethrough
...                          outline=None,
...                          shadow=None,
...                          condense=None,
...                          extend=None,
...                          color=None,
...                          u=None,
...                          vertAlign=None,
...                          scheme=None,
...                          )

Fortunately, if you already have a Font object, you can simply
initialize an InlineFont object with an existing Font
object:

>>> from openpyxl.cell.text import Font
>>> font = Font(name='Calibri',
...             size=11,
...             bold=False,
...             italic=False,
...             vertAlign=None,
...             underline='none',
...             strike=False,
...             color='00FF0000')
>>> inline_font = InlineFont(font)

You can create InlineFont objects on their own, and use them later.
This makes working with Rich Text cleaner and easier:

>>> big = InlineFont(sz="30.0")
>>> medium = InlineFont(sz="20.0")
>>> small = InlineFont(sz="10.0")
>>> bold = InlineFont(b=True)
>>> b = TextBlock
>>> rich_string2 = CellRichText(
...       b(big, 'M'),
...       b(medium, 'i'),
...       b(small, 'x'),
...       b(medium, 'e'),
...       b(big, 'd')
... )

For example:

>>> red = InlineFont(color='00FF0000')
>>> rich_string1 = CellRichText(['When the color ', TextBlock(red, 'red'), ' is used, you can expect ', TextBlock(red, 'danger')])

The CellRichText object is derived from list, and can be used as such.

Whitespace¶

CellRichText objects do not add whitespace between elements when rendering
them as strings or saving files.

>>> t = CellRichText()
>>> t.append('xx')
>>> t.append(TextBlock(red, "red"))

You can also cast it to a str to get only the text, without formatting.

Editing Rich Text¶

As editing large blocks of text with formatting can be tricky, the
as_list() method returns a list of strings to make indexing easy.

>>> l = rich_string1.as_list()
>>> l
['When the color ', 'red', ' is used, you can expect ', 'danger']
>>> l.index("danger")
3
>>> rich_string1[3].text = "fun"
>>> str(rich_string1)
'When the color red is used, you can expect fun'

Rich Text assignment to cells¶

Rich Text objects can be assigned directly to cells

>>> from openpyxl import Workbook
>>> wb = Workbook()
>>> ws = wb.active
>>> ws['A1'] = rich_string1
>>> ws['A2'] = 'Simple string'

У меня есть фрейм данных Pandas, который я записываю в XLSX, используя openpyxl. Многие ячейки в электронной таблице содержат длинные предложения, и я хочу установить wrap_text для всего содержимого листа (то есть для каждой ячейки).

Есть ли способ сделать это? Я видел, что openpyxl имеет опцию ‘Alignment’ для ‘wrap_text’, но я не вижу, как применить это ко всем ячейкам.

Редактировать:

Благодаря обратной связи, следующее делает свое дело. Примечание — копирование из-за того, что стили неизменны.

for row in ws.iter_rows():
    for cell in row:      
        cell.alignment =  cell.alignment.copy(wrapText=True)

3 ответа

Лучший ответ

Предположительно, когда вы перебираете свои ячейки, идея заключается в том, чтобы применить формат при этом.

for row in ws.iter_rows():
    for cell in row:
        cell.style.alignment.wrap_text=True

Здесь также есть довольно много подробностей о том, как использовать стиль переноса текста здесь Запись многострочных строк в ячейки с использованием openpyxl

Надеюсь это поможет.


7

Community
23 Май 2017 в 12:34

Я использовал openpyxl> = 2.5.6. Допустим, мы хотим обернуть текст для ячейки A1, тогда мы можем использовать приведенный ниже код.

from openpyxl.styles import Alignment

ws['A1'].alignment = Alignment(wrap_text=True)


14

SuperNova
21 Окт 2019 в 06:10

Перебирает все ячейки

  for rows in ws.iter_rows(min_row=1, min_col=1):
    for cell in rows:
      print('cell %s %s' % (cell.coordinate,cell.value))

* Протестировано с Python: 3.4.2 — openpyxl: 2.4.1 *


1

stovfl
14 Фев 2017 в 09:27

Понравилась статья? Поделить с друзьями:
  • Перенос части слова на другую строку в word
  • Перенос цифр в excel
  • Перенос цвета ячейки в excel
  • Перенос фрагментов в word
  • Перенос фрагмента в word