c#调用word com组件 替换书签套打
安装office2007,添加com引用Microsoft Word12.0 Object Library和Microsoft Office12.0 Object Library
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; using Microsoft.Office.Interop.Word;
using System.Reflection;
using System.Data; namespace CunJuInformationPlatformDataService.CommonClass
{
public class WordAPI
{
public static Paragraph AddParagraph(DocumentClass wordDoc, string contentTxt,WdParagraphAlignment align=WdParagraphAlignment.wdAlignParagraphLeft,int fontBold=1,int fontSize=12)
{
//由于使用的是COM库,因此有许多变量需要用Missing.Value代替
Object Nothing = System.Reflection.Missing.Value;//创建文档 // ////////////////////////////////
//Insert a paragraph at the beginning of the document
Microsoft.Office.Interop.Word.Paragraph myparagraph1;
myparagraph1 = wordDoc.Content.Paragraphs.Add(ref Nothing);
myparagraph1.Range.Text = contentTxt; //换3行显示123
myparagraph1.Alignment = align; //段落居左
myparagraph1.Range.Font.Bold = fontBold;
myparagraph1.Range.Font.Size = fontSize;
myparagraph1.Format.SpaceAfter = 24; //距离下一段的下边距(margin-bottom,单位是pt)
myparagraph1.Range.InsertParagraphAfter(); return myparagraph1;
} public static void AddImage(DocumentClass wordDoc,string imgPath,float width=-1,float height=-1)
{
object oEndOfDoc = "\\endofdoc";/*预置书签表示文档结尾,原文有错误反斜杠写成了//正斜杠,导致下面的myrange有问题*/
object myrange = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
//定义该插入的图片是否为外部链接
Object linkToFile = false; //默认
//定义要插入的图片是否随Word文档一起保存
Object saveWithDocument = true; //默认
//使用InlineShapes.AddPicture方法插入图片
wordDoc.InlineShapes.AddPicture(imgPath, ref linkToFile, ref saveWithDocument, ref myrange);
if (width!=-1)
{ wordDoc.Application.ActiveDocument.InlineShapes[1].Width = height;//图片宽度
}
if (height != -1)
{ wordDoc.Application.ActiveDocument.InlineShapes[1].Height = height;//图片高度
} Microsoft.Office.Interop.Word.Paragraph return_pragraph;
object myrange2 = wordDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
return_pragraph = wordDoc.Content.Paragraphs.Add(ref myrange2);
return_pragraph.Range.InsertParagraphAfter(); //插入一个空白行
} public static void BookMarkReplace(Document wordDoc, string bookMark, string type, string value)
{ foreach (Bookmark bm in wordDoc.Bookmarks)
{
if (bm.Name == bookMark)
{
Object missing = Missing.Value;
if (type == "IMG")
{
bm.Select();
//bm.Range.Text = "";//这句不能加加了下句就报对象已被移除,所以做图片书签的时候选空格来做就看不出来了
var img=bm.Range.InlineShapes.AddPicture(@value, ref missing, ref missing); //插入图片
img.Width = 600; //自动等比
//img.Height = 300; }
else if (type == "TABLE")
{
System.Data.DataTable table = Utils.JsonDataTableConvert.ToDataTable(value);//json转datatable //http://zhidao.baidu.com/link?url=Zo7GtNDbA3cnqy-g2QM9cIEWxrw5Le6W0l_MsNnYnF_d6NrEufjkmjGyZj9AC2liuj8JSSKiw4nky6MHueexEFk99z8XXpOo2_eMct2MIB3
Table wtable = wordDoc.Tables.Add(wordDoc.Bookmarks.get_Item(bookMark).Range, table.Rows.Count + 1, table.Columns.Count); /*行+1是表格列头*/ System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start(); // 开始监视代码运行时间 wtable.set_Style("网格型"); int tableRowCount = table.Rows.Count;
int tableColumnCount = table.Columns.Count;
//表格列名
for (int i = 1; i <= tableColumnCount; i++)
{
wtable.Rows[1].Cells[i].Range.Font.Bold = 1;
wtable.Rows[1].Cells[i].Range.Font.Size=10;
wtable.Rows[1].Cells[i].Range.Text = table.Columns[i - 1].ColumnName;
}
//循环往表格里赋值
for (int i = 1; i <= tableRowCount; i++)
{
for (int j = 1; j <= tableColumnCount; j++)
{
wtable.Rows[i + 1].Cells[j].Range.Font.Bold = 0;
wtable.Rows[i + 1].Cells[j].Range.Font.Size = 10;
wtable.Rows[i + 1].Cells[j].Range.Text = table.Rows[i - 1][j - 1].ToString();
}
} // your code ....
stopwatch.Stop(); // 停止监视
TimeSpan timespan = stopwatch.Elapsed; // 获取当前实例测量得出的总时间
double hours = timespan.TotalHours; // 总小时
double minutes = timespan.TotalMinutes; // 总分钟
double seconds = timespan.TotalSeconds; // 总秒数
double milliseconds = timespan.TotalMilliseconds; // 总毫秒数 Logger.InfoLog(tableRowCount+"行*"+tableColumnCount+"列,耗时:"+minutes+"分钟,折合:"+seconds+"秒."); }
else
{//其他文字,日期等文字
bm.Select();//选中书签
bm.Range.Text = value + "\r\n";//替换文字
} break;
}
} } }
}
调用:
DateTime dt = DateTime.Now;
var basePath = Server.MapPath("~/Upload/");
object savePathWord = basePath + "tem/" + dt.ToString("yyyy-MM-dd--HH-mm-ss-") + dt.Millisecond + "_" + fileName + ".docx"; File.Copy(Server.MapPath("~/") + wordTemplatePath, savePathWord.ToString()); Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
appWord.ScreenUpdating = false;
Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
object Visible = false;
object ReadOnly = false;
object missing = System.Reflection.Missing.Value;
doc = appWord.Documents.Open(ref savePathWord, ref missing, ref ReadOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref Visible, ref missing, ref missing, ref missing, ref missing); try
{ foreach (var item in ftvs)
{//表单值写入word if (item.ControlType != "IMG" && item.ControlType != "WORD" && item.ControlType != "EXCEL" && item.ControlType != "TABLE")
{//文本 日期 等文字内容
if (item.Id == -1)
{//insert }
else
{//update } <span style="color:#ff0000;">WordAPI.BookMarkReplace(doc, item.BookMarkName, item.ControlType, item.Value);
</span> }
else
{//附件已经在上传的时候插入了附件表和内容表,现在要把内容表的record_id外键改过来(默认为NULL)
if (item.ControlType == "TABLE")
{//表格
<span style="color:#ff0000;">WordAPI.BookMarkReplace(doc, item.BookMarkName, item.ControlType, item.Value);</span>
}
else if (item.ControlType == "IMG")
{
//放在最后集中处理
}
}
} #region 单独处理图片
//*****单独处理图片 //if (formTemplateValue_Ids != null)
//{
// string[] ftvIds = formTemplateValue_Ids.Split(',');
// var imgs = dc.FormTemplateValues.Where(ee => ee.ControlType == "IMG" && ftvIds.Contains(ee.Id.ToString()));
// foreach (var item in imgs)
// {
// string imgPath =GetImgPath(item.Id);//Server.MapPath("~/")+item.PdfPath; //保存图片的时候也存在了服务器上
// WordAPI.BookMarkReplace(doc, item.BookMarkName, item.ControlType, imgPath);
// }
//} var imgs = dc.FormTemplateValues.Where(ee => ee.IsDeleted == false).Where(ee => ee.ControlType == "IMG" && ee.FormTemplateRecord_Id == recordId);
foreach (var item in imgs)
{
string imgPath = GetImgPath(item.Id);//Server.MapPath("~/")+item.PdfPath; //保存图片的时候也存在了服务器上
<span style="color:#ff0000;">WordAPI.BookMarkReplace(doc, item.BookMarkName, item.ControlType, imgPath);</span>
}
#endregion appWord.ScreenUpdating = true;
doc.Save();
doc.Close(ref missing, ref missing, ref missing);
//关闭wordApp组件对象
appWord.Quit(ref missing, ref missing, ref missing);
版权声明:本文为博主原创文章,未经博主允许不得转载。
c#调用word com组件 替换书签套打的更多相关文章
- C#关于word文档的书签替换操作
public void Get_Word(string gjbh) { try { DataSet ds = OperaterBase.GetDsBySql("select diffTabl ...
- 服务器端调用Word组件读取Word权限、未将对象引用到对象实例终极解决方案
最近因为业务需要,需要在服务器上调用Word组件,结果遇到各种问题,比如检索 COM 类工厂中 CLSID 为 {000209FF-0000-0000-C000-000000000046} 的组件失败 ...
- C# 操作Word书签(二)——插入图片、表格到书签;读取、替换书签
概要 书签的设置可以帮助我们快速的定位某段文字,使用起来很方便,也很节省时间.在前一篇文章“C# 如何添加/删除Word书签”中介绍了插入.删除书签的方法,本篇文章将对C# 操作Word书签的功能做进 ...
- 快速解决PHP调用Word组件DCOM权限的问题
1. 首先必须要在电脑上安装 Office 2. windows+r : 输入 dcomcnfg.exe 打开组件服务,然后双击 组件服务 ==> 双击 计算机 ==> 双击 我的电脑 = ...
- Java 操作Word书签(三):用文本、图片、表格替换书签
本篇文章将继续介绍通过Java来操作Word书签的方法,即替换Word中已有书签,包括用新的文本.图片.表格等替换原有书签处的内容. 使用工具:Free Spire.Doc for Java (免费版 ...
- 调用office Word Com 组件,提示权限不足处理
最近一直在处理一个项目,项目主要功能与Office-Word 有关,主要涉及到文本内容编辑与样式设置等相关内容.因项目依赖office 相关dll,需要兼容多种Office 版本(office 200 ...
- DocX开源WORD操作组件的学习系列三
DocX学习系列 DocX开源WORD操作组件的学习系列一 : http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_sharp_001_docx1.htm ...
- DocX开源WORD操作组件的学习系列一
DocX学习系列 DocX开源WORD操作组件的学习系列一 : http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_sharp_001_docx1.htm ...
- C# 调用word进程操作文档关闭进程
C# 调用word进程操作文档关闭进程 作者:Jesai 时间:2018-02-12 20:36:23 前言: office办公软件作为现在主流的一款办公软件,在我们的日常生活和日常工作里面几乎每天都 ...
随机推荐
- js去掉html标签和去掉字符串文本的所有的空格
去掉html标签的js <script> function delHtmlTag(str){ return str.replace(/<[^>]+>/g,"& ...
- 导出websphere内存镜像
1. 将脚本放致profiles\appservername\bin下 2. 查看一下soap host(在控制台port中能够看到) 3. 运行例如以下命令:./wsa ...
- 4kbps~15kbps语音编码器基础框架ACELP
- Android学习笔记----TimerTask中显示Toast的问题
今天想在TimerTask的run函数中调用Toast显示一下提示信息,却总是导致程序崩溃.可是try语句块却又无法捕获到异常,代码如下: ...... Timer timer = new Timer ...
- Retrofit
Retrofit 标签(空格分隔): 第三方&开源 Retrofit是一套RESTful架构的Android(Java)客户端实现,基于注解,提供JSON to POJO(Plain Ordi ...
- 使用U盘代替光盘来刻录ISO镜像文件的方法
原文链接: http://jingyan.baidu.com/article/d3b74d64aa4a6a1f77e60932.html 1.以管理员身份运行UltraISO,点击“文件”菜单下的“打 ...
- Swift 3 新特性和迁移详解
写在前面 Swift 3.0 正式版发布了差不多快一个月了,断断续续的把手上和 Swift 相关的迁移到了Swift 3.0.所以写点小总结. 背景 代码量(4万行) 首先,我是今年年初才开始入手 S ...
- jeos没有消亡,但看 debian 的 netinst .iso格式,那就是jeos的系统!
曾经ubuntu推出专供轻量硬件(如虚拟机)方式的just os格式的.iso [小巧.轻量.快速.干净] 但在 ubuntu 8.04后 再也没有继续 ...... 可惜 不曾想,ubuntu的老爸 ...
- JVM内存溢出及合理配置
Tomcat本身不能直接在计算机上运行,需要依赖于硬件基础之上的操作系统和一个Java虚拟机.Tomcat的内存溢出本质就是JVM内存溢出,所以在本文开始时,应该先对Java JVM有关内存方面的知识 ...
- CISA 信息系统审计知识点 [第一章. 信息系统审计过程 ]
对有志成为审计师或者IT管理者de朋友, 第一章. 信息系统审计过程 1. IS 审计和保障标准.指南.工具.职业道德规范 信息技术保证框架(ITAF,Information Technology A ...