def excelview(request, event_id): """Выборка по кластеру в виде эксель-файла Args: event_id (int): Идентификатор темы """ try: theme = Theme.objects.get(pk=event_id) data = [] sentiment_map = ('Нейтрально', 'Позитивно', 'Негативно') for item in ThemeArticles.objects.filter(theme_link=theme): data.append({ 'Дата публикации': item.article_link.publish_date, 'Ссылка': item.article_link.url, 'Заголовок': item.article_link.title, 'Тип источника': item.article_link.site.type, 'Отношение к власти': sentiment_map[item.article_link.sentiment], 'Общая тональность': sentiment_map[item.article_link.happiness_sentiment], 'Лайки': item.article_link.likes, 'Просмотры': item.article_link.views, 'Комментарии': Comment.objects.filter(article=item.article_link).count(), }) return ExcelResponse(data, f'FreyrMonitoring: Выборка по теме {theme.name}') except Theme.DoesNotExist: return HttpResponseNotFound('Такая тема не найдена!')
def send_email(): today = datetime.date.today() if today.weekday() == 0: # This check was done to make the request report a daily report # if last_report is None or last_report.fecha_ejecucion < yesterday: consultas = Consulta.objects.all() today_str = today.strftime("%d/%m/%Y") message = EmailMessage( 'Resumen de consultas (%s)' % today_str, 'Las consultas realizadas hasta %s se adjuntan en el siguiente archivo' % today_str, settings.FROM_EMAIL, [settings.TO_EMAIL], connection=get_connection(), ) excel_file = ExcelResponse(process_queryset(consultas)) if consultas.count() > 0: message.attach( 'reporte-%s.xls' % today_str, excel_file.content, 'application/vnd.ms-excel' ) else: message.body = 'No existen nuevas consultas hasta %s' % today_str message.send() Reporte(cantidad_consultas=consultas.count()).save()
def get_recharge_card_export(request): """ 微众卡充值导出 """ card_recharge_list = get_recharge_datas(request) members_info = [[ u'卡号', u'余额', u'已使用金额', u'充值额度', u'卡属性', u'卡类型', u'专属商家', u'充值日期', u'备注' ]] for card_recharge in card_recharge_list: belong_to_owner = card_recharge['belong_to_owner'] if card_recharge[ 'belong_to_owner'] else '' info_list = [ card_recharge['card_number'], card_recharge['remainder'], card_recharge['used_money'], card_recharge['recharge_money'], card_recharge['card_attr'], card_recharge['card_type'], belong_to_owner, card_recharge['created_at'], card_recharge['remark'] ] members_info.append(info_list) filename = u'微众卡充值列表' #TODO 上线 加.encode('utf8') return ExcelResponse(members_info, output_name=filename.encode('utf8'), force_csv=False)
def get(request): is_export = True purchase_method = account_models.UserProfile.objects.get( user_id=request.user.id).purchase_method product_list = getProductRelationData(request, is_export) titles = [ u'编号', u'商品名称', u'一级分类', u'二级分类', u'供货商', u'当月销售数量', u'当月销售金额', u'累计销售数量', u'累计销售金额', u'客户来源', u'商品状态', u'停售原因' ] product_table = [] product_table.append(titles) for product in product_list: revoke_reasons = '' if product['product_status_value'] == 2: revoke_reasons = product['revoke_reasons'] info = [ '', product['product_name'], product['first_level_name'], product['second_level_name'], product['customer_name'], '-', '-', product['total_sales'], '-', product['customer_from_text'], product['product_status'], revoke_reasons ] product_table.append(info) filename = u'商品统计列表' return ExcelResponse(product_table, output_name=filename.encode('utf8'), force_csv=False)
def export_activity_members(request, activity_id): activity = Activity.objects.get(id=activity_id) title_list = [u'会员名称',u'凭证码', u'是否签到'] items = ActivityItem.objects.filter(activity=activity) titile_order = [] for item in items: title_list.append(item.title) titile_order.append(item.id) member_info = [ [activity.name]] member_info.append(title_list) member_id_list = ActivityItemValue.objects.filter(activity=activity, owner=request.user).values("webapp_user_id").distinct().order_by("webapp_user_id") for member_id_dict in member_id_list: webapp_user_id = member_id_dict['webapp_user_id'] member = WebAppUser.get_member_by_webapp_user_id(webapp_user_id) items_values = ActivityItemValue.objects.filter(activity=activity, webapp_user_id=webapp_user_id) if member: nike_name = member.username try: nike_name = nike_name.decode('utf8') except: nike_name = member.username_hexstr items_value_list = [nike_name] else: items_value_list = ['-'] if int(webapp_user_id) != -1: activity_codes = ActivityUserCode.objects.filter(activity=activity, webapp_user_id=webapp_user_id) if activity_codes.count() > 0: activity_code = activity_codes[0] items_value_list.append(activity_code.sign_code) if activity_code.sign_status == 0: items_value_list.append(u'未签到') else: items_value_list.append(u'已签到') else: items_value_list.append('-') items_value_list.append('-') else: items_value_list.append('-') items_value_list.append('-') items_value_dict = {} for items_value in items_values: p=titile_order.index(items_value.item.id) items_value_dict[p] = items_value.value for i in range(len(titile_order)): if items_value_dict.has_key(i): items_value_list.append(items_value_dict[i]) else: items_value_list.append('') member_info.append(items_value_list) return ExcelResponse(member_info,output_name=u'报名列表'.encode('utf8'),force_csv=False)
def results(request, id): if request.method == "POST": upload_files = UploadedFile.objects.filter(user_group__id=id) return ExcelResponse(upload_files) upload_files = UploadedFile.objects.filter(user_group__id=id) user_group_id = id context = {'upload_files': upload_files, 'user_group_id': user_group_id} return render(request, 'file/results.html', context)
def export_adjust_accounts(request): items,_ = create_adjust_accounts_infos(request) adjust_accounts_table = [[u'商家名', u'账号',u'运营类型',u'微众卡(元)', u'积分(元)', u'总金额']] total = 0.0 for row in items: adjust_accounts_table.append([row['display_name'], row['name'], row['account_type'], row['weizoom_card_money'],row['integral_money'], row['total_sum']]) total = float(row['total_sum']) adjust_accounts_table.append([u'合计', '%.2f' % total]) return ExcelResponse(adjust_accounts_table,output_name=u'核算列表'.encode('utf8'),force_csv=False)
def get(request): is_export = True purchase_method = account_models.UserProfile.objects.get(user_id=request.user.id).purchase_method product_list = getProductData(request,is_export) if purchase_method == 1: titles = [ u'id', u'编号', u'一级分类', u'二级分类', u'商品名称', u'促销标题', u'商品价格(元)', u'结算价(元)' , u'销量', u'创建时间', u'状态', u'商品重量(Kg)', u'商品主图', u'商品轮播图', u'商品描述' ] else: titles = [ u'id', u'编号', u'一级分类', u'二级分类', u'商品名称', u'促销标题', u'商品价格(元)', u'销量', u'创建时间', u'状态', u'商品重量(Kg)', u'商品主图', u'商品轮播图', u'商品描述' ] product_table = [] product_table.append(titles) for product in product_list: product_name = product['product_name'] if purchase_method == 1: info = [ product['id'], '', product['first_level_name'], product['second_level_name'], product['product_name'], product['promotion_title'], product['product_price'], product['clear_price'], product['sales'], product['created_at'], product['status'], product['product_weight'], product['image_path'], u','.join(product['image_paths']), product['remark'] ] else: info = [ product['id'], '', product['first_level_name'], product['second_level_name'], product['product_name'], product['promotion_title'], product['product_price'], product['sales'], product['created_at'], product['status'], product['product_weight'], product['image_path'], u','.join(product['image_paths']), product['remark'] ] product_table.append(info) filename = u'商品统计列表' return ExcelResponse(product_table,output_name=filename.encode('utf8'),force_csv=False)
def render_to_response(self, context, **response_kwargs): """ Returns a response with a template rendered with the given context. """ cols = [ (USAGE_TEXT, ), ] cols += self.get_filters_as_rows(context) cols += [ ('Institution', 'Country', 'Institution Type', 'STARS Version', 'Points Earned', 'Available Points', context['reporting_field'].title, 'Units'), ] for o in context['object_list']: row = [ "%s" % o['ss'].institution, "%s" % o['ss'].institution.country, "%s" % o['ss'].institution.institution_type, "%s" % o['ss'].creditset.version ] if o['assessed_points']: row.append(o['assessed_points']) else: row.append('') if o['point_value']: row.append(o['point_value']) else: row.append('') if o['field']: if o['field'].documentation_field.type == 'upload': if o['field'].value: if self.request.is_secure(): url = 'https://' else: url = 'http://' url += (self.request.get_host() + o['field'].value.url) row.append(url) else: row.append('') row.append('') elif o['field'].documentation_field.type == 'choice': row.append(str(o['field'].value)) else: row.append(o['field'].value) if o['field'].documentation_field.units: row.append(o['field'].documentation_field.units.name) else: row.append('') else: row.append('') row.append('') cols.append(row) return ExcelResponse(cols)
def export_coupon(request, coupon_pool_id): coupon_list = [[u'优惠券', u'过期时间', u'抵扣金额']] coupons = Coupon.objects.filter(coupon_pool=coupon_pool_id) for coupon in coupons: coupon_list.append( [coupon.coupon_id, coupon.expired_time, coupon.money]) return ExcelResponse(coupon_list, output_name=u'优惠券'.encode('utf8'), force_csv=False)
def get(request): """ 导出订单列表 """ params = _extract_params(request) orders = _get_stats_data(request.manager, params, True) data = _export_orders_json(request, orders, params) return ExcelResponse(data, output_name=u'订单列表'.encode('utf8'), force_csv=False)
def export_order_list(request): status = { '0': u'待支付', '1': u'已取消', '2': u'已支付', '3': u'待发货', '4': u'已发货', '5': u'已完成' } orders = [[u'下单时间', u'订单号', u'金额', u'订单状态', u'出货数', u'收货人']] order_list = None #购买数量 number = 0 order_send_count = 0 order_list = Order.objects.all().order_by('-created_at') #订单总量 order_count = order_list.count() #总金额 order_total = order_list.filter(status=5).aggregate( total=Sum('total_price')) total = 0 if order_total: if order_total['total']: total = order_total['total'] #已完成 order_finish_count = order_list.filter(status=5).count() for order in order_list: number_list = OrderHasProduct.objects.filter( order_id=order.id).aggregate(number=Sum('number')) if number_list['number']: number = number_list['number'] #出货 if order.status == 5: order_send_count += number orders.append([ order.created_at.strftime('%Y-%m-%d %H:%M'), order.order_id, order.total_price, status[str(order.status)], number, order.ship_name ]) orders.append([ u'总计', u'订单量:' + str(order_count), u'已完成:' + str(order_finish_count), u'出货:' + str(order_send_count), u'金额:' + str(total), u'' ]) return ExcelResponse(orders, output_name=u'订单列表'.encode('utf8'), force_csv=False)
def excelview(request): """Generates ExcelSheet and downloads the ExcelSheet""" user_smses = request.user.sms_set.all() user_record = [['From', 'To', 'Message', 'Status']] for sms in user_smses: user_record.append([ sms.user.username, '+' + str(sms.to.country_code) + ' ' + str(sms.to.national_number), sms.sms_text, sms.status ]) return ExcelResponse(user_record, 'My_Sms_Sheet')
def export_detail_adjust_accounts(request): items = create_detail_adjust_accounts_infos(request) username = request.GET.get('username', None) adjust_accounts_table = [[u'时间', u'卡号', u'操作', u'金额(元)']] total = 0.0 for row in items: action = u"【{}】 {}".format(row['event_type'], ('' if row['order_id'] == '-1' else row['order_id'])) adjust_accounts_table.append([row['created_at'], row['card_id'], action, row['money']]) total = total + float(row['money']) adjust_accounts_table.append([u'合计', '%.2f' % total]) return ExcelResponse(adjust_accounts_table,output_name=u'核算明细列表'.encode('utf8'),force_csv=False)
def render_to_response(self, context, **response_kwargs): """ Returns a response with a template rendered with the given context. """ rows = [ (USAGE_TEXT, ), ] rows += self.get_filters_as_rows(context) cols = ["Institution", 'Country', 'Institution Type', "STARS Version"] selected_columns = self.get_selected_columns() for column in selected_columns: if not isinstance(column[1], CreditSet): column_name = str(column[1]) else: column_name = "Overall Score" cols.append(column_name) cols.append("") # blank space rows.append(cols) subcols = ["", "", "", ""] for c in selected_columns: subcols.append("Points Earned") subcols.append("Available Points") rows.append(subcols) for o in context['object_list']: row = [ "%s" % o['ss'].institution, "%s" % o['ss'].institution.country, "%s" % o['ss'].institution.institution_type, "%s" % o['ss'].creditset.version ] for c in o['cols']: if c['claimed_points'] is not None: if isinstance(c['claimed_points'], float): row.append("%.2f" % c['claimed_points']) else: row.append(c['claimed_points']) else: row.append('') if c['available_points']: row.append("%.2f" % c['available_points']) else: row.append('') rows.append(row) return ExcelResponse(rows)
def download_report(requeste, pid=None): CURRENT_TIME = time.strftime('%d%m%Y_%H%m%S') # print(f'PID = {pid} \n {type(pid)}') if pid and pid== 9000000000: print('I am here') query_results = patch_report.objects.all().order_by('-id') elif pid: query_results = HostList.objects.filter(Pid=pid).order_by('id') else: query_results = HostList.objects.all() print(f'query_results = > {query_results}') return ExcelResponse(query_results, f'JcMate_report_{CURRENT_TIME}')
def objection_report_date_submitted(request): if request.method == "POST": fromdate = request.POST.get('fromdate') todate = request.POST.get('todate') if fromdate > todate: return render(request, 'objections/objection_report.html') else: reportresult = Objection.objects.filter( date_submitted__gte=fromdate, date_submitted__lte=todate).values( 'complaint_id', 'complaint_language__name', 'service_provider__name', 'agent__user__username', 'date_submitted', 'date_processing_start', 'due_date', 'status_note__name', 'psp_objection_referenced_code_section__name', 'ccts_determination_referenced_code_section__name', 'objection_status__name', 'ccts_assessment__name', 'closing_level__name', 'ccts_assistance_required__name', 'customer_assistance_required__name', 'date_processing_end' ).annotate( ComplaintID=F('complaint_id'), ComplaintLanguage=F('complaint_language__name'), ServiceProvider=F('service_provider__name'), Agent=F('agent__user__username'), DateSubmitted=F('date_submitted'), ProcessingStartDate=F('date_processing_start'), DueDate=F('due_date'), StatusNote=F('status_note__name'), PSPObjectionRefCodeSection=F( 'psp_objection_referenced_code_section__name'), CCTSDeterminationRefCodeSection=F( 'ccts_determination_referenced_code_section__name'), ObjectionStatus=F('objection_status__name'), CCTSAssessment=F('ccts_assessment__name'), ClosingLevel=F('closing_level__name'), CCTSAssistanceRequired=F('ccts_assistance_required__name'), CustomerAssistanceRequired=F( 'customer_assistance_required__name'), ProcessingEndDate=F('date_processing_end')).values( 'ComplaintID', 'ComplaintLanguage', 'ServiceProvider', 'Agent', 'DateSubmitted', 'ProcessingStartDate', 'DueDate', 'StatusNote', 'PSPObjectionRefCodeSection', 'CCTSDeterminationRefCodeSection', 'ObjectionStatus', 'CCTSAssessment', 'ClosingLevel', 'CCTSAssistanceRequired', 'CustomerAssistanceRequired', 'ProcessingEndDate') return ExcelResponse( data=reportresult, output_filename='objection_report_based_on_date_submitted' + str(datetime.datetime.now()), worksheet_name='objection-report') else: return render(request, 'objections/objection_report.html')
def export_as_xls(modeladmin, request, queryset): data = [( 'User', 'Amount', 'Location', 'Category', 'Organisation', 'Project', 'Time', )] for expense in queryset: data.append(expense.data_tuple()) return ExcelResponse(data)
def get(request): orders = CustomerOrdersList.api_get(request) titles = [ u'订单号', u'下单时间', u'商品名称', u'商品规格', u'商品单价', u'商品数量', u'销售额', u'商品总重量', u'订单状态', u'收货人', u'联系电话', u'收货地址', u'发货人', u'发货人备注', u'物流公司', u'快递单号', u'发货时间', u'用户备注' ] table = [] table.append(titles) for order in orders: product_infos = json.loads(order['product_infos']) for product_info in product_infos: if product_info['model_names']: product_models = product_info['model_names'] else: product_models = '' if order['leader_name'].find('|') == -1: leader_name = order['leader_name'] leader_name_message = '' else: leader_name, leader_name_message = order[ 'leader_name'].split('|') price = float(product_info['price']) sales_price = str('%.2f' % (price * int(product_info['count']))) # print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.' # print order['express_company_name'] # print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.' if order[ 'express_company_name'] not in haved_express_company_name: cur_express_company_name = order[ 'express_company_storename'] else: cur_express_company_name = express_company_name2text[ order['express_company_name']] table.append([ order['order_id'], order['order_create_at'], product_info['product_name'], product_models, str('%.2f' % price), str(product_info['count']) + u'件', sales_price, order['total_weight'], order['status'], order['ship_name'], order['ship_tel'], order['ship_area'] + ' ' + order['ship_address'], leader_name, leader_name_message, cur_express_company_name, order['express_number'], order['delivery_time'], order['customer_message'] ]) return ExcelResponse(table, output_name=u'订单列表'.encode('utf8'), force_csv=False)
def get(self, request, *args, **kwargs): filename = 'shop_managers_info' field_header_map = { 'FK_ShopManager__first_name': 'نام', 'FK_ShopManager__last_name': 'نام خانوادگی', 'FK_ShopManager__User_Profile__NationalCode': 'کد ملی', 'State': 'استان', 'BigCity': 'شهرستان', 'City': 'شهر', 'Location': 'نشانی', } queryset = Shop.objects.shop_managers_info() return ExcelResponse( data=queryset, output_filename=filename, )
def export_point_card_rule(request): rule_id = request.GET['rule_id'] card_list = [ [u'积分充值卡', u'卡号', u'密码', u'包含积分', u'使用状态', u'生成日期'] ] point_cards = PointCard.objects.filter(point_card_rule_id = rule_id) for point_card in point_cards: card_list.append([ point_card.point_card_rule.name, point_card.point_card_id, point_card.password, point_card.point, POINT_CARD_STATUS2POINT_CARD_STATUS_STR[point_card.status], point_card.created_at.strftime('%Y-%m-%d') ]) return ExcelResponse(card_list, output_name=u'积分卡'.encode('utf8'), force_csv=False)
def get(request): # 处理排序 name = request.GET.get('name', None) if not name: suppliers = Supplier.objects.filter(owner_id=request.manager.id).filter(is_delete=False).order_by('-id') else: suppliers = Supplier.objects.filter(owner_id=request.manager.id).filter(name__contains=name).filter(is_delete=False).order_by('-id') # 得到所有该用户的所有满足条件的供货商 cloumn_name = [u'供货商名称',u'客户负责人',u'供货商电话',u'供货商地址',u'备注'] supplier_data = [ cloumn_name ] for su in suppliers: supplier_data.append([su.name,su.responsible_person, su.supplier_tel,su.supplier_address,su.remark]) return ExcelResponse(supplier_data, output_name=u'供货商列表'.encode('utf8'), force_csv=False)
def get_lines_excel(request): excel_name = '线路信息' data = [['线路名称', '地点名称', '下次到达时间(min)', '允许时间误差(min)', '顺序']] try: for line in LinesModel.objects.all(): data.append( [line.name, line.position, line.next_time_arrival, line.order]) pass pass except Exception as e: print e print traceback.format_exc() return ExcelResponse(data, excel_name) pass
def get(request): orders = YunyingOrdersList.api_get(request) titles = [u'订单编号', u'物流公司', u'快递单号'] table = [] table.append(titles) for order in orders: if order['express_company_name'] not in haved_express_company_name: cur_express_company_name = order['express_company_storename'] else: cur_express_company_name = express_company_name2text[ order['express_company_name']] table.append([ order['order_id'], cur_express_company_name, order['express_number'] ]) return ExcelResponse(table, output_name=u'发货文件'.encode('utf8'), force_csv=False)
def post(self, request, *args, **kwargs): if request.user.has_perm(self.permission) and self.other_condition(request,*args,**kwargs): self.object = None form_order = self.get_form(request,False) if form_order.is_valid(): form_data = self.get_form_cleaned_data(form_order) self.get_ordering(form_data) self.object_list = self.get_queryset() form_filter = self.form_filter(request.POST,self.object_list) self.object_list = form_filter.qs context = self.get_context_data(object_list=self.object_list,form=form_order,form2=form_filter,**kwargs) if not form_filter.is_valid(): return render(request,self.template_name,context) else: context = self.get_context_data(form=form_order,form2=form_filter,**kwargs) return render(request,self.template_name,context) allow_empty = self.get_allow_empty() if not allow_empty: # When pagination is enabled and object_list is a queryset, # it's better to do a cheap query than to load the unpaginated # queryset in memory. if self.get_paginate_by(self.object_list) is not None and hasattr(self.object_list, 'exists'): is_empty = not self.object_list.exists() else: is_empty = not self.object_list if is_empty: raise Http404(_("Empty list and '%(class_name)s.allow_empty' is False.") % { 'class_name': self.__class__.__name__, }) if "export" in request.POST: return ExcelResponse( self.object_list, output_filename=f'{self.model.__name__}_data', worksheet_name=f'{self.model.__name__}', force_csv=False, header_font=None, data_font=None, guess_types=True ) return self.render_to_response(context) else: return render(request,self.permission_denied_template,{'error':'You dont have authorization for this action'})
def _do_export(request, object_model_class, object_name): query = request.GET.get('query', '') order_by = request.GET.get('order_by', '') objects = facet_view_utils.search_objects( request, filters=request.GET.getlist('filters'), query=query, object_model=object_model_class, facets=settings.FACET_FIELDS[object_name], order_by=order_by ) objects_ids = [obj.__dict__['pk'] for obj in objects] objects = object_model_class.objects.filter(id__in=objects_ids) values = [obj.serialize_to_export() for obj in objects] if len(values) == 0: raise ValueError("There are no values to export - your selection was empty") return ExcelResponse(values)
def export_vote_statistics(request, vote_id): vote = Vote.objects.get(id=vote_id) vote_options = VoteOption.objects.filter(vote=vote) votes = [ [vote.name], [u'名称', u'票数'], ] for vote_option in vote_options: votes.append([ vote_option.name, vote_option.vote_count, ]) return ExcelResponse( votes, output_name=u'投票列表'.encode('utf-8'), force_csv=False )
def get(request): is_export = True customer_list = getCustomerData(request, is_export) titles = [ u'客户名称', u'开始推广时间', u'总销量', u'订单数', u'总金额', u'现金', u'微众卡', u'优惠券' ] order_table = [] order_table.append(titles) for customer in customer_list: info = [ customer['customer_name'], customer['brand_time'], customer['total_sales'], customer['total_order_number'], customer['total_order_money'], customer['total_final_price'], customer['total_weizoom_card_money'], customer['total_coupon_money'] ] order_table.append(info) filename = u'客户统计列表' return ExcelResponse(order_table, output_name=filename.encode('utf8'), force_csv=False)
def get(request): """ 导出福利卡券码库 """ items, _ = get_codes(request, False) codes = [ [u'卡券码', u'创建时间', u'起始时间', u'结束时间', u'卡券状态', u'领用时间', u'领取人id', u'领取人昵称', u'订单号'] ] for item in items: codes.append([ item['code'], item['created_at'], item['start_time'], item['end_time'], item['status'], item['get_time'], item['member_id'], item['member_name'], item['order_id'] ]) return ExcelResponse(codes, output_name=u'福利卡券码库详情'.encode('utf8'), force_csv=False)
def get(self, request, format=None): print "came", request.GET if 'mode' in request.GET: regData = EventRegistration.objects.filter( event=request.GET['event']) if request.GET['mode'] == 'all': print 'alllllll' regData_json = serializers.serialize('json', regData) return HttpResponse(regData_json) elif request.GET['mode'] == 'download': print 'downloaddddddddddd' da = [] for i in regData: da.append({ 'name': i.name, 'email': i.email, 'phoneNumber': i.phoneNumber }) print da return ExcelResponse(da) else: return Response(status=status.HTTP_400_BAD_REQUEST)