• Python写入数据至Excel文件中--学习笔记


    import xlwt
    
    class WritrExcel():
    
        def set_style(self,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
    
        #写入Excel
        def write_excel(self,path,rows):
            # 创建工作簿
            workbook = xlwt.Workbook(encoding='utf-8')
            # 创建sheet
            data_sheet = workbook.add_sheet('Sheet1')
            #将样式定义在循环之外
            default = self.set_style('Times New Roman', 220, True)
            j = k = 0
            # 循环读取每一行数据并写入Excel
            for row in rows:
                for i in range(len(row)):
                    try:
                        # 写入
                        data_sheet.write((j + k), i, row[i], default)
                    except :
                        print(i)
                        raise
                    # data_sheet.write(1, i, row1[i], self.set_style('Times New Roman', 220, True))
                k = k + 1
            workbook.save(path)
            print("写入文件成功,共" + str(k) + "行数据")
    
    
    if __name__ == '__main__':
        # 设置路径
        rows = (
            ('字段名称', '大致时段', 'CRNTI', 'CELL-ID'),
            ('测试0', '15:50:33-15:52:14', '22706', '4190202'),
            ('测试1', '15:50:33-15:52:14', '22706', '4190202'),
            ('测试2', '15:50:33-15:52:14', '22706', '4190202')
        )
        path = 'demo.xls'
        WritrExcel().write_excel(path,rows)
        print(u'创建demo.xls文件成功')
  • 相关阅读:
    tuple-1
    禅语-1
    综述的写作技巧-1
    皆大欢喜组合
    类和对象-3
    双棍练习
    CodeBlocks开发环境使用-1
    类和对象-2
    类和对象-1
    13-归并排序-分治策略应用于排序
  • 原文地址:https://www.cnblogs.com/siyz/p/9517515.html
Copyright © 2020-2023  润新知