Python excel 写入的问题 使用python读写excel的问题
python \u5199\u5165excel \u95ee\u9898\u4e00\u76f4\u62a5\u9519def eachrowintext(filename, spliter=','):
with open(filename, 'r') as handle:
for ln in handle:
yield ln.strip().split(spliter)
def write2sheet(sheet, iter_rows, baserow=1, basecol=1):
for j, row in enumerate(iter_rows):
for i, item in enumerate(row):
sheet.write(baserow+j, basecol+i, item)
wb=xlwt.Workbook()
ws=wb.add_sheet('hongan3')
write2sheet(ws, eachrowintext('61610400.txt'))
wb.save("hongan11.xls")
\u53ef\u4ee5\uff0c\u5982\u679carcgis\u662f10\u7248\u672c\uff0c\u53ef\u4ee5\u7528arcpy\u6a21\u5757\u4e2d\u7684SearchCursor\u8bfb\u53d6shp\u7684\u5c5e\u6027\u8868\uff1b\u7528python\u8bfb\u5199excel\u9700\u8981\u5b89\u88c5pythonWin\u6216\u8005\u5b89\u88c5comtypes\u90fd\u53ef\u4ee5\uff0c\u4f60\u53ef\u4ee5\u4e0a\u7f51\u627e\u4e00\u4e0b\u8fd9\u6837\u7684\u8d44\u6599\u3002
(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中输出中文了。
默认是ascii。当然要记得在文件头部添加:
#!/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:est1.xls') # 在字符串前加r,声明为raw字符串,这样就不会处理其中的转义了。否则,可能会报错
#for Python 3
txt1 = '中文名字'
sheet.write(0, 1, txt1.encode('utf-8').decode('utf-8')) # 此处需要将中文字符串解码成unicode码,否则会报错
txt2 = '马可瓦多'
sheet.write(1, 1, txt2.encode('utf-8').decode('utf-8'))
扩展阅读:python手机版下载官方 ... python基础代码大全 ... python代码自动生成器 ... python excel temple ... python登录网站 ... 用python新建一个excel ... python让excel自动化 ... python for beginners ... python excel pandas ...