You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

104 lines
2.8 KiB
Python

# -*- coding:utf8 -*-
import io
import pandas as pd
import tornado.gen as gen
import xlwt
class Excel(object):
@gen.coroutine
def generate_excel(self, head, rows):
"""
head is a dict, eg: [(0, u"编号"), (1, u"地址")]
rows is detail list, eg: [[0, "XXX"], ...]
"""
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet("sheet1")
row_num = 0
# col_num = 0
for item in head:
worksheet.write(row_num, head.index(item), item[1])
for row in rows:
row_num += 1
col_num = 0
for col in row:
worksheet.write(row_num, col_num, col)
col_num += 1
sio = io.BytesIO()
workbook.save(sio)
raise gen.Return(sio)
@gen.coroutine
# def generate_excel_pd(self, index, data, columns):
def generate_excel_pd(self, pd_data):
"""
pandas 构建图表
"""
sio = io.StringIO()
writer = pd.ExcelWriter(sio, engine='xlsxwriter')
for data in pd_data:
df = pd.DataFrame(data=data["data"], index=data["index"], columns=data["columns"])
sheet_name = data["sheet_name"]
df.to_excel(writer, sheet_name=sheet_name)
workbook = writer.book
worksheet = writer.sheets[sheet_name]
chart = workbook.add_chart({'type': 'line'})
max_row = len(df) + 1
for i in range(len(data['columns'])):
col = i + 1
chart.add_series({
# 'name': ['Sheet1', 0, col],
'name': [sheet_name, 0, col],
'categories': [sheet_name, 1, 0, max_row, 0],
'values': [sheet_name, 1, col, max_row, col],
'line': {'width': 1.00},
})
chart.set_x_axis({'name': 'Date', 'date_axis': True})
chart.set_y_axis({'name': 'Statistics', 'major_gridlines': {'visible': False}})
chart.set_legend({'position': 'top'})
worksheet.insert_chart('H2', chart)
# df = pd.DataFrame(data=data, index=index, columns=columns)
"""
# ================ anothor method =================
# workbook.save(sio)
io = StringIO.StringIO()
# Use a temp filename to keep pandas happy.
writer = pd.ExcelWriter('temp.xls', engine='xlsxwriter')
# Set the filename/file handle in the xlsxwriter.workbook object.
writer.book.filename = io
#
# Write the data frame to the StringIO object.
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
xlsx_data = io.getvalue()
# ================ anothor method =================
"""
# sheet_name = 'Sheet1'
writer.save()
raise gen.Return(sio)