面,我們將使用模板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 電子表格中:
我們可以從為應用程序創建一個文件夾開始。在這種情況下,我們將其命名為“實時數據”。接下來,需要在該文件夾中創建一個 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 應用程序之前,我們必須首先創建一個 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();
});
在上面的代碼中,我們遍歷數據源并在工作表中填寫一些示例數據。同時,還調用了一些將被定義的函數:bindData、addLineData、addChart 和 setConditionalFormatting。
當數據被正確獲取之后,如何在SpreadJS中進行顯示,可以前往如何將實時數據顯示在前端電子表格中(二)中一探究竟。
了解更多信息,歡迎私信我們,或者發送產品關鍵詞“SpreadJS”。
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)
具體研究可以看一下代碼
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---
*請認真填寫需求信息,我們會在24小時內與您取得聯系。