Sto provando a scrivere i dati in una cella, che ha più interruzioni di riga (credo \ n), il risultato .xlsx ha interruzioni di riga rimosse. C'è un modo per mantenere queste interruzioni di riga?Scrittura di stringhe multi-linea nelle celle utilizzando openpyxl
8
A
risposta
19
In openpyxl
è possibile impostare la proprietà di allineamento wrap_text
per avvolgere le stringhe multilinea:
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')
Ciò è possibile anche con il modulo XlsxWriter.
Ecco un piccolo esempio di lavoro:
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()
17
L'API per gli stili cambiato per openpyxl> = 2. Il codice di seguito viene illustrato l'API moderno.
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")
grazie per il vostro aiuto. Conosci per caso una buona documentazione per python openpyxl con esempi? – user1514631
Gli ultimi documenti OpenPyXL sono [qui] (https://openpyxl.readthedocs.org/en/latest/index.html). Tuttavia, ho capito la sintassi sopra leggendo il codice (e avendo un'idea generale di cosa stavo cercando). XlsxWriter ha dettagliato [docs] (https://xlsxwriter.readthedocs.org/en/latest/contents.html) e [esempi] (https://xlsxwriter.readthedocs.org/en/latest/examples.html). – jmcnamara
Ottengo la duplicazione su entrambi i moduli XlsxWriter e openpyxl. (Ad esempio, quando scrivo "line1 \ n line2" viene visualizzato "line1 \ n line2 line1 \ n line2" –