的Python: 有没有办法只用xlwt模块将多行字符串写入excel单元格? (我看到建议使用openpyxl模块的答案)
sheet.write()
方法忽略\ n转义序列。那么,只有xlwt,这可能吗?提前致谢。
答案 0 :(得分:23)
我在python-excel Google Group找到了答案。使用sheet.write()
和可选的style
参数,启用单元格的自动换行功能。以下是最低工作示例:
import xlwt
book = xlwt.Workbook()
sheet = book.add_sheet('Test')
# A1: no style, no wrap, despite newline
sheet.write(0, 0, 'Hello\nWorld')
# B1: with style, there is wrap
style = xlwt.XFStyle()
style.alignment.wrap = 1
sheet.write(0, 1, 'Hello\nWorld', style)
book.save('test.xls')
虽然在单元格A1中显示HelloWorld
没有换行符,但单元格B1显示Hello\nWorld
(即有换行符)。
答案 1 :(得分:1)
如果您不使用XFStyle,而是使用easyxf,则可以这样做:
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)
答案 2 :(得分:0)
您可以尝试一些事项:
\n
(换行符)字符是标准Unix方法并且也在Python中使用,但Windows需要回车符和换行符。因此,您可以尝试将\n
替换为\r\n
。