一、上传Word文档或者其他文档

1、简单地上传文件的web服务方法如下

[WebMethod]
public void UploadFile()
{
using (TransactionScope ts = new TransactionScope())
{
var postedFiles = Request.GetHttpFiles();
var guid = postedFiles[].Save(HttpContext.Current, Database); //其他操作可以在此处添加
Response.Write("<html><body>{ success: true, guid: '" + guid.GetFilePath(Database) + "' }</body></html>");
var info = string.Format("{0}上传文件,GUID:{1}", User.Name, guid);
BusinessLog.Write(User, Request.UserHostAddress, info, Database);
ts.Complete();
} }

2、调用函数的类:以上web服务用到的FileUpLoad和GUID相关的代码包含在HttpPostedFileExtension.cs文件中

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using Ipms.Server.Business;
using Ipms.Server.Business.Common; namespace Ipms.Server.UI.MISExtension
{
/// <summary>
/// 上传文档的相关扩展
/// </summary>
public static class HttpPostedFileExtension
{
/// <summary>
/// 上传文档保存路径
/// </summary>
public const string POSTED_FILE_ROOT_DIRECTORY = @"/IpmsDocument\";
/// <summary>
/// 保存上传文件
/// </summary>
/// <param name="postedFile"></param>
/// <param name="context"></param>
/// <param name="database"></param>
/// <returns></returns>
public static Guid Save(this HttpPostedFile postedFile, HttpContext context, IDatabase database)
{
string directory = context.Server.MapPath(POSTED_FILE_ROOT_DIRECTORY); if (!Directory.Exists(directory))
Directory.CreateDirectory(directory); string fileName = Path.GetFileName(postedFile.FileName);
string fileType = fileName.Substring(fileName.LastIndexOf(".") + ); Resource resource = new Resource();
resource.ResourceName = fileName;
resource.Type = fileType;
resource.Save(database); string newFileName = resource.Guid + "." + fileType;
string filePath = directory + newFileName; if (File.Exists(filePath))
File.Delete(filePath); postedFile.SaveAs(filePath); return resource.Guid;
}
/// <summary>
/// 取得文件路径
/// </summary>
/// <param name="guid"></param>
/// <param name="database"></param>
public static string GetFilePath(this Guid guid, IDatabase database)
{
var server = HttpContext.Current.Server;
Resource resource = database.Resources.GetByGuid(guid);
if (resource == null)
throw new ArgumentNullException("guid"); string fileName = POSTED_FILE_ROOT_DIRECTORY + "/" + guid + "." + resource.Type;
return fileName;
}
}
}

二、导出word文档

1、导出word文档的代码如下,下面的代码包含了来自两个模板的word文档的下载和导出,其原理为读取相应的word模板,找到标签或者表格,将数据库内的字段填入:

       [WebMethod]
