前言
近日项目中做到一个功能,需要上传附件后能够在线预览。之前也没做过这类似的,于是乎就查找了相关资料,.net实现office文件预览大概有这几种方式:
使用microsoft的office组件将文件直接转换为html文件(优点:代码实现最简单,工作强度最小。缺点:效果极差)
使用microsoft的office组件将文件转换为pdf格式文件,然后再使用pdf2swf转换为swf文件,也就是flash文件在使用flexpaper展示出来(优点:预览效果能接受,缺点:代码量大)
使用office online(优点:表现完美,缺点:不适合中小企业应用)
由于开发时间短而且还有其他功能点需要完成,所以暂时先已第一种方式实现了,这里也主要讲第一种方式,效果如下图:
具体实现
这里简单提一下效果图中的遮罩效果和上传实现,有喜欢的朋友也可以参考参考。
遮罩效果就是html+css+js来实现的,全部代码如下:
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en"
"http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>弹出层</title>
<script src="jquery-1.6.2.min.js" type="text/javascript"></script>
<style>
.black_overlay{
display: none;
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: black;
z-index:1001;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
}
.white_content {
display: none;
position: absolute;
top: 10%;
left: 10%;
width: 80%;
height: 80%;
border: 16px solid lightblue;
background-color: white;
z-index:1002;
overflow: auto;
}
.white_content_small {
display: none;
position: absolute;
top: 20%;
left: 30%;
width: 40%;
height: 50%;
border: 16px solid lightblue;
background-color: white;
z-index:1002;
overflow: auto;
}
</style>
<script type="text/javascript">
//弹出隐藏层
function showdiv(show_div,bg_div){
document.getelementbyid(show_div).style.display='block';
document.getelementbyid(bg_div).style.display='block' ;
var bgdiv = document.getelementbyid(bg_div);
bgdiv.style.width = document.body.scrollwidth;
// bgdiv.style.height = $(document).height();
$("#"+bg_div).height($(document).height());
};
//关闭弹出层
function closediv(show_div,bg_div)
{
document.getelementbyid(show_div).style.display='none';
document.getelementbyid(bg_div).style.display='none';
};
</script>
</head>
<body>
<input id="button1" type="button" value="点击弹出层" onclick="showdiv('mydiv','fade')" />
<!--弹出层时背景层div-->
<div id="fade" class="black_overlay">
</div>
<div id="mydiv" class="white_content">
<div style="text-align: right; cursor: default; height: 40px;">
<span style="font-size: 16px;" onclick="closediv('mydiv','fade')">关闭</span>
</div>
目前来说,我还是喜欢这个自己改造的弹出层。自己在项目中也用的是这个。
</div>
</body>
</html>
上传的话,因为文件比较小,所以采用的是保存在服务器,在数据库中存放路径的方式
前台代码
<div class="white_content" id="mydiv" style="text-align: center; display: none;">
<div style="text-align: right; cursor: default; height: 40px;">
<span style="font-size: 16px;" onclick="closediv('mydiv','fade')">关闭</span>
</div>
<tr style="width: 50%" id="upload_image">
<h1>
请上传常见问题附件</h1>
<td align="right" class="title">
上传附件
</td>
<td>
<asp:fileupload id="fileupload1" runat="server" />
<asp:label id="label1" runat="server" forecolor="red"></asp:label>
<asp:button id="uploadbutton" runat="server" text="上传附件" onclick="uploadbutton_click" />
</td>
</tr>
<tr>
<td colspan="2" align="center" id="show_image" style="visibility: hidden">
<asp:image id="image1" runat="server" height="118px" width="131px" />
</td>
</tr>
</div>
后台方法
try
{
string fullname = fileupload1.postedfile.filename;//获取附件物理地址
fileinfo fi = new fileinfo(fullname);
string name = fi.name;//获取附件名称
string type = fi.extension;//获取附件类型
if (type == ".xls" || type == ".xlsx" || type == ".doc" || type == ".docx" || type == ".pdf")
{
string savepath = server.mappath("~\\uploadfile");//附件保存到文件夹下
if (!directory.exists(savepath))
{
directory.createdirectory(savepath);
}
this.fileupload1.postedfile.saveas(savepath + "\\" + name);//保存路径
#region 将附件内容保存到数据库中
int showsuccess = cmsmodelmanager.submitted_questionsdao.save_file(name,type,savepath);
if (showsuccess == 1)
{
this.label1.text = "上传成功";
}
else
{
this.label1.text = "服务器繁忙,请稍后重试";
}
#endregion
}
else
{
this.label1.text = "请选择正确的格式附件";
}
}
catch (exception ex)
{
response.write(ex.message);
}
图中所示的将word转换成html的实现方式:
首先新建一个帮助类
using system;
using system.collections.generic;
using system.web;
//using microsoft.office.core;
using word = microsoft.office.interop.word;
namespace com.vanruportal.admin
{
public class office2htmlhelper
{
/// <summary>
/// word转成html
/// </summary>
/// <param name="path">要转换的文档的路径</param>
/// <param name="savepath">转换成html的保存路径</param>
/// <param name="wordfilename">转换成html的文件名字</param>
public static void word2html(string path, string savepath, string wordfilename)
{
word.applicationclass word = new word.applicationclass();
type wordtype = word.gettype();
word.documents docs = word.documents;
type docstype = docs.gettype();
word.document doc = (word.document)docstype.invokemember("open",
system.reflection.bindingflags.invokemethod, null, docs, new object[] { (object)path, true, true });
type doctype = doc.gettype();
string strsavefilename = savepath + wordfilename + ".html";
object savefilename = (object)strsavefilename;
doctype.invokemember("saveas", system.reflection.bindingflags.invokemethod, null, doc, new object[] { savefilename,
word.wdsaveformat.wdformatfilteredhtml });
doctype.invokemember("close", system.reflection.bindingflags.invokemethod, null, doc, null);
wordtype.invokemember("quit", system.reflection.bindingflags.invokemethod, null, word, null);
}
/// <summary>
/// excel转成html
/// </summary>
/// <param name="path">要转换的文档的路径</param>
/// <param name="savepath">转换成html的保存路径</param>
/// <param name="wordfilename">转换成html的文件名字</param>
public static void excel2html(string path, string savepath, string wordfilename)
{
string str = string.empty;
microsoft.office.interop.excel.application repexcel = new microsoft.office.interop.excel.application();
microsoft.office.interop.excel.workbook workbook = null;
microsoft.office.interop.excel.worksheet worksheet = null;
workbook = repexcel.application.workbooks.open(path, type.missing, type.missing, type.missing, type.missing, type.missing,
type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing, type.missing);
worksheet = (microsoft.office.interop.excel.worksheet)workbook.worksheets[1];
object htmlfile = savepath + wordfilename + ".html";
object ofmt = microsoft.office.interop.excel.xlfileformat.xlhtml;
workbook.saveas(htmlfile, ofmt, type.missing, type.missing, type.missing, type.missing,
microsoft.office.interop.excel.xlsaveasaccessmode.xlnochange, type.missing, type.missing,
type.missing, type.missing, type.missing);
object osave = false;
workbook.close(osave, type.missing, type.missing);
repexcel.quit();
}
}
}
后台调用方法
上传成功后将文件转换
string physicalpath = server.mappath(server.urldecode("/uploadfile"+"\\"+ name));//读取相对路径
string extension = path.getextension(physicalpath);//获取后缀名
string[] show_name = name.split(new string[] { "." }, stringsplitoptions.removeemptyentries);
//此处的name是上面上传附件中的名称分割
string show_name_view = show_name[0];//拿到实际name
switch (extension)
{
case ".doc":
case ".docx":
office2htmlhelper.word2html(mappath("/uploadfile" + "\\" + name + ""),
mappath("/html/"), "" + show_name_view + "");
//调用帮助类中生成wordhtml的方法,并保存起来
response.write("<script>window.open('/html/" + show_name_view + ".html','_blank')</script>");
//跳转并打开保存的相对路径中hmtl文件
break;
case ".xls":
case ".xlsx":
office2htmlhelper.excel2html(mappath("/uploadfile" + "\\" + name + ""),
mappath("/html/"), "" + show_name_view + "");
response.write("<script>window.open('/html/" + show_name_view + ".html','_blank')</script>");
break;
default:
break;
}
至此,一个简易的上传附件在线浏览已经全部实现
以上就是.net编程中word/excel 在线预览的内容。