在Excel中创建和使用ServerDocument
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的更多相关文章
- Java 在Excel中创建透视表
本文内容介绍通过Java程序在Excel表格中根据数据来创建透视表. 环境准备 需要使用Excel类库工具—Free Spire.XLS for Java,这里使用的是免费版,可通过官网下载Jar包并 ...
- VBA在EXCEL中创建图形线条
EXCEL使用了多少行: ActiveSheet.UsedRange.Rows.Count(再也不用循环到头啦) 创建线条并命名:ActiveSheet.Shapes.AddLine(x1,y1,x2 ...
- [转] JAVA中读取网络中的图片资源导入到EXCEL中
需求 导出人员的信息并且加上人员的照片至EXCEL中 完整的代码 //创建一个表格 HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb ...
- C#中创建、打开、读取、写入、保存Excel的一般性代码
---转载:http://hi.baidu.com/zhaocbo/item/e840bcf941932d15fe358228 1. Excel对象微软的Excel对象模型包括了128个不同的对象,从 ...
- 【NPOI】通过NPOI从内存流中创建EXCEL
一言不合就开始帖代码 XSSFWorkbook workbook = new XSSFWorkbook(); //创建工作簿 XSSFSheet sheet = (XSSFSheet)workbook ...
- C#利用NPOI在同一个Excel文件中创建多个sheet
借用NPOI来实现,要在同一Excel文件中创建多个sheet,只需要在同一个workbook中创建多个sheet即可.要注意的是,sheet的名字一定不能重复.下面是实现的代码: private v ...
- NOPI读取模板导出(Excel中追加数据)
在Controller里,我们定义一个FileResult的Action,返回值是一个文件形式被浏览器下载下来. [HttpGet] public FileResult ExportProductLi ...
- 如何使用免费控件将Word表格中的数据导入到Excel中
我通常使用MS Excel来存储和处理大量数据,但有时候经常会碰到一个问题—我需要的数据存储在word表格中,而不是在Excel中,这样处理起来非常麻烦,尤其是在数据比较庞大的时候, 这时我迫切地需要 ...
- 在Excel中使用SQL语句查询和筛选
本文转自:http://blog.sina.com.cn/s/blog_5fc375650102e1g5.html 今天在微博上看到@数据分析精选 分享的一篇文章,是关于<在Excel中使用SQ ...
随机推荐
- xe6+firedac连接sybase
一.Win7 X64系统安装sybase odbc: 1. 下载对应包至c:\system_odbc(文件夹名自己取,在后面注册表内容需要用到): 2. 将值信息写入到注册表内: Windows ...
- cocos2dx 3.3创建新项目 和 VS2012解决方案加载失败问题
首先创建新项目,步骤如下: 1.进入cocos2d-x-3.3\tools\cocos2d-console\bin目录,按住shift+鼠标右键 2.输入 cocos new 项目名 –p 包名 – ...
- Android WebView缓存分析
http://blog.csdn.net/a345017062/article/details/8703221 WebView的缓存可以分为页面缓存和数据缓存. 页面缓存是指加载一个网页时的htm ...
- [置顶] Android Journal
==================================================================================================== ...
- Hbase案例分析(一)
Hbase应用场景: 1 随机读或者写 2 大数据上的高并发操作,比如每秒对PB级数据进行上千次操作.(查询,删除等操作) 3 读写均是非常简单的操作,比如没有join操作 Hbase Schema设 ...
- perl post json数据
use LWP::UserAgent; use URI::Escape; use Net::Ping; use JSON qw(encode_json); use Socket; use Net::S ...
- Wide character in print at a2.pl line 6.
jrhapt01:/home/tomcat/test> cat a2.pl my $str="$ARGV[0]"; use Encode; use URI::Escape; ...
- 安卓高手之路之java层Binder
很多人一提到Binder就说代理模式,人云亦云的多,能理解精髓的少. 本篇文章就从设计角度分析一下java层BInder的设计目标,以及设计思路,设计缺陷,从而驾驭它. 对于[邦德儿]的理解, 从通信 ...
- fuser可以用于系统安全检查。
fuser可以用于系统安全检查.用fuser查看哪些用户和进程在某些地方作什么:fuser -cu /root 简略显示fuser -muv /mnt3 分列显示
- MySQL5.6 基于db的并行复制
slave的几个类结构: Master_info:用于IO线程的参数,包括连接master实例的信息. Relay_log_info:用于sql线程,表示relay log相关的信 ...