public void s()
{
try
{
var direc = HttpContext.Current.Server.MapPath(HttpPostedFileExtension.POSTED_FILE_ROOT_DIRECTORY);
//@"D:\member\wanghuanjun\Ipms\Solution\0.3\Ipms.WebSite\IpmsDocument\
var templateName = direc + "大型精密仪器设备论证一览表_模板.doc";
Microsoft.Office.Interop.Word.ApplicationClass wordApp;
Microsoft.Office.Interop.Word.Document wordDocument = new Microsoft.Office.Interop.Word.Document();
object Obj_FileName = templateName;
object Visible = false;
object ReadOnly = false;
object missing = System.Reflection.Missing.Value;
wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
Object Nothing = System.Reflection.Missing.Value;
wordDocument = wordApp.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref Visible,
ref missing, ref missing, ref missing,
ref missing);
wordDocument.Activate(); Microsoft.Office.Interop.Word.Table wordTable = wordDocument.Tables[]; var Iid = Request.GetInt("tastItemID"); var memI = Database.ConstructTaskItems.SingleOrDefault(cti => cti.ID == Iid);
wordDocument.Bookmarks.get_Item("Unit").Range.Text = memI.ConstructPlanItem.MemberApplyItem.MemberApply.Project.College.Name;
wordDocument.Bookmarks.get_Item("DeviceManager").Range.Text = memI.ConstructPlanItem.MemberApplyItem.MemberApply.Member.Name;
wordDocument.Bookmarks.get_Item("Manager").Range.Text = memI.ConstructPlanItem.MemberApplyItem.MemberApply.Project.Manager.Name;
wordDocument.Bookmarks.get_Item("DeviceNumber").Range.Text = memI.ConstructPlanItem.DeviceNumber; wordTable.Cell(, ).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName;
wordTable.Cell(, ).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.EnglishName;
wordTable.Cell(, ).Range.Text = memI.ConstructPlanItem.MemberApplyItem.Quantity.ToString();
wordTable.Cell(, ).Range.Text = (memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.UnitPrice / ).ToString() + "元";
wordTable.Cell(, ).Range.Text = ((memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.UnitPrice * memI.ConstructPlanItem.MemberApplyItem.Quantity) / ).ToString() + "元"; wordTable.Cell(, ).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.NecessityAnalysis;
wordTable.Cell(, ).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.MainSpec;
wordTable.Cell(, ).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.AccessorySpec; wordTable.Cell(, ).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Environment;
wordTable.Cell(, ).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Consumables;
wordTable.Cell(, ).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Power; var deviceMaths = Database.DeviceMatchs.Where(dm => dm.ApplyDevice == memI.ConstructPlanItem.MemberApplyItem.ApplyDevice);
var temp = ;
//设备选型
if (deviceMaths.Count() > && deviceMaths.Count() <= )
foreach (var item in deviceMaths)
{
if (item != null)
{
wordTable.Cell(, + temp).Range.Text = item.MarketDevice.MarketDeviceName;
wordTable.Cell(, + temp).Range.Text = item.MarketDevice.Model; var deviceSupplier = Database.DeviceSuppliers.Where(ds => ds.DeviceMatch == item).FirstOrDefault();
if (deviceSupplier != null)
{
wordTable.Cell(, + temp).Range.Text = deviceSupplier.Supplier.Name;
wordTable.Cell(, + temp).Range.Text = deviceSupplier.ContactPerson + ":" + deviceSupplier.ContactPhone;
wordTable.Cell(, + temp).Range.Text = (deviceSupplier.Price / ).ToString() + "元";
wordTable.Cell(, + temp).Range.Text = deviceSupplier.PriceSource == ? "供应商" : "网络";
}
}
temp += ;
}
var extrals = Database.DeviceExtramurals.Where(de => de.ApplyDevice == memI.ConstructPlanItem.MemberApplyItem.ApplyDevice).ToList();
if (extrals.Count() > && extrals.Count() <= )
{
if (extrals.Count() >= )
{
wordTable.Cell(, ).Range.Text = extrals[].Brand.ToString();
wordTable.Cell(, ).Range.Text = extrals[].WorkUnit.ToString();
wordTable.Cell(, ).Range.Text = extrals[].UserName;
wordTable.Cell(, ).Range.Text = extrals[].BuyTime.Value.ToShortDateString();
wordTable.Cell(, ).Range.Text = (extrals[].UnitPrice/).ToString()+"元";
for (int i = ; i < extrals.Count(); i++)
{
wordTable.Cell( + i, ).Range.Text = extrals[i].Brand.ToString();
wordTable.Cell( + i, ).Range.Text = extrals[i].WorkUnit.ToString();
wordTable.Cell( + i, ).Range.Text = extrals[i].UserName;
wordTable.Cell( + i, ).Range.Text = extrals[i].BuyTime.Value.ToShortDateString();
wordTable.Cell( + i, ).Range.Text = (extrals[i].UnitPrice/).ToString()+"元";
}
}
} SaveDocument(wordDocument, wordApp, direc + "大型精密仪器设备论证一览表.doc"); downLoad(direc + "大型精密仪器设备论证一览表.doc", "大型精密仪器设备论证一览表.doc"); var downLoadInfo = string.Format("国资处:{0},下载设备:{1} 的大型设备论证报告",User.Name,memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName);
BusinessLog.Write(User, Request.UserHostAddress, downLoadInfo, Database);
}catch(System.Exception ex){
new PackedException("导出大型精密仪器论证一览表", ex).Hanldle();
} }
[WebMethod]
public void downTable()
{
try
{
var direc = HttpContext.Current.Server.MapPath(HttpPostedFileExtension.POSTED_FILE_ROOT_DIRECTORY);
//@"D:\member\wanghuanjun\Ipms\Solution\0.3\Ipms.WebSite\IpmsDocument\
var templateName = direc + "附件1-985大型设备购置论证报告_模板.doc";
Microsoft.Office.Interop.Word.ApplicationClass wordApp;
Microsoft.Office.Interop.Word.Document wordDocument = new Microsoft.Office.Interop.Word.Document();
object Obj_FileName = templateName;
object Visible = false;
object ReadOnly = false;
object missing = System.Reflection.Missing.Value;
wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
Object Nothing = System.Reflection.Missing.Value;
wordDocument = wordApp.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref Visible,
ref missing, ref missing, ref missing,
ref missing);
wordDocument.Activate(); Microsoft.Office.Interop.Word.Table wordTable = wordDocument.Tables[]; var Iid = Request.GetInt("tastItemID"); var memI = Database.ConstructTaskItems.SingleOrDefault(cti => cti.ID == Iid); wordDocument.Bookmarks.get_Item("DeviceName").Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName;
wordDocument.Bookmarks.get_Item("Unit").Range.Text = memI.ConstructPlanItem.MemberApplyItem.MemberApply.Project.College.Name;
wordDocument.Bookmarks.get_Item("DeviceManager").Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Member.Name;
wordDocument.Bookmarks.get_Item("Phone").Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Member.GetExpert(Database).MobilePhone;
wordDocument.Bookmarks.get_Item("Year").Range.Text = DateTime.Now.Year.ToString();
wordDocument.Bookmarks.get_Item("month").Range.Text = DateTime.Now.Month.ToString();
wordDocument.Bookmarks.get_Item("day").Range.Text = DateTime.Now.Day.ToString();
wordDocument.Bookmarks.get_Item("year2").Range.Text = DateTime.Now.Year.ToString();
wordDocument.Bookmarks.get_Item("month2").Range.Text = DateTime.Now.Month.ToString();
//wordDocument.Bookmarks.get_Item("Manager").Range.Text = memI.ConstructPlanItem.MemberApplyItem.MemberApply.Project.Manager.Name;
//wordDocument.Bookmarks.get_Item("DeviceNumber").Range.Text = memI.ConstructPlanItem.DeviceNumber; wordTable.Cell(, ).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName;
wordTable.Cell(, ).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.EnglishName;
wordTable.Cell(, ).Range.Text = memI.ConstructPlanItem.MemberApplyItem.Quantity.ToString();
wordTable.Cell(, ).Range.Text = (memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.UnitPrice / ).ToString() + "元";
wordTable.Cell(, ).Range.Text = ((memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.UnitPrice * memI.ConstructPlanItem.MemberApplyItem.Quantity) / ).ToString() + "元"; wordDocument.Bookmarks.get_Item("NecessityAnalysis").Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.NecessityAnalysis;
wordTable.Cell(, ).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.MainSpec; SaveDocument(wordDocument, wordApp, direc + "大型设备购置论证报告.doc"); downLoad(direc + "大型设备购置论证报告.doc", "大型设备购置论证报告.doc"); var downLoadInfo = string.Format("{0}下载设备:{1},购置论证报告", User.Name, memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName);
BusinessLog.Write(User, Request.UserHostAddress, downLoadInfo, Database);
}
catch (System.Exception ex)
{
new PackedException("大型设备购置论证报告", ex).Hanldle();
}
} private void downLoad(string filePath, string downloadName)
{
bool isIE = Convert.ToBoolean(Request["isIE"]);
if (isIE)
downloadName = HttpUtility.UrlEncode(downloadName, System.Text.Encoding.UTF8); FileInfo fileInfo = new FileInfo(filePath);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "attachment;filename=" + downloadName);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.AddHeader("Connection", "Keep-Alive"); Response.ContentType = "application/octet-stream";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312"); Response.WriteFile(fileInfo.FullName);
Response.Flush();
Response.End();
} private void SaveDocument(Microsoft.Office.Interop.Word.Document wordDocument, Microsoft.Office.Interop.Word.ApplicationClass wordApp, string filePath)
{
object Visible = false;
object missing = System.Reflection.Missing.Value;
Object Nothing = System.Reflection.Missing.Value;
object Save_FileName = filePath;
//保存模板文件
wordDocument.SaveAs(ref Save_FileName, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref Visible,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing);
//关闭wordDoc文档对象
wordDocument.Close(ref Nothing, ref Nothing, ref Nothing);
wordDocument = null;
//关闭wordApp组件对象
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
}

