如何在 django 导入导出时添加页眉/页脚?
How to add header / footer on export on django import-export?
我在管理中使用 django-import-export 插件,我想在导出数据时添加一个 header/footer(images)。
有没有办法在覆盖 export
或 before_export
时获取 excel 或 pdf 对象的句柄?
django-import-export modules' core functionalities depend on the other package named tablib. You can't achieve what you are intended to do merely by overriding few methods which belong to django-import-export package since the export().format_name
property
属于tablib包。
解决方法(困难的)
- 创建新格式或编辑现有格式。参考 Adding New Formats (tablib doc)
- 编辑源代码后,构建自己的
tablib
python包
- 通过连接 自定义
tablib
包
构建您自己的 django-import-export
- 在你的 django 项目中连接 自定义
django-import-export
包
您可以通过在自定义管理 class 中覆盖 get_export_data()
来执行此操作。超级 class get_export_data()
将 return xlsx 数据。这可以加载到 Openpyxl 工作簿中,然后进行修改。这仅适用于 'xlsx' 个文件。
(示例取自 django-import-export 示例应用)
from io import BytesIO
from django.core.files.temp import NamedTemporaryFile
from openpyxl import load_workbook
class BookAdmin(ImportExportMixin, admin.ModelAdmin):
list_display = ('name', 'author', 'added')
list_filter = ['categories', 'author']
resource_class = BookResource
def get_export_data(self, file_format, queryset, *args, **kwargs):
"""
Returns file_format representation for given queryset.
"""
export_data = super().get_export_data(file_format, queryset, *args, **kwargs)
wb = load_workbook(BytesIO(export_data))
ws = wb.active
ws.insert_rows(1)
ws["A1"] = "NEW ROW"
with NamedTemporaryFile() as f:
wb.save(f.name)
data = BytesIO(f.read())
return data
我在管理中使用 django-import-export 插件,我想在导出数据时添加一个 header/footer(images)。
有没有办法在覆盖 export
或 before_export
时获取 excel 或 pdf 对象的句柄?
django-import-export modules' core functionalities depend on the other package named tablib. You can't achieve what you are intended to do merely by overriding few methods which belong to django-import-export package since the export().format_name
property
属于tablib包。
解决方法(困难的)
- 创建新格式或编辑现有格式。参考 Adding New Formats (tablib doc)
- 编辑源代码后,构建自己的
tablib
python包 - 通过连接 自定义
tablib
包 构建您自己的 - 在你的 django 项目中连接 自定义
django-import-export
包
django-import-export
您可以通过在自定义管理 class 中覆盖 get_export_data()
来执行此操作。超级 class get_export_data()
将 return xlsx 数据。这可以加载到 Openpyxl 工作簿中,然后进行修改。这仅适用于 'xlsx' 个文件。
(示例取自 django-import-export 示例应用)
from io import BytesIO
from django.core.files.temp import NamedTemporaryFile
from openpyxl import load_workbook
class BookAdmin(ImportExportMixin, admin.ModelAdmin):
list_display = ('name', 'author', 'added')
list_filter = ['categories', 'author']
resource_class = BookResource
def get_export_data(self, file_format, queryset, *args, **kwargs):
"""
Returns file_format representation for given queryset.
"""
export_data = super().get_export_data(file_format, queryset, *args, **kwargs)
wb = load_workbook(BytesIO(export_data))
ws = wb.active
ws.insert_rows(1)
ws["A1"] = "NEW ROW"
with NamedTemporaryFile() as f:
wb.save(f.name)
data = BytesIO(f.read())
return data