c#操作word模板插入文字、图片及表格

1.建立word模板文件 person.dot
用书签 标示相关字段的填充位置

2.建立web应用程序 加入Microsoft.Office.Interop.Word引用
具体添加引用请参看
http://www.microsoft.com/china/msdn/library/office/office/OfficePrIntopAssFAQ.mspx?mfr=true

3.相关示例代码

protected void CreateReport_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Word.Application appWord = null;//应用程序
Microsoft.Office.Interop.Word.DocumentClass doc = null;//文档
try
{
appWord = new Microsoft.Office.Interop.Word.Application();
appWord.Visible = false;
object objTrue = true;
object objFalse = false;
object objTemplate = Server.MapPath("person.dot");//模板路径
object objDocType = WdDocumentType.wdTypeDocument;
doc = (DocumentClass)appWord.Documents.Add(ref objTemplate, ref objFalse, ref objDocType,ref objTrue);
//第一步生成word文档
//定义书签变量
object obDD_Name = "bm_Name";//姓 名
object obDD_Sex = "bm_Sex";//性 别
object obDD_Birthday = "bm_Birthday"; //出生年月
object obpic="pic";
object obtable = "obtable";
object Nothing = System.Reflection.Missing.Value;
//InlineShape shape = appWord.Selection.InlineShapes.AddPicture(@"F:\Picture\_DSC1602.JPG", ref Nothing, ref Nothing, ref Nothing);
//第二步 读取数据,填充数据集
System.Data.DataTable dt = new DataTable();
dt.Columns.Add("p_Name");
dt.Columns.Add("p_Sex");
dt.Columns.Add("p_Birthday");
DataRow dr = dt.NewRow();
dr["p_Name"] = "张三";
dr["p_Sex"] = "男";
dr["p_Birthday"] = "1980-01-01";
dt.Rows.Add(dr); //第三步 给书签赋值
//给书签赋值
doc.Bookmarks.get_Item(ref obDD_Name).Range.Text = dt.Rows[]["p_Name"].ToString(); //姓 名
doc.Bookmarks.get_Item(ref obDD_Sex).Range.Text = dt.Rows[]["p_Sex"].ToString();//性 别
doc.Bookmarks.get_Item(ref obDD_Birthday).Range.Text = dt.Rows[]["p_Birthday"].ToString();//年龄
doc.Bookmarks.get_Item(ref obpic).Range.InlineShapes.AddPicture(@"F:\Picture\_DSC1602.JPG", ref Nothing, ref Nothing, ref Nothing); //文档中插入表格
//doc.Bookmarks.get_Item(ref obtable).Range.Tables.Add(doc.Bookmarks.get_Item(ref obtable).Range, 12, 3, ref Nothing, ref Nothing);
Microsoft.Office.Interop.Word.Table newTable = doc.Tables.Add(doc.Bookmarks.get_Item(ref obtable).Range, , , ref Nothing, ref Nothing);
newTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;
newTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
//给文档的最后一行再添加内容
doc.Paragraphs.Last.Range.Text = ""; //第四步 生成word
object filename = Server.MapPath("~") + "\\BG\\" + dt.Rows[]["p_Name"].ToString() + ".doc";
object miss = System.Reflection.Missing.Value;
doc.SaveAs(ref filename, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
object missingValue = Type.Missing;
object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
appWord.Application.Quit(ref miss, ref miss, ref miss);
doc = null;
appWord = null; }
catch (System.Exception ex)
{
//捕捉异常,如果出现异常则清空实例,退出word,同时释放资源
string aa = ex.ToString();
object miss = System.Reflection.Missing.Value;
object missingValue = Type.Missing;
object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
doc.Close(ref doNotSaveChanges, ref missingValue, ref missingValue);
appWord.Application.Quit(ref miss, ref miss, ref miss);
doc = null;
appWord = null;
}
}

-----
以上代码在运行时 如遭遇80070005错误

解决方法一:
控制面板-》管理工具-》组件服务-》计算机-》我的电脑-》DCom配置-》找到Microsoft Word文档
之后
单击属性打开此应用程序的属性对话框。 
2. 单击标识选项卡,然后选择交互式用户。 
3.单击"安全"选项卡,分别在"启动和激活权限"和"访问权限"组中选中"自定义",然后
自定义->编辑->添加ASP.NET账户和IUSER_计算机名
4. 确保允许每个用户访问,然后单击确定。 
5. 单击确定关闭 DCOMCNFG。

解决方法二:
如果上述方法不能解决问题,就应该是权限问题,请尝试用下面的方法:
在web.config中使用身份模拟,在<system.web>节中加入 <identity impersonate="true" userName="你的用户名

" password="密码"/>
</system.web>

参考文档:http://wenku.baidu.com/view/fc8aa56fb84ae45c3b358c98.html

附:图片的详细操作

object filename = @"C:\Inetpub\wwwroot\TestWebApp\test.doc";//文件名 
Word.Application a = new Word.ApplicationClass();//建立一个Word程序对像 
object Nothing = System.Reflection.Missing.Value;//空值 
Word.Document b = a.Documents.Open(ref filename,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing);//建立一个Word文档对像

//其实这步就是执行了这个宏 
InlineShape shape = a.Selection.InlineShapes.AddPicture(@"C:\Documents and Settings\Administrator\桌面\2003121512223366481.jpg",ref Nothing,ref Nothing,ref Nothing);

shape.Height = InchesToPoints(0.5) 
shape.Width = InchesToPoints(0.5)

//Selection.InlineShapes.AddPicture FileName:= "C:\Documents and Settings\Administrator\桌面\2003121512223366481.bmp", LinkToFile:=False, SaveWithDocument:=True End Sub b.Save();//保存 
b.Close(ref Nothing,ref Nothing,ref Nothing);//关闭Word文档 
a.Quit(ref Nothing,ref Nothing,ref Nothing);//退出Word程序

