一、上传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. 'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

    创建120像素的高分辨率和60个像素定期如上,苹果文档中提到,并设置名称的新图标.例如,icon-120.png和icon-152.png. 将这个图标到你的项目资源文件夹并添加该图标到项目: 在此之 ...

  2. SharePreference 工具类封装

    import java.util.List;import java.util.Map;import java.util.Set;import com.alibaba.fastjson.JSON;imp ...

  3. 查看oracle表中列的数据类型

    一. SQLPLUS中,直接用 DESC[ribe] tablename 即可. 二.在外部应用程序调用查看ORACLE中的表结构时,只能用下面的语句代替: 1.看字段名与数据类型 select * ...

  4. Android 设置代理(验证用户名和密码)

    这几天在研究在Android中,解析网页,但是公司内容,链接外网需要代理,并需要验证用户名和密码,十分头疼,网上查了下,没有头绪,最后总算在一个外国博客中看到类似的,记录下 URL url = new ...

  5. homestead注意事项

    1.如何修改php.ini Here is how you grant read/write access to php.ini, modify it, save changes & relo ...

  6. Oracle 中的作业队列和队列调度

    一,启动执行作业的进程       在 Oracle 中,是使用 “作业队列协调进程(CJQ0)” 这个协调数据库实例的作业队列的后台进程,来监视作业队列中的作业表(JOB$),并启动作业队列进程(J ...

  7. Android框架之AndroidAnnotations基础

    一:开源网址 https://github.com/excilys/androidannotations/wiki 二:AndroidAnnotation特点 (1)依赖注入 可以注入 views, ...

  8. TSuperEnumerator、TSuperAvlIterator、ObjectFindFirst

    通过 ISuperObject.GetEnumerator 可获取一个 TSuperEnumerator 对象. TSuperEnumerator 主要有: MoveNext 方法.Current 属 ...

  9. iscsi: 多路径

    作者:吴香伟 发表于 2014/10/8 版权声明:可以任意转载,转载时务必以超链接形式标明文章原始出处和作者信息以及版权声明 上图(a)给出了计算机的总线结构,SCSI磁盘挂在SCSI卡上,SCSI ...

  10. Odoo Shell

    Odoo shell 提供了一个简便的操作 Odoo的交互界面, 从 odoo 9.0 开始就是标准功能, 无需安装第三方应用. 本文基于Odoo10 说明 Odoo Shell以及 Odoo Mod ...