Перенос строки python excel

I’m trying to write data into a cell, which has multiple line breaks (I believe n), the resulting .xlsx has line breaks removed.
Is there a way to keep these line breaks?

asked Mar 12, 2013 at 19:29

user1514631's user avatar

The API for styles changed for openpyxl >= 2. The following code demonstrates the modern API.

from openpyxl import Workbook
from openpyxl.styles import Alignment

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

DowntownDev's user avatar

answered Jun 6, 2016 at 7:27

Charlie Clark's user avatar

Charlie ClarkCharlie Clark

18.1k4 gold badges47 silver badges54 bronze badges

3

Disclaimer: This won’t work in recent versions of Openpyxl. See other answers.

In openpyxl you can set the wrap_text alignment property to wrap multi-line strings:

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

enter image description here

This is also possible with the XlsxWriter module.

Here is a small working example:

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

Eldamir's user avatar

Eldamir

9,6886 gold badges46 silver badges73 bronze badges

answered Mar 13, 2013 at 11:35

jmcnamara's user avatar

jmcnamarajmcnamara

37k6 gold badges86 silver badges105 bronze badges

6

Just an additional option, you can use text blocking «»» my cell info here «»» along with the text wrap Boolean in alignment and get the desired result as well.

from openpyxl import Workbook
from openpyxl.styles import Alignment

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

Manuel's user avatar

Manuel

5343 silver badges9 bronze badges

answered Sep 28, 2020 at 12:14

Steven Barnard's user avatar

Just in case anyone is looking for an example where we iterate over all cells to apply wrapping:

Small working example:

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

answered Oct 25, 2021 at 13:17

Francesco Pisu's user avatar

В 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'

17.11.2016, 18:39. Показов 2657. Ответов 0


Студворк — интернет-сервис помощи студентам

Добрый день!
Помогите с решением задачи, не понимаю как сделать цикл, чтобы проверял наличие записей в строке и если есть, переходил на следующую и добавлял туда свежие данные из базы.
То есть, каждый раз, когда выполняется скрипт, создавалась новая строка ниже с данными.

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from datetime import datetime
import xlwt
import cx_Oracle
 
dsn_tns = cx_Oracle.makedsn('host', 'port', 'sid')
db = cx_Oracle.connect('test', 'test', dsn_tns)
 
cursor = db.cursor()
cursor.execute('select count(c.DATE) from test_1 c where c.DATE > TRUNC(SYSDATE)')
 
for sql_row in cursor:
    print(sql_row[0])
 
book = xlwt.Workbook()
sheet = book.add_sheet('Test')
style = xlwt.XFStyle()
style.num_format_str = 'D-MMM-YY'
 
sheet.write(0, 0, datetime.now(), style)
sheet.write(0, 1, sql_row[0])
 
book.save('sql-test.xls')

И еще вопрос, в 20 строке ругается на sql_row[0]this inspection warns about local variable referenced before assignment, если сделать так, то ошибка пропадает, на сколько правильное это решение? Как сделать правильно?

Python
1
2
3
4
5
6
7
8
client_count = None
 
for sql_row in cursor:
    if client_count is None:
        client_count = sql_row[0]
    print(sql_row[0])
 
sheet.write(0, 1, client_count)

Заранее спасибо за любую помощь!

Добавлено через 6 часов 5 минут
Неактуально, сделал…

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from xlutils.copy import copy
from datetime import datetime
import cx_Oracle
import xlwt
import xlrd
def get_clients_count():
    cursor = db.cursor()
    cursor.execute('select count(c.DATE) from test_1 c where c.DATE > TRUNC(SYSDATE)')
    for sql_row in cursor:
        print(sql_row[0])
    return sql_row[0]
dsn_tns = cx_Oracle.makedsn('host', 'port', 'sid')
db = cx_Oracle.connect('test', 'test', dsn_tns)
clients_count = get_clients_count()
style = xlwt.XFStyle()
style.num_format_str = 'D-MMM-YY'
wb = xlrd.open_workbook('sql-test.xls', formatting_info=True)
r_sheet = wb.sheet_by_index(0)
r = r_sheet.nrows
book = copy(wb)
sheet = book.get_sheet(0)
sheet.write(r, 0, datetime.now(), style)
sheet.write(r, 1, clients_count)
book.save('sql-test.xls')



0



Понравилась статья? Поделить с друзьями:
  • Перенос строки в ячейке excel код символа
  • Перенос строки excel alt
  • Перенос строки csv excel
  • Перенос строки в ячейке excel горячие клавиши
  • Перенос строк ячейки vba excel