• .NET环境下上传和下载Word文件


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

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

    [WebMethod]
            public void UploadFile()
            {
                using (TransactionScope ts = new TransactionScope())
                {
                    var postedFiles = Request.GetHttpFiles();
                    var guid = postedFiles[0].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(".") + 1);
    
                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:memberwanghuanjunIpmsSolution.3Ipms.WebSiteIpmsDocument
                    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[1];
    
                    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(1, 3).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName;
                    wordTable.Cell(2, 3).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.EnglishName;
                    wordTable.Cell(3, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.Quantity.ToString();
                    wordTable.Cell(3, 4).Range.Text = (memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.UnitPrice / 100).ToString() + "";
                    wordTable.Cell(3, 6).Range.Text = ((memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.UnitPrice * memI.ConstructPlanItem.MemberApplyItem.Quantity) / 100).ToString() + "";
    
                    wordTable.Cell(5, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.NecessityAnalysis;
                    wordTable.Cell(12, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.MainSpec;
                    wordTable.Cell(27, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.AccessorySpec;
    
                    wordTable.Cell(1, 6).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Environment;
                    wordTable.Cell(7, 9).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Consumables;
                    wordTable.Cell(9, 9).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.Power;
    
                    var deviceMaths = Database.DeviceMatchs.Where(dm => dm.ApplyDevice == memI.ConstructPlanItem.MemberApplyItem.ApplyDevice);
                    var temp = 0;
                    //设备选型
                    if (deviceMaths.Count() > 0 && deviceMaths.Count() <= 4)
                        foreach (var item in deviceMaths)
                        {
                            if (item != null)
                            {
                                wordTable.Cell(2, 5 + temp).Range.Text = item.MarketDevice.MarketDeviceName;
                                wordTable.Cell(4, 8 + temp).Range.Text = item.MarketDevice.Model;
    
                                var deviceSupplier = Database.DeviceSuppliers.Where(ds => ds.DeviceMatch == item).FirstOrDefault();
                                if (deviceSupplier != null)
                                {
                                    wordTable.Cell(6, 4 + temp).Range.Text = deviceSupplier.Supplier.Name;
                                    wordTable.Cell(7, 4 + temp).Range.Text = deviceSupplier.ContactPerson + ":" + deviceSupplier.ContactPhone;
                                    wordTable.Cell(8, 4 + temp).Range.Text = (deviceSupplier.Price / 100).ToString() + "";
                                    wordTable.Cell(9, 4 + temp).Range.Text = deviceSupplier.PriceSource == 0 ? "供应商" : "网络";
                                }
                            }
                            temp += 1;
                        }
                    var extrals = Database.DeviceExtramurals.Where(de => de.ApplyDevice == memI.ConstructPlanItem.MemberApplyItem.ApplyDevice).ToList();
                    if (extrals.Count() > 0 && extrals.Count() <= 4)
                    {
                        if (extrals.Count() >= 1)
                        {
                            wordTable.Cell(11, 4).Range.Text = extrals[0].Brand.ToString();
                            wordTable.Cell(11, 5).Range.Text = extrals[0].WorkUnit.ToString();
                            wordTable.Cell(11, 6).Range.Text = extrals[0].UserName;
                            wordTable.Cell(11, 7).Range.Text = extrals[0].BuyTime.Value.ToShortDateString();
                            wordTable.Cell(11, 8).Range.Text = (extrals[0].UnitPrice/100).ToString()+"";
                            for (int i = 1; i < extrals.Count(); i++)
                            {
                                wordTable.Cell(11 + i, 4).Range.Text = extrals[i].Brand.ToString();
                                wordTable.Cell(11 + i, 5).Range.Text = extrals[i].WorkUnit.ToString();
                                wordTable.Cell(11 + i, 6).Range.Text = extrals[i].UserName;
                                wordTable.Cell(11 + i, 7).Range.Text = extrals[i].BuyTime.Value.ToShortDateString();
                                wordTable.Cell(11 + i, 8).Range.Text = (extrals[i].UnitPrice/100).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:memberwanghuanjunIpmsSolution.3Ipms.WebSiteIpmsDocument
                    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[1];
    
                    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(1, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.DeviceName;
                    wordTable.Cell(2, 2).Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.EnglishName;
                    wordTable.Cell(3, 4).Range.Text = memI.ConstructPlanItem.MemberApplyItem.Quantity.ToString();
                    wordTable.Cell(3, 2).Range.Text = (memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.UnitPrice / 100).ToString() + "";
                    wordTable.Cell(3, 6).Range.Text = ((memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.UnitPrice * memI.ConstructPlanItem.MemberApplyItem.Quantity) / 100).ToString() + "";
    
                    wordDocument.Bookmarks.get_Item("NecessityAnalysis").Range.Text = memI.ConstructPlanItem.MemberApplyItem.ApplyDevice.NecessityAnalysis;
                    wordTable.Cell(5, 2).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打开模板,之后选择“开发工具”选项卡,如果这个选项卡选择之后,内部的小控件是不可编辑的,则需要进行相应的设置,然后添加标签或者查看表格的属性就可以完成模板的设置。

  • 相关阅读:
    db2 v11 安装测试
    DB2支持的三种表空间SMS、DMS、DMS的自动存储
    linux几种快速清空文件内容的方法
    修改文件或者文件夹权限
    db2start启动失败
    db2icrt创建实例,提示主机名无效
    浏览器内核以及在各个浏览器的前缀
    程序的三大结构(顺序结构、选择结构、循环结构)
    数组中元素的排序(常用的冒泡排序、选择排序、快速排序)
    数组的api以及api的简单使用
  • 原文地址:https://www.cnblogs.com/jzwh/p/3448292.html
Copyright © 2020-2023  润新知