class ExportView(APIView):
authentication_classes = [JSONWebTokenAuthentication,]
permission_classes = [IsAdminUser,]
def get(self,request,*args,**kwargs):
conn = pymysql.connect(
host='127.0.0.1',
user = '××××××××××',
password = '××××××××××',
database='××××××××××',
charset='utf8',
)
cursor = conn.cursor()
query = 'select * from nineth_article'
cursor.execute(query)
results = cursor.fetchall()
fields = cursor.description
workbook = xlwt.Workbook(encoding='UTF-8')
sheet = workbook.add_sheet('nine_article')
# for item in fields:
# print(item[0])
# print(results[0][1].strftime('%Y-%m-%d %H:%M:%S'))
#从fields中取出所有字段名,这里直接存成了excel表格的第0行(存成exel表格后是第一行),如果需要改变,可作调整
for index,value in enumerate(fields):
sheet.write(0,index,value[0])
#从表格的第1行开始,一行一行写入数据
for row_number in range(1,cursor.rowcount+1):
for col_number in range(len(fields)):
#将datatime对象转成时间字符串的形式存入
if col_number in (1,2):
strftime = results[row_number - 1][col_number].strftime('%Y/%m/%d %H:%M:%S')
sheet.write(row_number, col_number, strftime)
elif col_number == 10:
strftime = results[row_number - 1][col_number].strftime('%Y/%m/%d')
sheet.write(row_number, col_number, strftime)
else:
sheet.write(row_number,col_number,results[row_number-1][col_number])
#拼接文件保存的路径,这里需要注意文件后缀是xls,而不是xlsl(否则乱码打不开文件,原因不太清楚)
filename = '/'.join([settings.MEDIA_ROOT,'export','article.xls'])
workbook.save(filename)
cursor.close()
conn.close()
return APIResponse(msg='ok')