技术开发 频道

使用Open XML SDK 2.0生成Office文档

  【IT168 技术文档】我们会利用OpenXML SDK 2.0写程序生成一个Word文档。在这个文档中有一个表含有产品信息。每个产品的名称,类别,价钱和图像都显示在一个表格里。而这些信息又是从后台数据库里提取出来的。下面是几个步骤:

  • 添加引用到OpenXML SDK

  • 生成一个Word文档

  • 定义一个表(Table)和它的列

  • 给这个表加一行台头

  • 将每个产品信息生成一行添加到表单里

  • 将表加入到文档中

  备注:在这个程序中我们只更改Program.cs里的程序代码。

  1. 在解决方案资源管理器中, 右击 项目CreateDocFromDatabase 然后选中添加引用。

  2. 在添加引用对话框中,选择.Net tab,向下滚动,选中DocumentFormat.OpenXml,, 点击确定按钮。

  3. 用同样步骤添加对System.Drawing 和 WindowsBase的引用.

  备注:如果有多个WindowsBase,选中路径是c:\Program Files\Reference Assemblies\Microsoft \Framework\v3.0\WindowsBase.dll

  4. 删除在上一步加入在Main(){ }的程序:在解决方案资源管理器中,右击Program.cs 打开程序编辑页面。删除Main() { }中的所有程序。你的程序应该看上去像是这样:

  using System;
  
using System.Collections.Generic;
  
using System.Linq;
  
using System.Text;
  
namespace CreateDocFromDatabase
  {
  
class Program
  {
  
static void Main(string[] args)
  {
  }
  }
  }

   5. 将下面的代码段加入到最后一个Using 语句后面;为避免手工输入这些语句,可以通过插入代码段 | My Code Snippets | UsingStatement

  Using DocumentFormat.OpenXml;
  Using DocumentFormat.OpenXml.Packaging;
  Using DocumentFormat.OpenXml.Wordprocessing;
  Using wp
= DocumentFormat.OpenXml.Drawing.Wordprocessing;
  Using a
= DocumentFormat.OpenXml.Drawing;
  Using pic
= DocumentFormat.OpenXml.Drawing.Pictures;
  Using System.IO;
  Using System.Drawing;
  Your code should look like the following:
  
using System;
  
using System.Collections.Generic;
  
using System.Linq;
  
using System.Text;
  
using DocumentFormat.OpenXml;
  
using DocumentFormat.OpenXml.Packaging;
  
using DocumentFormat.OpenXml.Wordprocessing;
  
using wp = DocumentFormat.OpenXml.Drawing.Wordprocessing;
  
using a = DocumentFormat.OpenXml.Drawing;
  
using pic = DocumentFormat.OpenXml.Drawing.Pictures;
  
using System.IO;
  
using System.Drawing;
  
namespace CreateDocFromDatabase
  {
  
class Program
  {
  
static void Main(string[] args)
  {
  }
  }
  }

 

0
相关文章