需求:市委组织部考核项目,既然是考核项目就会有很多考核标准要求等,而且各个下属单位对于被考核指标的结果需要上传。这些过程都是通过文档实现的。也就是需要word文档的上传,下载,预览等功能。
Word上传:
后台代码:
<span style="font-family:KaiTi_GB2312;font-size:24px;"> /// <summary>
/// word上传
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpWord_Click(object sender, EventArgs e)
{
string newName = "";
string flex = "";
string wjlj = "";
//事务开始——
using (TransactionScope tx = new TransactionScope())
{
try
{
if (Request.Files.Count > 0)
{
Random ro = new Random();
if (FileUpload2.FileName != "")
{
//文档全称
string filename = Path.GetFileName(FileUpload2.FileName).Trim ();
//无后缀名的文档名称
string filemainname = (Path.GetFileNameWithoutExtension(FileUpload2.FileName)).Trim ();
//文档后缀名
flex = (Path.GetExtension(FileUpload2.FileName)).Trim ();
if (flex == ".doc" || flex == ".docx")
{
//string stro = ro.Next(100, 1000000).ToString();
//string stro = DateTime.Now.ToString("yyyyMMdd");
//newName = DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + stro;
//上传后添加数据在数据库中
WordEntity enWord = new WordEntity();
//enWord.WordAddress= Server.MapPath("UpLoadWord/") + FileUpload2.FileName;
wjlj = "UpLoadWord/" + filemainname + newName + flex;
enWord.WordAddress = wjlj;
enWord.WordName = filename;
DateTime now = DateTime.Now;
enWord.StrDate = DateTime.Now.ToString("yyyy-MM-dd");
enWord.StrYear = now.Year.ToString();
//enWord.UnitName=Session["UserName"].ToString ();
enWord.UnitName = "hejingyuan";
WordBLL wordBll = new WordBLL();
//判断此单位是否已经上传过这个文档了,参数,文档名称和提交单位
bool isExist = wordBll.Exists(filename);
if (isExist == false)
{
bool flag = wordBll.Add(enWord);
if (flag == false)
{
MessageBox.Show(this, "word上传失败,请联系管理员!");
throw new Exception();
//return;
}
else
{ //保有存文件到目录下
//FileUpload2.PostedFile.SaveAs(Server.MapPath("UpLoadWord/") + newName + flex);
FileUpload2.PostedFile.SaveAs(Server.MapPath("UpLoadWord/") + newName + filename);
//wjlj = "UpLoadWord/" + filemainname + newName + flex;
Response.Write("<script>alert('保存成功');location.replace(location.href)</script>");
}
}
else
{
//MessageBox.Show(this, "word上传失败,此文档已经存在!");
//File.Delete(Server.MapPath("UpLoadWord/") + FileUpload2.FileName);
Response.Write("<script>alert('word上传失败,此文档已经存在!');location.replace(location.href)</script>");
//return;
}
}
else {
System.Web.HttpContext.Current.Response.Write("<script language='javascript'>alert('导入文件格式不对,导入文件必须为Word文件!');;window.location.href='" + System.Web.HttpContext.Current.Request.ServerVariables["HTTP_REFERER"] + "'</script>");
System.Web.HttpContext.Current.Response.End();
}
}
}
//string sql = string.Format("insert into zl(xh, wdmc, wdlj)values ('{0}','{1}','{2}')", Guid.NewGuid().ToString(), wdmc, wjlj);
//执行SQL语句,省略.....
tx.Complete();
}
catch (Exception)
{
File.Delete(Server.MapPath("UpLoadWord/") + FileUpload2.FileName);
Response.Write("<script>alert('保存错误,请联系管理员!');location.replace(location.href)</script>");
}
finally
{
//释放资源
tx.Dispose();
}
}
}
</span>
Word预览,下载,删除,查询。
年份:根据年份进行筛选信息。文件名:模糊查询
预览效果:
前台代码:
<span style="font-family:KaiTi_GB2312;font-size:24px;"><span>年 份: </span>
<asp:DropDownList ID="YearName" runat="server" editable="false" panelHeight="auto" class="easyui-combobox" required="true" Width="131px"></asp:DropDownList>
<label class="first txt-green">文件名: </label>
<asp:TextBox ID="txtWordName" runat="server"></asp:TextBox>
<%-- 何静媛 2014年2月18日 ,模糊查询 文本框输入进行限制,防止SQL注入 ErrorMessage="请输入模糊查询条件"--%>
<%--<asp:LinkButton ID="btnSearch" class="btn-lit btn-middle" runat="server" οnclick="queryYear()" ValidationGroup="fuzzyQueryExam" ><span>查询</span></asp:LinkButton>--%>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtWordName" ValidationGroup="fuzzyQueryExam" Display="Dynamic" ></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtWordName" ValidationGroup="fuzzyQueryExam"
ErrorMessage="请输入汉字,数字,字母或下划线_!"
ValidationExpression="^[a-zA-Z0-9_\u4e00-\u9fa5]+$" Display="Dynamic"></asp:RegularExpressionValidator>
<%-- 结束 何静媛 2014年2月18日 --%>
<a href="#" class="easyui-linkbutton" οnclick="queryYear();" data-options="">查询</a>
<div style="margin:10px 0;"></div>
<div id="toolbar" style="padding:5px;">
<a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-ok" οnclick="btnDownLoad()">下载word文档</a>
<%--<a href="javascript:void(0)" id="btnLoad" class="easyui-linkbutton" plain="true" οnclick="btnDownLoad()" οnclick="btnLoad_Click">下载</a>--%>
<asp:LinkButton ID="btnLoad" style="display:none" runat="server" οnclick="btnLoad_Click" >下载</asp:LinkButton>
<%--<asp:LinkButton ID="btnPreView" style="display:none" CssClass="easyui-linkbutton" runat="server" OnClick="btnConvert_Click">预览swf</asp:LinkButton>--%>
<asp:LinkButton ID="btnPreView" style="display:none" CssClass="easyui-linkbutton" runat="server" OnClick="WordtoHtml_Click">预览html</asp:LinkButton>
<a href="javascript:void(0)" class="easyui-linkbutton" οnclick="javascript:btnPreView()">预览HTML</a>
<asp:LinkButton ID="btnRemove" style="display:none" CssClass="easyui-linkbutton" runat="server" OnClick="DelectWord_Click">删除文档</asp:LinkButton>
<a href="javascript:void(0)" class="easyui-linkbutton" iconcls="icon-remove" plain="true" οnclick="destroyWord()">删除文档</a>
</div>
</span>
js代码:
<span style="font-family:KaiTi_GB2312;font-size:24px;"><script type="text/javascript">
//下载
function btnDownLoad() {
var row = $('#dg').datagrid('getSelected');
if (row) {
//选中行的id,文档名称,文档地址
var id = row.id;
var name = row.wordName;
var wordaddress = row.wordAddress;
//createXMLHTTP(); //创建XMLHttpRequest对象 + "&wordaddress=" + wordaddress
//var url = "QueryWord.aspx?name=" + name + "&wordaddress=" + wordaddress;
//js跳转页
//window.location.href = "QueryWord.aspx?name=" + name;
//调用后台click方法
//document.getElementById("btnLoad").click();
//var myurl = "QueryWord.aspx" + "?" + "name=" + name + "&wordaddress=" + wordaddress;
var myurl = wordaddress;
//当跳转为文档的地址时,即实现下载
window.location.assign(myurl);
}
else {
alert('请选中一条记录进行修改');
return;
}
}
//预览
function btnPreView() {
var row = $('#dg').datagrid('getSelected');
if (row) {
var wordaddress = row.wordAddress;
//将获取到的选中行地址赋给隐藏控件
document.getElementById("HiddenField1").value = wordaddress;
//js调用后台的click方法
document.getElementById("btnPreView").click();
}
else {
alert('请选中一条记录进行修改');
return;
}
}
//删除
function destroyWord() {
var row = $('#dg').datagrid('getSelected');
if (row) {
var id = row.id;
var wordName = row.wordName;
//将获取到的选中行地址赋给隐藏控件
document.getElementById("HiddenField2").value = id;
document.getElementById("HiddenField3").value = wordName;
//js调用后台的click方法
document.getElementById("btnRemove").click();
}
else {
alert('请选中一条记录进行修改');
return;
}
}
//重新加载页面
function reloadgrid() {
//查询参数直接添加在queryParams中
var queryParams = $('#dg').datagrid('options').queryParams;
getQueryParams(queryParams);
$('#dg').datagrid('options').queryParams = queryParams;//传递值
$("#dg").datagrid('reload');//重新加载table
}
//查询参数直接添加在queryParams中
function queryYear() {
var queryParams = $('#dg').datagrid('options').queryParams;
getQueryParams(queryParams);
$('#dg').datagrid('options').queryParams = queryParams; //传递参数值
$('#dg').datagrid('reload'); //重新加载表信息datagrid
}
//查询并把数据传递给后台,数组
function getQueryParams(queryParams) {
var Category = $("#YearName").datebox("getText");
var txtWordName = document.getElementById("txtWordName").value;
queryParams.WordID = Category;
queryParams.txtWordName = txtWordName;
return queryParams;
}
</script>
</span>
后台代码:
<span style="font-family:KaiTi_GB2312;font-size:24px;"> /// <summary>
/// 窗体加载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
DropYear();
}
/// <summary>
/// 加载数据库中的年份
/// </summary>
private void DropYear()
{
try
{
//是否需要多次调用
//加载管理端字典表中的数据
WordBLL wordBll = new WordBLL();
System.Data.DataTable dtYear = wordBll.QueryYear().Tables[0];
YearName.Items.Add("全部");
for (int i = 0; i < dtYear.Rows.Count; i++)
{
YearName.Items.Add(dtYear.Rows[i]["strYear"].ToString());
}
}
catch (Exception ex)
{
//MessageBox.Show(this.Page, ex.Message);
}
}
/// <summary>
/// 调用转换
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void WordtoHtml_Click(object sender, EventArgs e)
{
try
{ //word文档的地址
string strpath = HiddenField1.Value;
string HtmlPath = WordToHtml(Server.MapPath(strpath));
string rePath = HtmlPath.Substring(HtmlPath.IndexOf("UpLoadWord\\") + 11, HtmlPath.Length - HtmlPath.IndexOf("UpLoadWord\\") - 11);
Response.Redirect("UpLoadWord/" + rePath);
}
catch {
MessageBox.Show(this, "预览失败,请重新查看!");
return;
}
}
/// <summary>
/// word转成html[把word文档换成同名的html文件,并返回其路径]
/// </summary>
/// <param name="wordFileName"></param>
public string WordToHtml(object wordFileName)
{
//在此处放置用户代码以初始化页面
ApplicationClass word = new ApplicationClass();
Type wordType = word.GetType();
Documents docs = word.Documents;
//打开文件
Type docsType = docs.GetType();
Document doc = (Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { wordFileName, true, true });
//转换格式,另存为
Type docType = doc.GetType();
string wordSaveFileName = wordFileName.ToString();
string extendName = Path.GetExtension(wordSaveFileName);
string strSaveFileName = null;
if (extendName == ".docx")
{
strSaveFileName = wordSaveFileName.Substring(0, wordSaveFileName.Length - 4) + "html";
}
else if (extendName == ".doc")
{
strSaveFileName = wordSaveFileName.Substring(0, wordSaveFileName.Length - 3) + "html";
}
else
{
Response.Write("<script>alert('转换错误,请查看是否为doc或docx格式!');location.replace(location.href)</script>");
}
object saveFileName = (object)strSaveFileName;
docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, WdSaveFormat.wdFormatFilteredHTML });
docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod, null, doc, null);
//退出 Word
wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
return saveFileName.ToString();
}
//DelectWord_Click
/// <summary>
/// 删除上传的word文档
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void DelectWord_Click(object sender, EventArgs e)
{
using (TransactionScope tx = new TransactionScope())
{
try
{
//选中行的id值
string id = HiddenField2.Value;
//选中行的word文档名称
string strName = HiddenField3.Value;
//将删除数据库中的字段
WordBLL wordbll = new WordBLL();
//根据id删除数据库中的数据
bool flag = wordbll.Delete(id);
//删除服务器中的文档
File.Delete(Server.MapPath("UpLoadWord/") + strName);
//替换
string name = strName.Replace(".docx", ".html");
name = name.Replace(".doc", ".html");
//string filename = strName.Replace(".docx", ".files/");
//filename = filename.Replace(".doc", ".files/");
File.Delete(Server.MapPath("UpLoadWord/") + name);
//文件夹无法删除,每次生成的文件夹都是只读属性
//File.Delete(Server.MapPath("UpLoadWord/") + filename);
if (flag == true)
{
MessageBox.Show(this, "删除文档成功!");
tx.Complete();
}
else
{
//MessageBox.Show(this, "删除文档失败,请联系管理员!");
throw new Exception();
}
}
catch (Exception)
{
Response.Write("<script>alert('删除失败,请联系管理员!');location.replace(location.href)</script>");
return;
}
finally
{
//释放资源
tx.Dispose();
}
}
//string HtmlPath = WordToHtml(Server.MapPath(strpath));
//string rePath = HtmlPath.Substring(HtmlPath.IndexOf("UpLoadWord\\") + 11, HtmlPath.Length - HtmlPath.IndexOf("UpLoadWord\\") - 11);
//Response.Redirect("UpLoadWord/" + rePath);
}
</span>
总结:
以上只是对word上传,预览,下载,删除操作的代码罗列,整理出来方便以后查看,积累经验,其中的一些知识点会在后续的博客中继续总结!其中有一点需要大家注意就是存放在数据库中的文档地址字段“\”符号,因为“\”符号加一些字母通常会代表一些含义,固需要转义!
地址如下:
UpLoadWord\数据库系统原理实践报告.docx--无法查出数据
UpLoadWord\\数据库系统原理实践报告.docx--能执行查询