功能要求:导出数据到制定好的excel的模板文件中 刚开始做项目,一边摸索一边做,搜了很多资料,踩了很多坑,记录一下 在模型的admin.py文件中定义函数和要导出的字段 中间注释的代码是没有测试成功的,请跳过
exportable_fields = ['sale_person', 'place_order_date', 'department', 'shipment_date', 'card_id', 'user_code',
'process_specification', 'product_name', 'product_model_number', 'quantity', 'out_stock_name',
'out_stock_model_number',
'power_supply', 'output_signal', 'measuring_medium', 'medium_temperature_min',
'medium_temperature_max', 'compensation_temperature', 'display_mode', 'electrical_interface',
'line_length', 'process_interface', 'measuring_range', 'accuracy', 'wiring_method',
'print_content',
'special_instructions', 'audit',
'sensor', 'shell_drawing_number', 'transmitting_board', 'cable', 'lighting_protection_board',
'receiving_materials'
]
def export_model_as_excel(modeladmin, request, queryset):
response = HttpResponse(content_type='application/msexcel')
field_list = exportable_fields
response['Content-Disposition'] = 'attachment; filename={}.xlsx'.format(datetime.datetime.now())
import openpyxl
import os
from process_card_management.settings import BASE_DIR
str_base = str(BASE_DIR)
path = str_base + '/mytools/J2009002.xlsx'
print(path)
wb = openpyxl.load_workbook(path)
ws = wb['Sheet2']
data = []
for obj in queryset:
for field in field_list:
data = [f'{getattr(obj, field)}' for field in field_list]
ws.append(data)
break
wb.save(response)
return response
最后在模型管理类cardAdmin中添加
actions = [export_model_as_excel]
|