码迷,mamicode.com
首页 > 编程语言 > 详细

Python操作Excel

时间:2017-06-09 14:12:40      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:range   name   main   save   time   int   for   exce   样式   

安装模块

Python操作excel主要用到xlrd和xlwt这两个库,即xlrd是读excel,xlwt是写excel的库。

pip2 install xlrd

pip2 install xlwt

xlrd是读excel

 

 

xlwt是写excel

# ecoding:utf-8

import os
import xlwt

def set_style(name, height, bold = False):
    style = xlwt.XFStyle()   #初始化样式

    font = xlwt.Font()       #为样式创建字体
    font.name = name
    font.bold = bold
    font.color_index = 4
    font.height = height

    style.font = font
    return style

def write_excel():
    #创建工作簿
    workbook = xlwt.Workbook(encoding=‘utf-8‘)
    #创建sheet
    data_sheet = workbook.add_sheet(‘Sheet1‘)
    row0 = [u‘第一列‘, u‘第二列‘, u‘第三列‘,u‘第四列‘]
    row1 = [u‘第一列‘, u‘第二列‘, u‘第三列‘,u‘第四列‘]

    #生成第一行和第二行
    for i in range(len(row0)):
        data_sheet.write(0, i, row0[i], set_style(‘Times New Roman‘, 220, True))
        data_sheet.write(1, i, row1[i], set_style(‘Times New Roman‘, 220, True))

    #保存文件
    workbook.save(‘demo.xls‘)

if __name__ == ‘__main__‘:
    write_excel()
    print u‘创建demo.xlsx文件成功‘

 

Python操作Excel

标签:range   name   main   save   time   int   for   exce   样式   

原文地址:http://www.cnblogs.com/cnki/p/6971625.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!