您的位置:首页 > 编程语言 > Python开发

如何用Python修改Excel数据

2013-05-08 18:49 435 查看
在前面的文章中介绍了如何用Python读写Excel数据,今天再介绍一下如何用Python修改Excel数据。需要用到xlutils模块。下载地址为https://pypi.python.org/pypi/xlutils。下载后执行pythonsetup.pyinstall命令进行安装即可。

具体使用代码如下:

#-*-coding:utf-8-*-
fromxlutils.copyimportcopy#http://pypi.python.org/pypi/xlutilsfromxlrdimportopen_workbook#http://pypi.python.org/pypi/xlrdfromxlwtimporteasyxf#http://pypi.python.org/pypi/xlwt
importsys
reload(sys)
sys.setdefaultencoding('utf-8')

#0based(subtract1fromexcelrownumber)
START_ROW=404

ismal_index=2
#url所在列
url_index=12
#domain所在列
domain_index=11
#malinfo所在列
malinfo_index=9

file_path="C:\\Users\\***\\Desktop\\20130514.xls"
#formatting_info=True保存之前数据的格式
rb=open_workbook(file_path,formatting_info=True)
r_sheet=rb.sheet_by_index(0)#readonlycopytointrospectthefile
wb=copy(rb)#awritablecopy(Ican'treadvaluesoutofthis,onlywritetoit)
w_sheet=wb.get_sheet(0)#thesheettowritetowithinthewritablecopy

malurl='''http://xbox.ooqqxx.com/res/ext.jarhttp://xbox.ooqqxx.com/res/stat.jarhttp://xbox.ooqqxx.com/pages/v.htmlhttp://xbox.ooqqxx.com/pages/extv.htmlhttp://xbox.ooqqxx.com/pages/r.html'''
domain_info="http://xbox.ooqqxx.com"
malinfo=u"获取恶意URL,写入配置文件中,下载恶意可执行程序。"

#r_sheet.nrows为总行数
forrow_indexinrange(START_ROW,r_sheet.nrows):
#xlsvalue=r_sheet.cell(row_index,col_age_november).value
w_sheet.write(row_index,ismal_index,u'是')
w_sheet.write(row_index,url_index,malurl)
w_sheet.write(row_index,domain_index,domain_info)
w_sheet.write(row_index,malinfo_index,malinfo)
#wb.save(file_path+'.out'+os.path.splitext(file_path)[-1])
wb.save("C:\\Users\\***\\Desktop\\2013.xls")


注意:

如果在写入数据(中文)时出现以下错误:

asciicodeccan'tdecodebyte0xe8inposition0:ordinalnotinrange(128)


则需加上以下代码:

importsys
reload(sys)
sys.setdefaultencoding('utf-8')


另外,则中文字符串前记得加上u.


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: