一、上传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打开模板,之后选择“开发工具”选项卡,如果这个选项卡选择之后,内部的小控件是不可编辑的,则需要进行相应的设置,然后添加标签或者查看表格的属性就可以完成模板的设置。

05-08 15:09