ServerDocument是微软提供的一种读取Word或Excel文档级应用中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文档,我们就可以发现有条新记录已经通过控制台程写入的文档中.

在Excel中创建和使用ServerDocument的更多相关文章

  1. Java 在Excel中创建透视表

    本文内容介绍通过Java程序在Excel表格中根据数据来创建透视表. 环境准备 需要使用Excel类库工具—Free Spire.XLS for Java,这里使用的是免费版,可通过官网下载Jar包并 ...

  2. VBA在EXCEL中创建图形线条

    EXCEL使用了多少行: ActiveSheet.UsedRange.Rows.Count(再也不用循环到头啦) 创建线条并命名:ActiveSheet.Shapes.AddLine(x1,y1,x2 ...

  3. [转] JAVA中读取网络中的图片资源导入到EXCEL中

    需求 导出人员的信息并且加上人员的照片至EXCEL中 完整的代码 //创建一个表格 HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb ...

  4. C#中创建、打开、读取、写入、保存Excel的一般性代码

    ---转载:http://hi.baidu.com/zhaocbo/item/e840bcf941932d15fe358228 1. Excel对象微软的Excel对象模型包括了128个不同的对象,从 ...

  5. 【NPOI】通过NPOI从内存流中创建EXCEL

    一言不合就开始帖代码 XSSFWorkbook workbook = new XSSFWorkbook(); //创建工作簿 XSSFSheet sheet = (XSSFSheet)workbook ...

  6. C#利用NPOI在同一个Excel文件中创建多个sheet

    借用NPOI来实现,要在同一Excel文件中创建多个sheet,只需要在同一个workbook中创建多个sheet即可.要注意的是,sheet的名字一定不能重复.下面是实现的代码: private v ...

  7. NOPI读取模板导出(Excel中追加数据)

    在Controller里,我们定义一个FileResult的Action,返回值是一个文件形式被浏览器下载下来. [HttpGet] public FileResult ExportProductLi ...

  8. 如何使用免费控件将Word表格中的数据导入到Excel中

    我通常使用MS Excel来存储和处理大量数据,但有时候经常会碰到一个问题—我需要的数据存储在word表格中,而不是在Excel中,这样处理起来非常麻烦,尤其是在数据比较庞大的时候, 这时我迫切地需要 ...

  9. 在Excel中使用SQL语句查询和筛选

    本文转自:http://blog.sina.com.cn/s/blog_5fc375650102e1g5.html 今天在微博上看到@数据分析精选 分享的一篇文章,是关于<在Excel中使用SQ ...

随机推荐

  1. shell编程的一些例子3

    数值处理 1.let 命令 bash 的内部命令let可以用来计算算术表达式的值.如果表达式中有空格或者特殊字符,则应将表达式括在双引号中. let的语法命令:let express-list 如果最 ...

  2. C#函数的方法定义和方法调用小议

    using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cons ...

  3. bzoj 3527: [Zjoi2014]力 快速傅里叶变换

    题意: 给出n个数qi,给出Fj的定义如下:  令Ei=Fi/qi,求Ei. fft的那一堆东西还是背不到啊...这次写虽说完全自己写的,但是还是在参见了以前fft程序的情况下调了很久,主要在如下几点 ...

  4. [转贴]WebService的简单实现 C++

    WebService的简单实现 一.socket主机创建和使用过程 1.socket()//创建套接字 2.Setsockopt()//将套接字属性设置为允许和特定地点绑定 3.Bind()//将套接 ...

  5. UVA_393_Doors_(计算几何基础+最短路)

    描述 https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=5&page ...

  6. 应用程序域 z

    应用程序域(AppDomain)已经不是一个新名词了,只要熟悉.net的都知道它的存在,不过我们还是先一起来重新认识下应用程序域吧,究竟它是何方神圣. 应用程序域 众所周知,进程是代码执行和资源分配的 ...

  7. AppScan修复漏洞:启用不安全的HTTP方法

    最近对于系统使用Appscan扫描出中危漏洞“启用不安全的HTTP方法,找了很多修复方法都不能达到效果. 漏洞截图: 漏洞描述: 危险级别   中危险 影响页面   整个WEB页面. 简短描述   管 ...

  8. 员工部门表综合查询SQL

    --数据库的表设计如下: --部门:部门编号,部门名称,地址: --员工:员工编号,员工名字,职务,管理编号,入职日期,薪资,奖金,部门编号: --创建部门表: CREATE TABLE dept( ...

  9. List<T>的IndexOf方法和Remove方法

    Microsoft地址 List<T>的IndexOf()方法 如果T是值类型的,就按照比较值的方法从列表的第一个元素开始逐个匹配,如果T是引用类型,就比较引用是否相同 举例如下: cla ...

  10. Tomcat7.0配置

    Tomcat7.0下载地址:http://tomcat.apache.org/download-70.cgi 选择符合自己操作系统的版本即可(本机win8-64位系统),选择如下: http://11 ...