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. cocos2d-x笔记4: TextField不能删除内容,以及我的解决办法。。。

    3.0正式版,win32下,TextField按下backspace键不能删除内容.网上搜了下,很早就有的问题了,正式版了竟然还不解决... 真心无力吐槽啊!!!这种巨大而又明显的Bug... 从昨天 ...

  2. 实现CodeFirst自动数据迁移无需命令

    本主题假设您掌握了实体框架中 Code First 迁移的基本知识. 借助自动迁移功能,您无需对您所做的每一个更改都在程序包管理器控制台中运行Update-Database 命令. 启用迁移 只需执行 ...

  3. C#开发攀爬集锦

    工具使用 Files has invalid value "<<<<<<< .mine". Illegal characters in p ...

  4. 国内外最全的asp.net开源项目 (转)

    最近一些项目开始用到CMS系统,最开始是研究JAVA的,无奈国内JAVA的CMS开源系统还是比较少,最多最成熟的还是PHP的,当然现在.NET的也不少了,这里做一下汇总备忘,留待学习研究. 国内系统: ...

  5. java项目打成jar包时引用了第三方jar,此时我们该如何解决呢

    Web项目做多了,反而对单纯的java项目陌生了,今天我们在开发项目的过程中,碰到一个这样的需求:需要将java项目放到linux系统上跑起来,当然这个javaSE项目是带main方法的.我们知道在I ...

  6. Java数据库连接关闭后无法启动

    错误如下: java.sql.SQLException: No operations allowed after connection closed. at com.mysql.jdbc.Connec ...

  7. 在 Visual Studio 2010 中创建 ASP.Net Web Service

    第一步:创建一个“ASP.Net Empty Web Application”项目 第二步:在项目中添加“Web Service”新项目 第一步之后,Visual Studio 2010会创建一个仅含 ...

  8. SPRING IN ACTION 第4版笔记-第三章Advancing wiring-001-DataSource在应用和开发环境之间切换 profile

    一. DataSource在应用和开发环境的产生方式不同,可以用srping 的profile管理 Spring’s solution for environment-specific beans i ...

  9. HTML标签与表格

    1.打开DREAMWEAVER,新建HTML,如下图: 2.body的属性: bgcolor 页面背景色 background    背景壁纸.图片 text  文字颜色 topmargin   上边 ...

  10. Perl,Python,Ruby,Javascript 四种脚本语言比较

    Perl 为了选择一个合适的脚本语言学习,今天查了不少有关Perl,Python,Ruby,Javascript的东西,可是发现各大阵营的人都在吹捧自己喜欢的语言,不过最没有争议的应该是Javascr ...