Excel实现报表
應用知識點
使用python創(chuàng)建、保存excel
設置表單、插入文字等
設置文字顏色,合并單元格等
excel數(shù)據(jù)讀取、轉(zhuǎn)換操作
python的with用法
mysql數(shù)據(jù)庫
實現(xiàn)功能
插入圖表并實現(xiàn)報表
with用法
def open_file():""" 使用with語法打開一個文件 """try:f = open('./static/test.txt', 'r', encoding='utf-8')rest = f.read()print(rest)except:passfinally:f.close()# with open('./static/test.txt', 'r', encoding='utf-8') as f:# rest = f.read()# print(rest)if __name__ == '__main__':open_file()操作Excel
from datetime import datetime import MySQLdbfrom openpyxl import Workbook, load_workbook from openpyxl.drawing.image import Image from openpyxl.styles import Font, colorsclass ExcelUtils(object):"""pip install openpyxlpip install pillow"""def __init__(self):self.wb = Workbook()self.ws = self.wb.activeself.ws_two = self.wb.create_sheet('我的表單')self.ws.title = '你的表單'self.ws.sheet_properties.tabColor = 'ff0000'self.ws_three = self.wb.create_sheet()def do_sth(self):# 插入數(shù)據(jù)self.ws['A1'] = 66self.ws['A2'] = '你好'self.ws['A3'] = datetime.now()for row in self.ws_two['A1:E5']:for cell in row:cell.value = 2# 對數(shù)據(jù)進行求和self.ws_two['G1'] = '=SUM(A1:E1)'# 設置文字font = Font(sz=18, color=colors.RED)self.ws['A2'].font = font# 插入圖片# img = Image('./static/temp.jpg')# self.ws.add_image(img, 'B1')self.ws.merge_cells('A4:E5')self.ws.unmerge_cells('A4:E5')self.wb.save('./static/test.xlsx')def read_xls(self):"""讀取excel數(shù)據(jù):return:"""ws = load_workbook('./static/template.xlsx')names = ws.get_sheet_names()print(names)conn = self.get_conn()wb = ws.activewb = ws[names[0]]for (i, row) in enumerate(wb.rows):if i < 2:continueyear = wb['A{0}'.format(i + 1)].valuemax = wb['B{0}'.format(i + 1)].valueavg = wb['C{0}'.format(i + 1)].valueprint(year)if year is None:continuecursor = conn.cursor()sql = 'INSERT INTO `score`(`year`, `max`, `avg`) VALUES({year}, {max}, {avg})'.format(year=year, max=max, avg=avg)print(sql)cursor.execute(sql)conn.autocommit(True)# print(conn)def get_conn(self):""" 獲取mysql 的連接 """try:conn = MySQLdb.connect(db='user_grade',host='localhost',user='root',password='',charset='utf8')except:passreturn conndef export_xls(self):""" 從mysql數(shù)據(jù)庫導出數(shù)據(jù)到excel """# 獲取數(shù)據(jù)庫的連接conn = self.get_conn()cursor = conn.cursor()# 準備查詢語句 (如果數(shù)據(jù)量大,需要借助于分頁查詢)sql = 'SELECT `year`, `max`, `avg` FROM `score`'# 查詢數(shù)據(jù)cursor.execute(sql)rows = cursor.fetchall()# 循環(huán)寫入到excelwb = Workbook()ws = wb.activefor (i, row) in enumerate(rows):print(row)(ws['A{0}'.format(i+1)],ws['B{0}'.format(i+1)],ws['C{0}'.format(i+1)]) = row# 保存excelwb.save('./static/export.xlsx')if __name__ == '__main__':client = ExcelUtils()# client.do_sth()client.read_xls()# client.export_xls()py+mysql圖表實戰(zhàn)
import MySQLdb from openpyxl import load_workbook from openpyxl.chart import AreaChart, Referenceclass GaokaoExport(object):def __init__(self):self.wb = load_workbook('./static/tmpl.xlsx')self.ws = self.wb.activeself.ws.title = '成績統(tǒng)計'self.ws.sheet_properties.tabColor = 'ff0000'def get_conn(self):""" 獲取mysql 的連接 """try:conn = MySQLdb.connect(db='user_grade',host='localhost',user='root',password='',charset='utf8')except:passreturn conndef export_data(self):# 獲取數(shù)據(jù)庫的連接conn = self.get_conn()cursor = conn.cursor()# 準備查詢語句 (如果數(shù)據(jù)量大,需要借助于分頁查詢)sql = 'SELECT `year`, `max`, `avg` FROM `score`'# 查詢數(shù)據(jù)cursor.execute(sql)rows = cursor.fetchall()# 循環(huán)寫入到excelrow_id = 10for (i, row) in enumerate(rows):print(row)(self.ws['C{0}'.format(row_id)],self.ws['D{0}'.format(row_id)],self.ws['E{0}'.format(row_id)]) = rowrow_id += 1# 顯示圖表chart = AreaChart()chart.title = "統(tǒng)計表"chart.style = 13chart.x_axis.title = '年份'chart.y_axis.title = '分數(shù)'# 橫坐標cats = Reference(self.ws, min_col=3, min_row=10, max_row=row_id)# 數(shù)據(jù)區(qū)域data = Reference(self.ws, min_col=4, min_row=9, max_col=5, max_row=row_id)chart.add_data(data, titles_from_data=True)chart.set_categories(cats)self.ws.add_chart(chart, "A{0}".format(row_id+2))# 保存excelself.wb.save('./static/stats.xlsx')if __name__ == '__main__':client = GaokaoExport()client.export_data()總結(jié)
- 上一篇: JS_day03
- 下一篇: 【大数据】《红楼梦》作者分析(QDU)