在Excel中创建和使用ServerDocument

ServerDocument是微软提供的一种读取WordExcel文档级应用中CachedData的工具。本示例将向你展示如何使用用ServerDocument

 

1.      创建文档级应用

打开Visual Studio,

新建一个Excel Workbook应用

2.     创建数据模型

在类库中,建产一个名为“ContractTable”的数据表。

我们在类库中写一个“DataSource”的类来封装对数据表的操作。

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataModle
{
    /// <summary>
    /// DataSource类
    /// </summary>
    public class DataSource
    {
        private DataSet1 source = null;

        public DataSet1 Source
        {
            set
            {
                source = value;
            }
            get
            {
                return source;
            }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public DataSource()
            : base()
        {
            source = new DataSet1();
        }

        /// <summary>
        /// AddData方法,用来向数据集添加数据
        /// </summary>
        /// <param name="paramCollection">数据</param>
        public void AddData(params object[] paramCollection)
        {
            try
            {
                source.Tables["ContractTable"].Rows.Add(paramCollection[0],
                    paramCollection[1], paramCollection[2]);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}


 

3.      在文档级应用中使用数据模型

ExcelWorkbook工程中,我们先引入上面的那个类库

然后在Sheet1安放一个List空件用来显示数据。

Sheet1.cs中通过以下代码来实现Cached Data。在ServerDocument中我们的主要目的就是操作这些Cached Data

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using Microsoft.Office.Tools.Excel;
using Microsoft.VisualStudio.Tools.Applications.Runtime;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using DataModle;

namespace ExcelWorkbook1
{
    public partial class Sheet1
    {
        public DataSet mySource = null;

        private void Sheet1_Startup(object sender, System.EventArgs e)
        {
            // 判断是否存在Cached Data“mySource”
            if (!IsCached("mySource"))
            {
                var source = new DataSource();
                mySource = source.Source;
                // 建立Cached Data并绑定到list1
                StartCaching("mySource");
                source.AddData(1, "郭靖", "桃花岛");
                source.AddData(2, "黄蓉", "桃花岛");
                source.AddData(3, "郭芙", "桃花岛");
                list1.SetDataBinding(mySource.Tables["ContractTable"]);
            }
            else
            {
                if (mySource != null)
                {
                    list1.SetDataBinding(mySource.Tables["ContractTable"]);
                }
            }
        }

        private void Sheet1_Shutdown(object sender, System.EventArgs e)
        {
        }

        #region VSTO 设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(Sheet1_Startup);
            this.Shutdown += new System.EventHandler(Sheet1_Shutdown);
        }

        #endregion

    }
}


 

4.      创建ServerDocument应用程序

建建一个控制台程序来实现使用ServerDocument操作ExcelWorkbook1

在开始写代码前我们先要引入“Microsoft.VisualtStudio.Applications.ServerDocument”组件。ServerDocument类就在这个组件中。

由于在程序中我们会用到一些Winform的组件。所以,我们还需要引用一下“System.Windows.Forms”组件。

在程序中我们写入以下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Windows.Forms;
using Microsoft.VisualStudio.Tools.Applications;
using System.Data;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            OpenFileDialog OFD = new OpenFileDialog();
            OFD.Filter = "Excel Document| *.xls;*.xlsx";
            OFD.Multiselect = false;
            OFD.ShowDialog();
            try
            {
                // 打开ServerDocument
                ServerDocument SD = new ServerDocument(OFD.FileName);
                // 获取CachedDataHostItem
                CachedDataHostItem CDHI = SD.CachedData
                    .HostItems["ExcelWorkbook1.Sheet1"];
                // 获取CachedDataItem
                CachedDataItem CDI = CDHI.CachedData["mySource"];

                // 以下为数据处理过程
                DataSet ds = new DataSet("DataSet1");
                MemoryStream ms = new MemoryStream();
                StreamWriter sw = new StreamWriter(ms);
                sw.Write(CDI.Schema);
                sw.Flush();
                ms.Position = 0;
                ds.ReadXmlSchema(ms);
                MemoryStream mss = new MemoryStream();
                sw.Close();
                sw = new StreamWriter(mss);
                sw.Write(CDI.Xml);
                sw.Flush();
                mss.Position = 0;
                ds.ReadXml(mss);
                ds.Tables["ContractTable"].Rows.Add(4, "郭襄", "襄阳");
                CDI.SerializeDataInstance(ds);
                SD.Save();
                SD.Close();
                sw.Close();
                ms.Close();

                ConsoleColor original = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Complete!");
                Console.ForegroundColor = original;
            }
            catch (Exception ex)
            {
                ConsoleColor original = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ForegroundColor = original;
            }
            Console.ReadKey();
        }
    }
}


将编译好的ExcelWorkbook1(在bin目录下的那个Excel文档),运行结果如下:

然后关闭Excel会弹出对话框,要求保存文档。选择保存(这很重要,如果不保存就不会有Cached Data保存在Excel文档中)。

运行控制台程序,选中刚才的那个Excel文档。

运行结果如图:

然后我们打开那个Excel文档,我们就可以发现有条新记录已经通过控制台程写入的文档中.

posted @ 2013-08-11 20:35  许阳 无锡  阅读(268)  评论(0编辑  收藏  举报