整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

Django开发网站-4-利用templates模板

Django开发网站-4-利用templates模板显示数据

面,我们将使用模板tempalte来显示上篇文章中的excel数据。

首先在user下建立templates文件夹,在文件夹下建立一个html文件。


在show.html文件中写入如下内容。这是一个html文件的基本框架。

<!DOCTYPE html>
<html>
    <head>
        <title>显示excel数据</title>
    
    </head>
    <body>
        这里展示数据
        
    </body>


</html>

下面修改views.py文件,在浏览器中展示出show.html.将文件中的return 按下面的方式修改。

    return render(request,"show.html")

运行应用。浏览器中输入http://127.0.0.1:8000/show_excel

将模板文件show.html成功显示在浏览内。


接下来,将df数据闯入show.html中,views.py的代码如下:

return render(request,"show.html",{'df':df})

view.py中的show.excel方法的代码修改完如下:

其中{'df':df}就是向模板传递参数,前面'df'表示前端文件中的变量参数,后边的df就是方法中读取excel文件得到的数据变量,使用:将df赋值给前端的df参数。

def show_excel(request):
    df=pd.read_excel(BASE_DIR/'data/1.xlsx')  #读取excel文件中的数据
    return render(request,"show.html",{'df':df})

df数据传入前端模板后,需要修改前端模板show文件显示出数据,代码如下。

利用<table></table>来显示数据。利用for语句,循环读取df中的数据。

<!DOCTYPE html>
<html>

<head>
    <title>显示excel数据</title>
</head>
<body>
    <table>
        <tr>
            <th>学号</th>
            <th>姓名</th>
            <th>语文</th>
            <th>数学</th>
            <th>英语</th>
        </tr>
        {% for idx,row in df.iterrows %}
        <tr>
            <td>{{ row.学号 }}</td>
            <td>{{ row.姓名 }}</td>
            <td>{{ row.语文 }}</td>
            <td>{{ row.数学 }}</td>
            <td>{{ row.英语 }}</td>
        </tr>
        {% endfor %}
    </table>
</body>
</html>

重新运行程序。打开浏览器,输入http://127.0.0.1:8000/show_excel


正确显示了excel文件中的参数。

数据(包括股票、天气和体育比分)在不断更新为新信息时最为有用。SpreadJS是一个非常通用的 JavaScript 电子表格组件,它还可以轻松地使用、显示并通过数据绑定提供实时数据更新。

我们将使用WebSocket从Finnhub.IO获取实时数据,然后使用基本的 SpreadJS 功能来展示数据。要使用 Finnhub Stock API,您需要创建一个免费帐户并生成您的 API 密钥,我们稍后将在该应用程序中使用该密钥。

在本教程中,我们将使用 Node.JS Express 和 WebSocket,因此请确保安装最新版本。我们还将使用 Visual Studio Code,因此以管理员身份运行它,以便 NPM 命令可以在终端中运行。

在此文中,我们将介绍如何按照以下步骤将实时数据合并到 JavaScript 电子表格中:

  1. 设置应用程序
  2. 连接到数据源
  3. 使用 SpreadJS 中的数据
  4. 为折线图添加数据
  5. 添加折线图
  6. 运行程序

应用设置

我们可以从为应用程序创建一个文件夹开始。在这种情况下,我们将其命名为“实时数据”。接下来,需要在该文件夹中创建一个 package.json 文件,用作项目的清单文件。这可能包含类似于以下的内容:

{
    "name": "real-time-data",
    "version": "0.0.2",
    "description": "An app that imports real-time data into Spread JS",
    "dependencies": {}
}

对于这个应用程序,我们将使用 Express 作为 Web 框架和 WebSockets 来获取实时数据,我们可以简单地使用 npm 安装它,也将使用它来安装 SpreadJS 文件。在 Visual Studio Code 终端中,您可以键入:

npm install --save express@4.18.2 finnhub websocket @grapecity/spread-sheets @grapecity/spread-sheets-charts

一旦安装成功,就可以创建一个名为“index.js”的文件来设置应用程序,其中会包含以下内容:

var express=require('express');
var app=express();
var http=require('http').Server(app);
app.use('/node_modules', express.static('node_modules'));
// Add code here
http.listen(3000, function(){
    console.log('Stock Ticker Started, connect to localhost:3000');
});

现在就可以添加应用程序到 HTML 文件中。在这种情况下,我们可以将文件命名为“index.html”。然后继续向HTML 文件添加一些代码,包括对 SpreadJS 脚本和 CSS 引用以及一些基本的初始化代码:

