The Chinese characters of excel file cells generated by xlwt are garbled


The system is Mac, Office 2011 is used, python is installedxlwt

The code is as follows:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
import xlwt 

file = xlwt.Workbook(encoding = 'utf-8') 
table = file.add_sheet('hello', cell_overwrite_ok = True) 

table.write(1, 1, '测试')'demo.xls')

The data is written into demo.xls file. After the file is opened, the contents of the cell are all scrambled. However, if the mouse clicks on the cell, the inside display in the formula bar (fx) above is normal (as shown in the figure below). If the file is opened in windows inside, the Chinese language can be displayed normally. What is the reason? How to solve it?



According to @fen, the following code was added to solve the problem:

style = xlwt.XFStyle()
font = xlwt.Font() = 'SimSun'    # 指定“宋体”
style.font = font       

table.write(1, 1, '测试', style) # 使用 style

It’s the font, not the code.

很多由程序导出生成的 Word, Excel 经常出现这样的问题,其实只要先选择整个文档的内容(CMD+A),然后再把字体替换成中文的(比如宋体),就会正常显示了。缺点就是中英文字体都会变成一致了。

Xlwt should be able to specify fonts when generating files, you have a try. After all, replacing fonts is not a good step for users.