近段时间由于工作中需要对一些数据的整理和可视化显示,故记下使用python操作Excel可视化操作,方便后续查阅。
一、数据导入Excel
Demo:
#!/usr/bin/env python# -*- coding: utf-8 -*-# @File Name: python_excel.py# @Time : 2019/7/25# @Author : zhong# @Blog : https://www.jianshu.com/search?q=keitwo&page=1&type=note# @QQ交流 : 3227456102import xlsxwriter # 导入模块workbook = xlsxwriter.Workbook('7月生活消费.xlsx') # 新建excel表worksheet = workbook.add_worksheet('消费表') # 新建sheet(sheet的名称为"sheet1")headings = ['Number', '交通费', '伙食费','通讯费'] # 设置表头data = [ ['2019-7-1', '2019-7-2', '2019-7-3', '2019-7-4', '2019-7-5', '2019-7-6'], [10, 40, 50, 20, 10, 50], [30, 60, 70, 50, 40, 30], [100,50,150,50,100,50],] # 自己造的数据worksheet.write_row('A1', headings)worksheet.write_column('A2', data[0])worksheet.write_column('B2', data[1])worksheet.write_column('C2', data[2]) # 将数据插入到表格中worksheet.write_column('C2', data[3])workbook.close() # 将excel文件保存关闭,如果没有这一行运行代码会报错
运行结果:
二、给数据添加格式和汇总
Demo:
#!/usr/bin/env python# -*- coding: utf-8 -*-# @File Name: python_excel.py# @Time : 2019/7/25# @Author : zhong# @Blog : https://www.jianshu.com/search?q=keitwo&page=1&type=note# @QQ交流 : 3227456102# 导入模块import xlsxwriter# 新建excel表workbook = xlsxwriter.Workbook('7月生活消费.xlsx')# 新建sheet(sheet的名称为"消费表")worksheet = workbook.add_worksheet('消费表')# 设置表头headings = ['Number', '交通费', '伙食费','通讯费']# 自己造的数据data = [ ('2019-7-1', '2019-7-2', '2019-7-3', '2019-7-4', '2019-7-5', '2019-7-6'), (10, 40, 50, 20, 10, 50), (30, 60, 70, 50, 40, 30), (100,50,150,50,100,50),]worksheet.write_row('A1', headings)# 添加全局格式bold =workbook.add_format({
'bold':True})money = workbook.add_format({
'num_format':'$#,##0'})# 添加表头附带格式# worksheet.write('B2','交通费',bold)# worksheet.write('C2','