<!doctype html>
<html>
  <head>
    <title>Real Time Data</title>
  </head>
  <script type="text/javascript" src="stockTemplate.js"></script>
  <link href="/node_modules/@grapecity/spread-sheets/styles/gc.spread.sheets.excel2013white.css" rel="stylesheet" type="text/css" />
  <script src="/node_modules/@grapecity/spread-sheets/dist/gc.spread.sheets.all.min.js"></script>
  <script src="/node_modules/@grapecity/spread-sheets-charts/dist/gc.spread.sheets.charts.min.js" ></script>
  <script>
    window.onload=function() {
      // Initialize spread variables
      var spread=new GC.Spread.Sheets.Workbook(document.getElementById("spreadSheet"), { sheetCount: 1 });
      spread.fromJSON(stockTemplate);
      spread.options.scrollbarMaxAlign=true;
      spread.options.showHorizontalScrollbar=false;
      spread.options.showVerticalScrollbar=false;
      spread.options.grayAreaBackColor='rgb(38,38,38)';
      var activeSheet=spread.getActiveSheet();
      var dataSheet=spread.getSheet(1);
      activeSheet.clearSelection();
    }
  </script>
  <body>
    <div id="spreadSheet" style="width: 680px; height: 590px; border: 1px solid gray"></div>
  </body>
</html>

在前面的代码片段中,我们使用了 spread.fromJSON() 来加载模板文件。在下面的例子中,我们以股票数据显示为背景建立相应的模板文件。通过使用 SpreadJS Designer,我们可以为数据源创建数据标签和绑定、格式化单元格、删除网格线和标题,并为图表添加一个区域。同时,提供名为“stockTemplate.js”的模板文件

想要从设计器中导出到 JS,可以单击“文件”>“导出”并选择“导出 JavaScript 文件”。在本教程中,我们将该模板文件(stockTemplate.js)与 index.js 和 index.html 文件放在同一文件夹中。

回到 index.js 文件,我们需要使用以下代码告诉程序来提供 HTML 文件和模板:

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});
// Required to load template file
app.get('/stockTemplate.js', function(req, res){
    res.sendFile(__dirname + '/stockTemplate.js');
});

同时,在 index.html 文件中,可以通过添加脚本来加载该模板文件:

<script type="text/javascript" src="stockTemplate.js"></script>

要完成设置,还需要初始化稍后会用到的变量,并创建一个下拉单元格来选择股票数据:

// Initialize variables
var stockSymbolLookup=[{text:'Apple Inc.', value:'AAPL'}, {text:'Microsoft Inc.', value:'MSFT'}, {text:'Google', value:'GOOGL'}];
var dataSource=[],
    lastPrice=0,
    timeStamp=0,
    volume=0,
    stockCounter=0,
    chart=null,
    chartAxisRange=0.5,
    lineDataMaxSize=10,
    lineData=new Array(lineDataMaxSize),
    initialData=true,
    socket,
    stock;
// Create a drop down for selecting a stock
var stockDropDown=new GC.Spread.Sheets.CellTypes.ComboBox().items(stockSymbolLookup);
activeSheet.getCell(2,1).cellType(stockDropDown);

我们还可以为开盘价的变化设置特定的条件格式。

绿色=正
红色=负

创建 SpreadJS Blazor 组件

在将 SpreadJS 放入 Blazor 应用程序之前,我们必须首先创建一个 Blazor 组件来包含 SpreadJS。在本教程中,我们将使用 Visual Studio 2022 和 SpreadJS V16.0。

想要创建组件,首先要创建一个 Razor 类库:

为简单起见,您可以将其命名为“SpreadJS_Blazor_Lib”:

创建项目后,我们需要将 SpreadJS 文件复制到“wwwroot”文件夹。

连接到数据源

在实际编写代码连接到数据源之前,我们需要添加一些代码来处理用户从 Spread 的下拉列表中选择股票的情况。只有这样我们才能连接并获取数据。为此,我们可以绑定到 EditEnded 事件,通过数组查找股票代码,然后连接到该股票数据:

// Bind an event for changing the stock in the drop down menu
// Set the stock variable to the newly selected stock from the list
activeSheet.bind(GC.Spread.Sheets.Events.EditEnded, function(e, info) {
    if(info.row===2 && info.col===1) {
      stock=stockSymbolLookup.find(stockLookup=> stockLookup.text===activeSheet.getValue(2,1));
      connectToDataSource();
    }
  });

这将调用一个我们创建的名为“connectToDataSource”的新函数:

// Handle connecting to the data source to get new stock information when the selected stock is changed
function connectToDataSource() {
    // Create a new WebSocket connected to the FinnHub Stock API with a personal token
    socket=new WebSocket('wss://ws.finnhub.io?token=<YOUR TOKEN HERE>');
    if (socket.readyState !==WebSocket.CLOSED)
      console.log("CONNECTED.");
    else
      console.log("NOT CONNECTED.");
     
    // When the socket first opens, set the length of the data source to zero, remove the line chart if
    // it exists, and send a message back to the server with the selected stock
    socket.addEventListener('open', function (event) {
      dataSource.length=0;
      if (activeSheet.charts.get('line') !=null)
        activeSheet.charts.remove('line');
      socket.send(JSON.stringify({'type':'subscribe', 'symbol':stock.value}));
    });
  }

