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

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()

У меня есть фрейм данных 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

I’m using openpyxl to open an .xlsx file, update some values in it and save it as a different .xlsx file. I am trying to add a footer with new lines in it:

# example code
wb = openpyxl.load_workbook('file.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
sheet.header_footer.left_footer.font_size = 7
sheet.header_footer.left_footer.text = '&BSome text&BnMore textnEven more'
sheet.header_footer.right_footer.font_size = 7
sheet.header_footer.right_footer.text = 'Page &P of &N'
wb.save('new_file.xlsx')

But when I open newly created file and look at the footer, n gets replaced in a weird way:

Some text^lMore text^pEven more

I have also noticed that if I try to convert it to PDF with a help of libreoffice, e.g. like this:

os.system('libreoffice --headless --invisible --convert-to pdf --outdir /path/on/disk new_file.xlsx')

the generated PDF renders it out to something different again:

Some text_x000D_More text_x000D_Even more

How can I properly generate new line in the footer?
(Might be worth of mentioning that I’m using openpyxl 2.3.3 with Python 3.4 on Ubuntu 14.04. Version of LibreOffice is 5.0.5.2)

Пример программы для настройки выравнивания ячеек.

from openpyxl import Workbook
from openpyxl.styles import Alignment

wb = Workbook()
ws = wb.active
ws.title = "Test"
ws['A1'] = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis sollicitudin mauris. Integer in mauris eu nibh euismod gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue, eros est euismod turpis, id tincidunt sapien risus a quam. Maecenas fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis, neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing sapien, sed malesuada diam lacus eget erat. Cras mollis scelerisque nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis, molestie eu, feugiat in, orci. In hac habitasse platea dictumst."""
c = ws['A1']
c.alignment = Alignment(horizontal='general', vertical='bottom', text_rotation=0, wrap_text=True, shrink_to_fit=False, indent=0)
wb.save("test.xlsx")

РЕДАКТИРОВАТЬ

Причина, по которой это не сработало, заключается в том, что

>>> type(c.alignment)
<class 'openpyxl.styles.proxy.StyleProxy'>

Это объект Style Proxy, который не позволяет получить доступ к атрибутам. Вы можете назначить только новый стиль. Вы можете посмотреть исходник здесь

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