纯前端实现xls表格下载

纯前端实现xls表格下载

1.createXlsStr:生成xls模板字符串函数

  • xls字符串,基本不需要变更,我们只需要通过变量控制结果即可
  • worksheet:xls的文件名(不是下载的文件名!)
  • contentStr: xls表格内部的数据(主要是tr和td元素拼接成的字符串)
function createXlsStr(worksheet,contenStr){
       return `
            <html 
                xmlns:o="urn:schemas-microsoft-com:office:office" 
                xmlns:x="urn:schemas-microsoft-com:office:excel" 
                xmlns="http://www.w3.org/TR/REC-html40"
            >
                <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
                    <x:Name>${worksheet}</x:Name>
                    <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
                    </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
                </head>
                <body>
                    <table>${contenStr}</table>
                </body>
            </html>
        `;
    }

2.tableToExcel:表格数据转换xls

  • window.btoa()将去空格的encodeURIComponent转换的str转为base64
  • createDataStr生成内容字符串
  • 利用浏览器特性,将基础类型+准换后的base64,触发跳转下载
  • 参数:jsonData-表格数据源,tableOptions-表格配置项
function tableToExcel(params){
    const {worksheet, jsonData, tableOptions} = params;
    const uri = 'data:application/vnd.ms-excel;base64,';
    const base64 = s => window.btoa(unescape(encodeURIComponent(s)));
    const contenStr = '<tr><td>测试</td></tr>'
    // const contenStr = createDataStr(jsonData, tableOptions)
    const template =createXlsStr(worksheet,contenStr)
    window.location.href = uri + base64(template);
}

3.createDataStr:封装配置化表单

  • jsonData:[{},{},{}],数据源,数组对象。
  • tableOptions:表格配置项,[{label:striing,key:string,render:(record:any)=>void}]
    • label:表头名称
    • key:数据绑定的字段名
    • render:如需要自定义或者自己计算属性,将会渲染return的结果
function createDataStr(jsonData, tableOptions){
    // 列标题
    let str = tableOptions.reduce((prev, next,index) => {
        prev+=`<td>${next.label}</td>${index === tableOptions.length-1 ? '</tr>':''}`
        return prev
    },'<tr>');
    // 循环遍历,每行加入tr标签,每个单元格加td标签
    for(let i = 0 ; i < jsonData.length ; i++ ){
        const item =jsonData[i]
        str+='<tr>';
        for (let s = 0; s < tableOptions.length; s++) {
            // 增加\t为了不让表格显示科学计数法或者其他格式
            str+=`<td>${ tableOptions[s].render ? tableOptions[s].render(item) : item[tableOptions[s].key] + '\t'}</td>`;    
        }
        str+='</tr>';
    }
    return str;
}

4.完整代码:不积跬步无以至千里

// 封装配置化表单
function createDataStr(jsonData, tableOptions){
    // 列标题
    let str = tableOptions.reduce((prev, next,index) => {
        prev+=`<td>${next.label}</td>${index === tableOptions.length-1 ? '</tr>':''}`
        return prev
    },'<tr>');
    // 循环遍历,每行加入tr标签,每个单元格加td标签
    for(let i = 0 ; i < jsonData.length ; i++ ){
        const item =jsonData[i]
        str+='<tr>';
        for (let s = 0; s < tableOptions.length; s++) {
            // 增加\t为了不让表格显示科学计数法或者其他格式
            str+=`<td>${ tableOptions[s].render ? tableOptions[s].render(item) : item[tableOptions[s].key] + '\t'}</td>`;    
        }
        str+='</tr>';
    }
    return str;
}
// 生成xls模板字符串函数
function createXlsStr(worksheet,contenStr){
       return `
            <html 
                xmlns:o="urn:schemas-microsoft-com:office:office" 
                xmlns:x="urn:schemas-microsoft-com:office:excel" 
                xmlns="http://www.w3.org/TR/REC-html40"
            >
                <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
                    <x:Name>${worksheet}</x:Name>
                    <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
                    </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
                </head>
                <body>
                    <table>${contenStr}</table>
                </body>
            </html>
        `;
    }
// 表格数据转换xls
function tableToExcel(params){
    const {worksheet, jsonData, tableOptions} = params;
    const uri = 'data:application/vnd.ms-excel;base64,';
    const base64 = s => window.btoa(unescape(encodeURIComponent(s)));
    const contenStrDefault = '<tr><td>测试</td></tr>'
    const contenStr = createDataStr(jsonData, tableOptions)
    const template =createXlsStr(worksheet,contenStr)
    window.location.href = uri + base64(template);
}

tableToExcel({
	worksheet:'测试表格',
	jsonData:[{name:'小明',age:18, time:'今天'},{name:'小红',age:18, time:'今天'}],
	tableOptions:[
		{label:'姓名',key:'name'},
		{label:'年龄',key:'age'},
		{label:'时间',key:'time',render:(record)=>Date().toLowerCase()},
	],
})
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
很抱歉,作为AI助手,我无法知晓你与我之间的约定和要求。但是,我可以为你提供一份Django导入表格、导入数据库,并在前端页面展示的代码示例,供参考: 首先,需要安装一些Python包: ```bash pip install django pip install openpyxl pip install pandas ``` 接下来,创建一个Django项目,然后在`urls.py`中添加以下路由: ```python # urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('upload/', views.upload, name='upload'), ] ``` 在`views.py`中添加以下代码: ```python # views.py import pandas as pd from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import ExcelForm from .models import ExampleModel def index(request): data = ExampleModel.objects.all() return render(request, 'index.html', {'data': data}) def upload(request): if request.method == 'POST': form = ExcelForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] # 读取Excel文件 xls = pd.ExcelFile(file) df = xls.parse('Sheet1') # 保存数据到数据库中 for index, row in df.iterrows(): data = ExampleModel() data.col1 = row['col1'] data.col2 = row['col2'] data.col3 = row['col3'] data.save() return HttpResponseRedirect('/') else: form = ExcelForm() return render(request, 'upload.html', {'form': form}) ``` 在`models.py`文件中创建一个模型: ```python # models.py from django.db import models class ExampleModel(models.Model): col1 = models.CharField(max_length=100) col2 = models.CharField(max_length=100) col3 = models.CharField(max_length=100) ``` 接下来,创建一个表单`forms.py`: ```python # forms.py from django import forms class ExcelForm(forms.Form): file = forms.FileField() ``` 最后,在`templates`目录中创建两个HTML文件,`index.html`和`upload.html`,分别用于显示数据和上传文件。 `index.html`代码: ```html <!-- index.html --> <!DOCTYPE html> <html> <head> <title>Example</title> </head> <body> <table> <thead> <tr> <th>Column 1</th> <th>Column 2</th> <th>Column 3</th> </tr> </thead> <tbody> {% for item in data %} <tr> <td>{{ item.col1 }}</td> <td>{{ item.col2 }}</td> <td>{{ item.col3 }}</td> </tr> {% endfor %} </tbody> </table> </body> </html> ``` `upload.html`代码: ```html <!-- upload.html --> <!DOCTYPE html> <html> <head> <title>Example</title> </head> <body> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> </body> </html> ``` 以上代码可以实现将Excel文件导入数据库,并在前端页面展示数据。但应根据实际情况进行修改和适配。希望能对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

家雀安知鸿鹄志

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值