此代码使用 WebSocket 连接到数据源,并传入要订阅的股票代码。

注意:初始化 WebSocket 时,您需要添加从 Finnhub.IO 生成的令牌。

此外,为保证数据在重置的过程中能够得到正确的结果,我们需要增加

activeSheet.charts.remove('line');,

每次更改股票选择时都会调用此函数。

当程序连接到数据源并订阅特定股票值时,程序将从该数据源接收 JSON 数据形式的更新,我们需要解析这些数据并在 Spread 中进行使用。为此,我们可以使用事件侦听器来侦听来自 WebSocket 的消息

// Listen for a message from the server
socket.addEventListener('message', function (event) {
    spread.suspendPaint();
    // Get the data from the server message
    var dataArray=JSON.parse(event.data)
    console.log(dataArray);
    if (dataArray.data && dataArray.data.length !=0) {
      // Set the data source and extract values from it
      var dataSource=dataArray.data[dataArray.data.length-1];
      lastPrice=dataSource.p;
      timeStamp=dataSource.t;
      volume=dataSource.v;
      // Fill in starting data for the line chart
      if (initialData) {
        lineData.fill({Value:lastPrice});
        setConditionalFormatting();
        initialData=false;
      }
      // Set the specific values in the spreadsheet
      activeSheet.setValue(4, 1, stock.value);
      activeSheet.setValue(5, 1, lastPrice);
      activeSheet.setValue(2, 7, lastPrice);
      activeSheet.setValue(4, 7, new Date(timeStamp));
      activeSheet.setValue(6, 7, volume);
      // Add the line chart if one doesn't exist
      if (activeSheet.charts.all().length==0) {
        addChart();
      }
      addLineData(lastPrice);
      bindData();
    }
   
    spread.resumePaint();
  });

在上面的代码中,我们遍历数据源并在工作表中填写一些示例数据。同时,还调用了一些将被定义的函数:bindDataaddLineDataaddChartsetConditionalFormatting

当数据被正确获取之后,如何在SpreadJS中进行显示,可以前往如何将实时数据显示在前端电子表格中(二)中一探究竟。

了解更多信息,欢迎私信我们,或者发送产品关键词“SpreadJS”。

o.1

Excel表格是可以作为网页来进行展示的,也就是说当你完成一个表格,想要通过Web网页来进行发布,那么就需要看这篇文章了。

目前网络技术发展十分快,办公方式也逐渐向网络办公进行迁移,这是大趋势。

那么,当我们编辑好一个工作表之后,如何在网页上正确显示,就需要以Web代码形式来进行处理,这是Excel之外的另一种编码方式,但是Excel也给出了解决方法。

如下图所示,编辑好一个表格,通过一些代码就可以实现网页显示。

下图为发布成Web页的效果,也就是Htm后缀的文件。

Htm文件有什么用呢?

它是Web页通用格式,当然不是唯一的格式,也就是说,Htm格式可以用任何浏览器打开,而xls或xlsx只能用Excel或WPS等编辑软件打开,通用性不同,Htm格式只能读不能编辑。

下面进入正题,了解一下通过VBA如何实现Web网页发布。

如下图所示,首先要认识PublishObject对象,图中有对象的方法和属性详细内容。

PublishObject对象看不到,它是不是存在,可以通过代码来查看。

WorkBook.PublishObjects.Count '返回工作薄中的PublishObject对象数

WorkBook.PublishObjects.item(1).FileName'返回第一个PublishObject对象文件地址和文件名

PublishObjects是一个集合,包含了所有PublishObject对象。

发布只用一个方法:

PublishObject.Publish(true)

具体研究可以看一下代码

No.2

Sub NewPublishObject(xPath As String) '导出Html文件
On Error Resume Next
Dim wx As Workbook, pobj As Object
Set wx=ActiveWorkbook
Set pobj=wx.PublishObjects.Add(xlSourceRange, xPath, wx.ActiveSheet.Name _
, wx.ActiveSheet.UsedRange.Address, xlHtmlStatic, "", wx.ActiveSheet.Name)
    With pobj
        .Publish (True)
        .AutoRepublish=False
         '   MsgBox .DivID
    End With
Set pobj=Nothing
End Sub

上述代码首先添加一个PublishObject对象,然后再进行方法和属性设置。

添加PublishObject使用PublishObjects.Add()方法

具体参数如下图所示:

如果要进行网页展示表格,相信这个还是十分有用的。

欢迎关注、收藏

---END---