首页 > 编程语言 > 详细

Python操作Excel表格

时间:2018-06-11 21:13:32      阅读:203      评论:0      收藏:0      [点我收藏+]

 

使用xlwt + xlrd + xlutils操作Excel表格

 

# coding: utf-8
import xlwt
from xlrd import open_workbook
from xlutils.copy import copy
import os
import sys
reload(sys)
sys.setdefaultencoding(utf-8)


def save_excel(my_list):
    path = os.getcwd()
    file_path = path + os.sep + grade.xls
    style_bold = xlwt.easyxf(font: color-index red, bold on)
    header_style = style_bold
    workbook = xlwt.Workbook(encoding=utf-8)
    book_sheet = workbook.add_sheet(Sheet 1, cell_overwrite_ok=True)
    i = 0
    for x, item in enumerate(my_list):
        book_sheet.write(i, x, item, header_style)
    workbook.save(file_path)


def xlutil(my_list):
    try:
        path = os.getcwd()
        file_path = path + os.sep + grade.xls
        rexcel = open_workbook(file_path, formatting_info=True)  # 用wlrd提供的方法读取一个excel文件
        rows = rexcel.sheets()[0].nrows  # 用wlrd提供的方法获得现在已有的行数
        print "rows:", rows
        first_row = [title, pub_time, aid, view, danmaku, favorite, coin, share, author, sex]
        style_bold = xlwt.easyxf(font: color-index red, bold on)
        header_style = style_bold
        excel = copy(rexcel)  # 用xlutils提供的copy方法将xlrd的对象转化为xlwt的对象
        table = excel.get_sheet(0)  # 用xlwt对象的方法获得要操作的sheet
        if rows == 0:
            for y, value in enumerate(first_row):
                table.write(rows, y, value.decode(utf-8), header_style)
            excel.save(file_path)
        else:
            for y, value in enumerate(my_list):
                table.write(rows, y, value.decode(utf-8))
            excel.save(file_path)
    except Exception, e:
        print e
        print "请先关闭grade.xls"


if __name__ == __main__:
    # path = os.getcwd()
    # file_path = path + os.sep + ‘grade.xls‘
    # w = xlwt.Workbook(encoding=‘utf-8‘)
    # ws = w.add_sheet(‘Sheet 1‘, cell_overwrite_ok=True)
    # w.save(file_path)
    my_list = [34, 2017-10-16 14:42, 44, 67, 1, 3, 0, 0, 69, 33]
    # save_excel(my_list)
    xlutil(my_list)

 

Python操作Excel表格

原文:https://www.cnblogs.com/delav/p/9169110.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!