zoukankan      html  css  js  c++  java
  • python36--将数据保存为excel

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import xlwt
    import os
    
    
    class ExcelHelper(object):
        @staticmethod
        def create_excel(column_heads, row_items, file_path):
            book = xlwt.Workbook(encoding='utf-8', style_compression=0)
            sheet = book.add_sheet('sheet1', cell_overwrite_ok=True)
            column_count = len(column_heads)
            row_count = len(row_items)
            # 写入列标题
            for column_id in range(column_count):
                sheet.write(0, column_id, column_heads[column_id])
            # 遍历所有行
            for row_id in range(row_count):
                row_item = row_items[row_id]
                # 遍历每行的所有列
                for column_id in range(column_count):
                    # 将每一行的对应列写sheet中
                    sheet.write(row_id + 1, column_id, row_item[column_id])
            # 保存文件
            if os.path.exists(file_path):
                os.remove(file_path)
            book.save(file_path)
    
    
    def demo():
        column_heads = ["姓名", "学校", "出生日期", "年龄"]
        row_items = [
            ["张删", "北京大学", "1988-01-02", 29],
            ["王二小", "清华大学", "1989-01-02", 28],
        ]
        file_path = r"d:	1.xls"
        ExcelHelper.create_excel(
            column_heads=column_heads,
            row_items=row_items,
            file_path=file_path
        )
        print("file {0} was created".format(file_path))
    
    
    if __name__ == '__main__':
        demo()

    引入xlwt需要安装openpyxl包

    =========================================================================

  • 相关阅读:
    offsetheight和clientheight和scrollheight的区别以及offsetwidth和clientwidth和scrollwidth的区别
    响应时间控制
    浏览器兼容
    生成随机数
    递归加载目录
    用委托定义的冒泡排序法
    ref 与out
    二维数组与交错数组的理解
    C#学习
    Jquery选择器
  • 原文地址:https://www.cnblogs.com/TeyGao/p/8799454.html
Copyright © 2011-2022 走看看