乔山办公网我们一直在努力
您的位置:乔山办公网 > excel表格制作 > 如何利用<em>python</em>将中文文档写入<em>excel</em

如何利用<em>python</em>将中文文档写入<em>excel</em

作者:乔山办公网日期:

返回目录:excel表格制作


确实还真就没用过这样的函数,不过可以自己实现。

就是把插e799bee5baa6e59b9ee7ad94366入行之后值重新输出来。

import xlwt;
import xlrd;
from xlutils.copy import copy;
 
#styleBoldRed   = xlwt.easyxf('font: color-index red, bold on');
#headerStyle = styleBoldRed;
#wb = xlwt.Workbook();
#ws = wb.add_sheet('sheetName');
#ws.write(0, 0, "Col1",        headerStyle);
#ws.write(0, 1, "Col2", headerStyle);
#ws.write(0, 2, "Col3",    headerStyle);
#wb.save('fileName.xls');

#open existed xls file
oldWb = xlrd.open_workbook("fileName.xls", formatting_info=True);
oldWbS = oldWb.sheet_by_index(0)
newWb = copy(oldWb);
newWs = newWb.get_sheet(0);
inserRowNo = 1
newWs.write(inserRowNo, 0, "value1");
newWs.write(inserRowNo, 1, "value2");
newWs.write(inserRowNo, 2, "value3");

for rowIndex in range(inserRowNo, oldWbS.nrows):
    for colIndex in range(oldWbS.ncols):
        newWs.write(rowIndex + 1, colIndex, oldWbS.cell(rowIndex, colIndex).value);
newWb.save('fileName.xls');
print "save with same name ok";



(1)对Excel的写操作:

# -*- coding: utf-8 -*-
#导入xlwt模块
import xlwt
# 创建一个Workbook对象,这就相当于创建了一个Excel文件
book = xlwt.Workbook(encoding='utf-8', style_compression=0)
'''
Workbook类初始化时有encoding和style_compression参数
encoding:设置字符编码,一般要这样设置:w = Workbook(encoding='utf-8'),就可以在excel中输出中文了。
默认是e79fa5e98193e58685e5aeb9363ascii。当然要记得在文件头部添加:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
style_compression:表示是否压缩,不常用。
'''
#创建一个sheet对象,一个sheet对象对应Excel文件中的一张表格。
# 在电脑桌面右键新建一个Excel文件,其中就包含sheet1,sheet2,sheet3三张表
sheet = book.add_sheet('test', cell_overwrite_ok=True)
# 其中的test是这张表的名字,cell_overwrite_ok,表示是否可以覆盖单元格,其实是Worksheet实例化的一个参数,默认值是False
# 向表test中添加数据
sheet.write(0, 0, 'EnglishName')  # 其中的'0-行, 0-列'指定表中的单元,'EnglishName'是向该单元写入的内容
sheet.write(1, 0, 'Marcovaldo')
txt1 = '中文名字'
sheet.write(0, 1, txt1.decode('utf-8'))  # 此处需要将中文字符串解码成unicode码,否则会报错
txt2 = '马可瓦多'
sheet.write(1, 1, txt2.decode('utf-8'))
 
# 最后,将以上操作保存到指定的Excel文件中
book.save(r'e:\test1.xls')  # 在字符串前加r,声明为raw字符串,这样就不会处理其中的转义了。否则,可能会报错


style = xlwt.XFStyle() # 初始化样
font = xlwt.Font() # 为样式创建字体
style.font = font # 设定样
style.alignment.wrap = 1#自动换行
使用:
worksheet1.write(0, 0, 'line1\r\nline2', style)

相关阅读

关键词不能为空
极力推荐

ppt怎么做_excel表格制作_office365_word文档_365办公网