3

網頁連結直接開啟 Word/Excel 檔

 3 years ago
source link: https://blog.darkthread.net/blog/launch-word-excel-from-web/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

網頁連結直接開啟 Word/Excel 檔

2021-02-19 08:45 PM 1 3,659

SharePoint 有項蠻酷功能,文件庫有個「在 Word/Excel 中編輯」連結,點下去可直接啟動 Word 或 Excel 開啟檔案:

反觀一般在網頁放 .docx、.xlsx 檔案 <a> 連結,都得儲存成本機檔案再開啟,流暢度輸了一截,讓我很不甘心,於是便研究了原理,發現我們也能辦到:

祕訣是將 href 網址改成「ms-word:ofv|u|可下載docx的網址」,例如:

  • ms-word:ofv|u|http://localhost/aspnet/officefiles/%E6%96%87%E4%BB%B6.docx
  • ms-excel:ofv|u|http://localhost/aspnet/officefiles/%E5%B7%A5%E4%BD%9C%E8%A1%A8.xlsx

這種格式的專業術語叫 Office URI Schemes,規則為:

< scheme-name >:< command-name >"|"< command-argument-descriptor > "|"< command-argument >

  1. scheme-name 指定要啟動的軟體,Excel 為 ms-excel,Word 為 ms-word。
  2. command-name 決定動作,ofv 為唯讀開啟或檢視模式,ofe 則為編輯模式。
  3. command-argument-descriptor 固定傳 "u"
  4. command-argument 下載檔案內容的 URL。

所以,只需在下載 docx/xlsx 的 URL 前面加上 ms-word:ofv|u| 或 ms-excel:ofv|u| 並換成絕對網址即可,完整範例如下:

<%@Page Language="C#"%>
<script runat="server">
string GetAbsUrl(string fileName) 
{
	return new Uri(Request.Url, fileName).AbsoluteUri;
}
</script>

<!DOCTYPE html>

<html>
<head>
	<meta charset="utf-8">
</head>
<body>
	<ul>
		<li><a href="ms-word:ofv|u|<%=GetAbsUrl("文件.docx")%>">文件.docx</a></li>
		<li><a href="ms-excel:ofv|u|<%=GetAbsUrl("工作表.xlsx")%>">工作表.xlsx</a></li>
	</ul>
</body>
</html>

最後補充一個眉角,如果 Office 檔案是靠 ASP.NET MVC 加上參數傳回,例如 /ControllerName/Download?f=fileName.docx,實測 URL 檔名結尾若不是 .docx、.xlsx 等副檔名,Word/Excel 開啟會出錯,故需使用 MVC 路由功能讓下載網址改為 .xlsx/.docx 結尾,但要注意檔名結尾 URL 導致 MVC 路由失效問題,web.config 要稍做調整。


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK