Django模板中的文件的table导出Excel问题

hdztroop 2024-02-20 18:25:54

在Django中有一个html模板,主要用表格显示一些实习数据,,想把这个表格导出到excel文件中,已经添加了xlsx.full.min.js文件,显示也无问题,但是在导出excel文件时,没有相应,模板代码如下,请各位帮忙指点!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h2>年度实践环节经费预算统计表</h2>
    <hr>
    <table align="center" border="1" id="TableToExport">
        <tr>
            <th>环节名称</th>
            <th>周数</th>
            <th>学分</th>
            <th>专业</th>
            <th>班级</th>
            <th>人数</th>
            <th>实习地点</th>
            <th>实习形式</th>
            <th>标准</th>
            <th>经费预算</th>
            <th>指导教师人数</th>
            <th>备注</th>
        </tr>
        {% for budget in budgets %}
            <tr>
                <td>[{{ budget.classID }}]{{ budget.name }}</td>
                <td>{{ budget.weeks }}</td>
                <td>{{ budget.mark }}</td>
                <td>{{ budget.get_major_display }}</td>
                <td>{{ budget.banji }}</td>
                <td>{{ budget.number }}</td>
                <td>{{ budget.get_location_display }}</td>
                <td>{{ budget.get_practiceType_display }}</td>
                <td>{{ budget.budgetStandard }}</td>
                <td>{{ budget.total_budget }}</td>
                <td>{{ budget.teachers }}</td>
                <td>{{ budget.get_semester_display }}</td>
            </tr>
        {% endfor %}
    </table>
    <button id="sheetjsexport"><b>Export as XLSX</b></button>
    <script src="xlsx.full.min.js"></script>
    <script>
        document.getElementById("sheetjsexport").addEventListener('click', function() {
          /* Create worksheet from HTML DOM TABLE */
          let wb = XLSX.utils.table_to_book(document.getElementById("TableToExport"));
          /* Export to file (start a download) */
          XLSX.writeFile(wb, "SheetJSTable.xlsx");
        });
    </script>
</body>
</html>

百度盘

...全文
1732 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复

我下载了您的代码,找到问题原因是xlsx.full.min.js没有引入成功。您可以按照下列步骤改:
1.在根目录下新建static文件夹,将xlsx.full.min.js放入其中。

img

2.修改settings.py
增加

import os
STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

整个文件:

"""
Django settings for DptManage project.

Generated by 'django-admin startproject' using Django 5.0.

For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""
import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-n#xeg5(@x++(0ymbbffqg4*7nfn@ssx$&)#ggufrz*5#us1%(b'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'PracticeBudget',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'DptManage.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates']
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'DptManage.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/

STATIC_URL = '/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'



3.修改practice_budget.html
增加

{% load static %}
<script src="{% static 'xlsx.full.min.js' %}"></script>

整个文件:

{% load static %}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
    <h2>年度实践环节经费预算统计表</h2>
    <hr>
    <table align="center" border="1" id="TableToExport">
        <tr>
            <th>环节名称</th>
            <th>周数</th>
            <th>学分</th>
            <th>专业</th>
            <th>班级</th>
            <th>人数</th>
            <th>实习地点</th>
            <th>实习形式</th>
            <th>标准</th>
            <th>经费预算</th>
            <th>指导教师人数</th>
            <th>备注</th>
        </tr>
        {% for budget in budgets %}
        <tr>
            <td>[{{ budget.classID }}]{{ budget.name }}</td>
            <td>{{ budget.weeks }}</td>
            <td>{{ budget.mark }}</td>
            <td>{{ budget.get_major_display }}</td>
            <td>{{ budget.banji }}</td>
            <td>{{ budget.number }}</td>
            <td>{{ budget.get_location_display }}</td>
            <td>{{ budget.get_practiceType_display }}</td>
            <td>{{ budget.budgetStandard }}</td>
            <td>{{ budget.total_budget }}</td>
            <td>{{ budget.teachers }}</td>
            <td>{{ budget.get_semester_display }}</td>
        </tr>
        {% endfor %}
    </table>
    <button id="sheetjsexport"><b>Export as XLSX</b></button>
    <script src="{% static 'xlsx.full.min.js' %}"></script>
    <script>
        document.getElementById("sheetjsexport").addEventListener('click', function() {
            /* Create worksheet from HTML DOM TABLE */
            let wb = XLSX.utils.table_to_book(document.getElementById("TableToExport"));
            /* Export to file (start a download) */
            XLSX.writeFile(wb, "SheetJSTable.xlsx");
        });
    </script>
</body>

</html>


5.导出的Excel

img

hdztroop 02-20
  • 举报
回复
@太空漫步11 多谢您的回复,很详细,我也从其他人那里得到了解决问题的方法,的确是xlsx.full.min.js没有加载成功,我会尝试一下您的方法,多谢您的帮助。

39,084

社区成员

发帖
与我相关
我的任务
社区描述
HTML5是构建Web内容的一种语言描述方式。HTML5是互联网的下一代标准,是构建以及呈现互联网内容的一种语言方式.被认为是互联网的核心技术之一。
社区管理员
  • HTML5社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