|
Author |
Alex Zhang |
|
Category |
SpreadJS |
|
Tags |
SpreadJS,前端電子表格,實時資料,RealTime Data |
前言
資料(包括股票、天氣和體育比分)在不斷更新為新資訊時最為有用,SpreadJS是一個非常通用的 JavaScript 電子表格組件,它還可以輕松地使用、顯示并通過資料系結提供實時資料更新,
我們將使用WebSocket從Finnhub.IO獲取實時資料,然后使用基本的 SpreadJS 功能來展示資料,要使用 Finnhub Stock API,您需要創建一個免費帳戶并生成您的 API 密鑰,我們稍后將在該應用程式中使用該密鑰,
在本教程中,我們將使用 Node.JS Express 和 WebSocket,因此請確保安裝最新版本,我們還將使用 Visual Studio Code,因此以管理員身份運行它,以便 NPM 命令可以在終端中運行,

在此文中,我們將介紹如何按照以下步驟將實時資料合并到 JavaScript 電子表格中:
- 設定應用程式
- 連接到資料源
- 使用 SpreadJS 中的資料
- 為折線圖添加資料
- 添加折線圖
- 運行程式
應用設定
我們可以從為應用程式創建一個檔案夾開始,在這種情況下,我們將其命名為“實時資料”,接下來,需要在該檔案夾中創建一個 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 [email protected] 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="https://www.cnblogs.com/powertoolsteam/p/stockTemplate.js"></script>
<link href="https://www.cnblogs.com/node_modules/@grapecity/spread-sheets/styles/gc.spread.sheets.excel2013white.css" rel="stylesheet" type="text/css" />
<script src="https://www.cnblogs.com/node_modules/@grapecity/spread-sheets/dist/gc.spread.sheets.all.min.js"></script>
<script src="https://www.cnblogs.com/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="https://www.cnblogs.com/powertoolsteam/p/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 = https://www.cnblogs.com/powertoolsteam/p/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 = https://www.cnblogs.com/powertoolsteam/p/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();
});
在上面的代碼中,我們遍歷資料源并在作業表中填寫一些示例資料,同時,還呼叫了一些將被定義的函式:bindData、addLineData、addChart 和 setConditionalFormatting,
當資料被正確獲取之后,如何在SpreadJS中進行顯示,可以前往如何將實時資料顯示在前端電子表格中(二)中一探究竟,
歡迎訪問SpreadJS產品官網:https://www.grapecity.com.cn/developer/spreadjs
本文是由葡萄城技術開發團隊發布,轉載請注明出處:葡萄城官網
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/552905.html
標籤:Java
下一篇:返回列表
