https://www.cnblogs.com/miki-peng/p/12904383.html 【python接口自动化】- openpyxl读取excel数据 2021-8-11
写EXCEL文件(xlwt库)
# -*- coding: utf-8 -*- import xlwt book = xlwt.Workbook(encoding = "utf-8", style_compression = 0)#创建一个Wordbook对象,相当于创建了一个Excel文件 sheet = book.add_sheet("sheet1", cell_overwrite_ok = True)#创建一个sheet对象,一个sheet对象对应Excel文件中的一张表格 #向表sheet1中添加数据 #sheet.write(0, 0, "1行1列") #sheet.write(1, 0, "2行1列") #sheet.write(0, 1, "1行2列") #sheet.write(1, 1, "2行2列") for i in range(0,30): sheet.write(i,0,i) sheet.write(i,1,i*2) sheet.write(i,2,i*3) #最后,将以上操作保存到指定的Excel文件中 book.save("zz.xls")
读EXCEL文件的内容(xlrd库)
import xlrd xls_file = "zz.xls" book = xlrd.open_workbook(xls_file)#打开指定文件 sheet1 = book.sheet_by_index(0)# 通过sheet索引获得sheet对象 # 获得行数和列数 nrows = sheet1.nrows# 总行数 ncols = sheet1.ncols#总列数 # 遍历打印表中的内容 for i in range(nrows): for j in range(ncols): cell_value = sheet1.cell_value(i, j) print(cell_value, end = "\t") print("")
读EXCEL文件的内容(pandas库)
# -*- coding: utf-8 -*- #coding=utf-8 __author__ = '' # 打开"20240427sun.xlsx"的Sheet2,对“游玩人数”列进行可视化 import pandas as pd import matplotlib import matplotlib.pyplot as plt matplotlib.rcParams['font.sans-serif'] = ['SimHei']# 为了能显示中文(而不是显示一个框) matplotlib.rcParams['font.family']='sans-serif' matplotlib.rcParams['axes.unicode_minus'] = False # 为了能显示负号(而不是显示一个框) excel_path = "c:\\Python3\\zz\\20240427sun.xlsx" try: # 读取Sheet2 df = pd.read_excel(excel_path, sheet_name='Sheet2', engine='openpyxl') play_counts = df['游玩人数'].tolist() print(play_counts) except Exception as e: # 如果发生错误,比如列名不存在,打印错误信息 print("error:"+ e) x=[] y=[] for i in range(len(play_counts)): x.append(i) y.append(play_counts[i]) print(play_counts[i]) # print(len(play_counts)) def scatterPlots(): plt.figure(figsize=(14, 8)) # 屏幕大小 plt.title('游玩人数',color='#ff33a0') plt.xlabel('x轴:天数') # 设置X坐标轴标题 plt.ylabel('y轴:游玩人数') # 设置Y坐标轴表 plt.xlim(0, 365) # 设置坐标轴的范围(设置坐标轴取值范围 plt.ylim(0, 300000) # r:red, b:blue, g:green, y:yellow, k:black, w:white, c:cyan蓝绿色, m:magenta品红 # plt.plot(x, y, 'b') # 不写 o*sphx+Dd 等参数,是折线图 plt.plot(x, y, 'sb') plt.show() scatterPlots()
...