2、以上使用标签机制来完成的word文档的下载和内容的导出,因此需要有一个word模板,之后这个模板内应设置相应的标签或者表格内容

在设置word标签和表格内容的时候,首先使用word2010打开模板,之后选择“开发工具”选项卡,如果这个选项卡选择之后,内部的小控件是不可编辑的,则需要进行相应的设置,然后添加标签或者查看表格的属性就可以完成模板的设置。

.NET环境下上传和下载Word文件的更多相关文章

  1. php 上传文件实例 上传并下载word文件

    上传界面 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3 ...

  2. 11、只允许在主目录下上传和下载文件,不允许用putty登录

    创建用户xiao,   使其只允许在用户主目录 (/var/www/html)下上传和下载文件,不允许用putty登录 (为了安全起见,不给过多的权限) 1.创建xiao用户 [root@localh ...

  3. XShell上传、下载本地文件到linux服务器

    Python之道发表于程序员八阿哥订阅 1.2K 腾讯云服务器 年付3折起 首次购买云服务器 最低3折起 超高性价比 限时抢购 Xshell很好用,然后有时候想在windows和linux上传或下载某 ...

  4. SpringMVC下文件的上传与下载以及文件列表的显示

    1.配置好SpringMVC环境-----SpringMVC的HelloWorld快速入门! 导入jar包:commons-fileupload-1.3.1.jar和commons-io-2.4.ja ...

  5. WP8_(windows phone环境下)上传文件从C#到php接口

    在windows phone环境下,将手机上的图片上传到服务端(php环境): 注意事项:在上传的地方,头文件中name,例如name= img,则在php服务端处理时 ,需要约定好 存取一致 php ...

  6. IIS环境下上传文件失败

    跟随学习代码练习 php 上传文件,一开始是点击按钮后没有反应,不知道是否成功,使用 var_dump($_FILES) 查看,发现空空如也.遂百度一下,发现基本代码应如下 <form acti ...

  7. linux学习 XShell上传、下载本地文件到linux服务器

    (一)通过命令行的方式 1.linux服务器端设置 在linux主机上,安装上传下载工具包rz及sz; 如果不知道你要安装包的具体名称,可以使用yum provides */name 进行查找系统自带 ...

  8. 使用fastDFS上传和下载图片文件

    package com.xuecheng.test.fastdfs;import org.csource.common.MyException;import org.csource.fastdfs.* ...

  9. WAMP环境下访问PHP提示下载PHP文件

    原因是服务器没有加载到PHP文件 到http.conf下加载 AddType application/x-httpd-php .php AddType application/x-httpd-php ...

随机推荐

  1. Masonry控制台打印约束冲突问题解决

    不知道你是不是视图的布局也是用的第三方Masonry,在使用中是不是也遇到了控制台约束冲突的警告打印,看下图: 从输出的信息可以知道,有的控件的约束明显重复了设置,所以指出了是哪个控件,重复设置了哪些 ...

  2. <转> Lua使用心得(2)

    在lua脚本调用中,如果我们碰到一种不好的脚本,例如: do do end 那我们的程序主线程也会被阻塞住.那我们如何防止这种问题呢?下面就给出一个解决的办法. 首先为了不阻塞主线程,那我们就要开一个 ...

  3. Chrome & Linux font

    1 $ sudo apt-get install texlive-full # 较大 2 $ mkdir -p ~/.fonts 3 下载这个win7字体包解压后放到~/.fonts下 4 $ sud ...

  4. NPOI简单应用

    打开或创建文件 fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); 不同版本的workbook if ...

  5. L440 无线网卡:由于该设备有问题,Windows 已将其停止(代码 43)

    最近重装了系统,本来用的好好的,结果重启之后突然无线网卡不能用了,设备管理器老是黄色叹号!无线网卡设备状态:由于该设备有问题,Windows 已将其停止. (代码 43).      无线网卡型号:2 ...

  6. Handler使用总结(转)

    方法一:(java习惯,在android平台开发时这样是不行的,因为它违背了单线程模型) 刚刚开始接触android线程编程的时候,习惯好像java一样,试图用下面的代码解决问题 new Thread ...

  7. JavaWeb技术(二):DAO设计模式

    1. DAO全称:Data Access Object , 数据访问对象.使用DAO设计模式来封装数据持久化层的所有操作(CRUD),使得数据访问逻辑和业务逻辑分离,实现解耦的目的. 2. 典型的DA ...

  8. Android开发工具全面转向Android Studio(3)——AS project/module的目录结构(与Eclipse对比)

    如果AS完全还没摸懂的,建议先看下Android开发工具全面转向Android Studio(2)——AS project/module的CRUD. 注:以下以Windows平台为标准,AS以目前最新 ...

  9. 刨一刨内核container_of()的设计精髓

    新年第一帖,总得拿出点干货才行,虽然这篇水分还是有点大,大家可以晒干了温水冲服.这段时间一直在整理内核学习的基础知识点,期间又碰到了container_of()这个宏,当然还包括一个叫做offseto ...

  10. CSS 部件

    1.导航菜单: [荐]抽屉式菜单 jQuery.mmenu jQuery.mmenu 实现了类似手机上经常使用的抽屉式菜单,效果很好.http://mmenu.frebsite.nl/ 2.jQuer ...