.NET环境下上传和下载Word文件
一、上传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文件的更多相关文章
- php 上传文件实例 上传并下载word文件
上传界面 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3 ...
- 11、只允许在主目录下上传和下载文件,不允许用putty登录
创建用户xiao, 使其只允许在用户主目录 (/var/www/html)下上传和下载文件,不允许用putty登录 (为了安全起见,不给过多的权限) 1.创建xiao用户 [root@localh ...
- XShell上传、下载本地文件到linux服务器
Python之道发表于程序员八阿哥订阅 1.2K 腾讯云服务器 年付3折起 首次购买云服务器 最低3折起 超高性价比 限时抢购 Xshell很好用,然后有时候想在windows和linux上传或下载某 ...
- SpringMVC下文件的上传与下载以及文件列表的显示
1.配置好SpringMVC环境-----SpringMVC的HelloWorld快速入门! 导入jar包:commons-fileupload-1.3.1.jar和commons-io-2.4.ja ...
- WP8_(windows phone环境下)上传文件从C#到php接口
在windows phone环境下,将手机上的图片上传到服务端(php环境): 注意事项:在上传的地方,头文件中name,例如name= img,则在php服务端处理时 ,需要约定好 存取一致 php ...
- IIS环境下上传文件失败
跟随学习代码练习 php 上传文件,一开始是点击按钮后没有反应,不知道是否成功,使用 var_dump($_FILES) 查看,发现空空如也.遂百度一下,发现基本代码应如下 <form acti ...
- linux学习 XShell上传、下载本地文件到linux服务器
(一)通过命令行的方式 1.linux服务器端设置 在linux主机上,安装上传下载工具包rz及sz; 如果不知道你要安装包的具体名称,可以使用yum provides */name 进行查找系统自带 ...
- 使用fastDFS上传和下载图片文件
package com.xuecheng.test.fastdfs;import org.csource.common.MyException;import org.csource.fastdfs.* ...
- WAMP环境下访问PHP提示下载PHP文件
原因是服务器没有加载到PHP文件 到http.conf下加载 AddType application/x-httpd-php .php AddType application/x-httpd-php ...
随机推荐
- C语言fgetpos()函数:获得当前文件的读写指针(转)
头文件:#include<stdio.h>fgetpos()函数获得当前文件的指针所指的位置,并把该指针所指的位置信息存放到pos所指的对象中.pos以内部格式存储,仅由fgetpos() ...
- javascript全局变量和局部变量
局部变量和全局变量可以同名.不过在函数体内部,局部变量的优先级高于全局变量.需要格外注意:专用于函数体内部的变量一定要用var关键字声明,否则该变量会变成全局变量.因为js是弱类型语言,所以它可以存放 ...
- Android停止运行问题1_layout布局xml问题
好好的写了300多行布局文件代码,写完之后运行结果,停止运行了.我当时就奇怪,xml有错误应该会提示啊,我就一个一个的缩小错误的代码范围,先直接换成一个简单的TextView ,运行一下没有错误.再慢 ...
- bootstarp-table表格中嵌套多个BUTON按钮实现
bootstarp-table表格中嵌套多个BUTON按钮实现 有时我们需要在bootsharp-table表格中嵌套多个按钮,来实现不同的功能,大概界面如下: 实现功能如下: 1:构建表格 ...
- Python之字符串小代码解析
本篇只是拿一段代码来对python中的字符串的一些使用做解释,来让大家更加了解python Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:25: ...
- ASP.NET中的Session怎么正确使用
Session对象用于存储从一个用户开始访问某个特定的aspx的页面起,到用户离开为止,特定的用户会话所需要的信息.用户在应用程序的页面切换时,Session对象的变量不会被清除. 对于一个Web应用 ...
- ssh学习小记
ssh 为Secure SHell 的缩写.OpenSSH: ssh协议的开源实现. SSH协议版本 v1: 基于CRC-32做MAC,不安全:man-in-middle v2:双方主机协议选择安全 ...
- 关于启动 SecureCRT 遇到一个致命的错误且必须关闭
--------------------------SecureCRT---------------------------SecureCRT 遇到一个致命的错误且必须关闭. 一个崩溃转储文件已创建于 ...
- <head></head>
<!DOCTYPE html><html lang="en"><head> <meta charset="utf-8&qu ...
- mac上的git completion
只安装bash-completion,是没有git补全的,因为此时/usr/local/etc/bash-completion.d/下面没有git-XXX.sh 解决方法是brew install g ...