Python操作Excel

安装模块

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文件成功'
原文地址:https://www.cnblogs.com/cnki/p/6971625.html