c# 向word中指定的书签写数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
//using System.Web.UI.HTMLControls;
//using Microsoft.office;
using Microsoft.Office.Core;
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Word; namespace common
{
public class WriteInWord
{ ApplicationClass app = null;//定义应用程序对象
Document doc = null; //定义word文档对象
Object missing = System.Reflection.Missing.Value;//定义空变量 Object isReadOnly = false;
public void OpenDocument(string parFilePath)
{ object filePath = parFilePath;//文档路径 app = new ApplicationClass(); //打开文档 doc = app.Documents.Open(ref filePath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); doc.Activate();//激活文档 } /// <summary> /// 向word文档写入数据 /// </summary> /// <param name="parLableName">域标签</param> /// <param name="parFillName">写入域中的内容</param> public void WriteIntoDocument(string parLableName, string parFillName)
{ object lableName = parLableName; Bookmark bm = doc.Bookmarks.get_Item(ref lableName);//返回标签 bm.Range.Text = parFillName;//设置域标签的内容 }
/// <summary> /// 保存并关闭 /// </summary> /// <param name="parSaveDocPath">文档另存为的路径</param> public void SaveAndClose(string parSaveDocPath)
{ object savePath = parSaveDocPath;//文档另存为的路径 Object saveChanges = app.Options.BackgroundSave;//关闭doc文档不提示保存 //文档另存为 doc.SaveAs(ref savePath, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); doc.Close(ref saveChanges, ref missing, ref missing);//关闭文档 app.Quit(ref missing, ref missing, ref missing); //关闭应用程序 } }

---------------------
作者:hy31337
来源:CNBLOGS
原文:https://www.cnblogs.com/elves/p/3624115.html
版权声明:本文为作者原创文章,转载请附上博文链接!

[转]C#操作word模板插入文字、图片及表格详细步骤的更多相关文章

  1. C#操作word模板插入文字、图片及表格详细步骤

    c#操作word模板插入文字.图片及表格 1.建立word模板文件 person.dot用书签 标示相关字段的填充位置 2.建立web应用程序 加入Microsoft.Office.Interop.W ...

  2. Csharp 简单操作Word模板文件

    原文:Csharp 简单操作Word模板文件 1.创建一个模板的Word文档  Doc1.dot 内容为: To: <Name> Sub:<Subject> Website i ...

  3. Qt 向word中插入文字(使用QAxWidget和QAxObject)

    pro 文件中要加入 CONFIG += qaxcontainer 2. main.cpp #include <QApplication> #include <QAxWidget&g ...

  4. word----遇到问题-----word中插入的图片无法左对齐----格式按钮为灰色

    当我们在用word时,有时要插入图片,却发现,插入的图片只在中间位置,不能拖到左边,这时怎么办呢 主要是图层的高低原因导致的不能拖动. 这个时候我们只需要设置一下图片的图层类型即可. 对着图片右键在设 ...

  5. C# 操作word 模板 值 替换

    1.引用 aspose.words   dll 2.word 使用doc 3.给word 模板中添加要替换位置的 书签 .引用 aspose.words dll .word 使用doc .给word ...

  6. 利用Python操作Word文档【图片】

    利用Python操作Word文档

  7. 教你一招:Word中的文字转换成表格,把表格转换成文字

    在使用office软件时,常常会在Word中加入表格,这时候我们一般想到的是,建立表格,然后一格一格的填写;或者用Excel表格制作在复制到Word文档中.其实在Word中就可以将文本文档转换成电子表 ...

  8. c#调用Aspose.Word组件操作word 插入文字/图片/表格 书签替换套打

    由于NPOI暂时没找到书签内容替换功能,所以换用Apose.Word组件. using System; using System.Collections.Generic; using System.C ...

  9. C#操作word之插入图片

    假如我们导出一份简历到word文档,那势必可能要同时导出我们包含的简历,下面就来试一下如何和通过C#代码,将图片插入到word文档中. 为了简便起见,就简单一点.类似下面这样的 姓名 张三 照片   ...

随机推荐

  1. 洛谷 P1948 [USACO08JAN]电话线Telephone Lines 最短路+二分答案

    目录 题面 题目链接 题目描述 输入输出格式 输入格式 输出格式 输入输出样例 输入样例 输出样例 说明 思路 AC代码 题面 题目链接 P1948 [USACO08JAN]电话线Telephone ...

  2. Lunix文件的读写权限问题

    今天把在windows平台build好的lunix执行文件复制到Lunix的虚拟机上,发现可执行文件不能执行了,后来才发现文件时有读写和可执行权限的,但是是可以更改的,右键属性,把可执行属性勾选上就可 ...

  3. 【风马一族_mysql】mysql基本指令

    船停在港湾是很安全的,但那不是造船的目的! 用户 创建用户 mysql>grant 权限(select,insert,update,delete) on  数据库.数据表  to  用户名@电脑 ...

  4. 解决PowerDesigner中DBMS选项卡为空白

    点击DBMS后面的黄色(浏览)文件图标, 找到安装目录里面PowerDesigner \Resource Files\DBMS,就可以了.

  5. UVA_401:Palindromes

    AC:Time(29ms)     C++ 4.8.2 #include<stdio.h> #include<string.h> char * mirstr = "A ...

  6. AT2377 Blue and Red Tree

    AT2377 Blue and Red Tree 法一:正推 红色的边在蓝色的树上覆盖,一定每次选择的是覆盖次数为1的边的覆盖这条边的红色边连出来 覆盖次数可以树剖找到 这条红色边,可以开始的时候每个 ...

  7. 2017 ACM-ICPC 亚洲区(南宁赛区)网络赛 M. Frequent Subsets Problem【状态压缩】

    2017 ACM-ICPC 亚洲区(南宁赛区)网络赛  M. Frequent Subsets Problem 题意:给定N和α还有M个U={1,2,3,...N}的子集,求子集X个数,X满足:X是U ...

  8. Spring Security入门篇——标签sec:authorize的使用

    Security框架可以精确控制页面的一个按钮.链接,它在页面上权限的控制实际上是通过它提供的标签来做到的 Security共有三类标签authorize authentication accessc ...

  9. Javascript用正则表达式replace替换父串中所有符合条件的子串

    这样用,只会替换匹配到的第一个子串 str = 'I hava a pen ,I hava an apple,apple pen, pen apple' str = str.replace('appl ...

  10. 洛谷P2947 [USACO09MAR]向右看齐Look Up

    #include<cstdio> #include<algorithm> #include<stack> #include<cctype> using ...