zoukankan      html  css  js  c++  java
  • Python操作Excel表格

    使用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)
  • 相关阅读:
    缓存概述
    进程Process
    MVC系统过滤器、自定义过滤器
    暂无,进程那篇深度不够
    SeasLog 与 monolog 日志系统的区别,SeasLog安装步骤
    阿里面试官:说一下从url输入到返回请求的过程,问的难度就是不一样!
    [技术分享]OSI七层模型详解
    Mysql引擎介绍及InnoDB逻辑存储结构
    Paypal 实现自动订阅
    PayPal 支付Checkout 收银台和 Subscription 订阅计划全过程分享
  • 原文地址:https://www.cnblogs.com/delav/p/9169110.html
Copyright © 2011-2022 走看看