搜档网
当前位置:搜档网 › C#操作word文档-C#实现Word中表格信息读取

C#操作word文档-C#实现Word中表格信息读取

C#操作word文档(一)
2009-03-12 16:40
1.c#操作word 在指定书签插入文字或者图片

using Word = Microsoft.Office.Interop.Word;

object Nothing = System.Reflection.Missing.Value;
object format = Word.WdSaveFormat.wdFormatDocument;
Word.Application wordApp = new Word.ApplicationClass();
//打开网页选择内容
object srcFileName = @"c:\new1.doc"; //里面有图片
Word.Document wordDoc2 = wordApp.Documents.Open(ref srcFileName, ref format, 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);
try
{
object bookmarkName = "jlr";
//Word.Range rng = wordDoc2.Bookmarks.get_Item(ref bookmarkName).Range;
//rng.Text = "newText";
//object range = rng;
//wordDoc2.Bookmarks.Add("jlr", ref range);
wordDoc2.Bookmarks.get_Item(ref bookmarkName).Select();
wordApp.Selection.InlineShapes.AddPicture("c:\\1.jpg", ref Nothing, ref Nothing, ref Nothing);
wordDoc2.Save();

}
catch { }
finally
{
//关闭网页wordDoc2
wordDoc2.Close(ref Nothing, ref Nothing, ref Nothing);
if (wordDoc2 != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc2);
wordDoc2 = null;
}
//关闭wordApp
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
if (wordApp != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
wordApp = null;
}
}
GC.Collect();

2.C#替换Word模版中的标签内容的例子

// open
object omissing = system.reflection.missing.value;
word.applicationclass wordapp= new microsoft.office.interop.word.applicationclass();
object readonly = false;
object template = templatepath;
word._document doc = wordapp.documents.open(ref template, ref omissing,ref readonly,
ref omissing, ref omissing, ref omissing, ref omissing, ref omissing, ref omissing,
ref omissing, ref omissing, ref omissing,ref omissing,ref omissing,ref omissing,ref omissing);
// modify
for (int i = 1; i <= doc.bookmarks.count; i++)
{
object j = i;
word.range wordrng = doc.bookmarks.get_item(ref j).range;
wordrng.text = "这是第" + i + "个标签,名称为" + doc.bookmarks.get_item(ref j).name;
}

// save
object savefilename = mappath(request.applicationpath + "/document") + "/" + guid.newguid().tostring() + ".doc";
doc.saveas(ref savefilename,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,
ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omissing,ref omi

ssing);
doc.close( ref omissing, ref omissing, ref omissing );
wordapp.quit( ref omissing, ref omissing, ref omissing );

3.用C#实现在Word文档中搜索文本

object filename=""; //要打开的文档路径
string strKey=""; //要搜索的文本
object MissingValue=Type.Missing;

Word.Application wp=new Word.ApplicationClass();
Word.Document wd=wp.Documents.Open(ref filename,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue);
int i=0,iCount=0;
Word.Find wfnd;

if (wd.Paragraphs!=null && wd.Paragraphs.Count>0)
{
iCount=wd.Paragraphs.Count;
for(i=1;i<=iCount;i++)
{
wfnd=wd.Paragraphs[i].Range.Find;
wfnd.ClearFormatting();
wfnd.Text=strKey;
if (wfnd.Execute(ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue))
{
MessageBox.Show("文档中包含指定的关键字!","搜索结果",MessageBoxButtons.OK);
break;
}
}
}


4.C#.net操作Word文档:以Office 2007为例

首先引入类库,Microsoft.Office.Interop.Word,然后进行编程。代码如下:

using System;
using System.Collections.Generic;
using https://www.sodocs.net/doc/9e12796704.html,ponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Word;

namespace WordTest
{
public partial class Form1 : Form
{
object strFileName;
Object Nothing;
Microsoft.Office.Interop.Word.Application myWordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
Document myWordDoc;
string strContent = "";

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
createWord();
//openWord();
}

private void createWord()
{
strFileName = System.Windows.Forms.Application.StartupPath + "test.doc";
if (System.IO.File.Exists((string)strFileName))
System.IO.File.Delete((string)strFileName);
Object Nothing = System.Reflection.Missing.Value;
myWordDoc = myWordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

#region 将数据库中读取得数据写入到word文件中

strContent = "你好\n\n\r";
https://www.sodocs.net/doc/9e12796704.html,st.Range.Text = strContent;

strContent = "这是测试程序";
https://www.sodocs.net/doc/9e12796704.html,st.Range.Text = strContent;


#endregion


//将WordDoc文档对象的内容保存为DOC文档
myWordDoc.SaveAs(ref strFileName, 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);
//关闭WordDoc文档对象
myWordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//关闭WordApp组件对象
myWordApp.Quit(ref Nothing, ref Nothing, ref Nothing);

this.richTextBox1.Text = strFileName + "\r\n" + "创建成功";

}
private void openWord()
{
fontDialog1.ShowDialog();
System.Drawing.Font font = fontDialog1.Font;
object filepath = "D:\\asp.docx";
object oMissing = System.Reflection.Missing.Value;
myWordDoc = myWordApp.Documents.Open(ref filepath, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
myWordDoc.Content.Font.Size = font.Size;
https://www.sodocs.net/doc/9e12796704.html, = https://www.sodocs.net/doc/9e12796704.html,;
myWordDoc.Save();
richTextBox1.Text = myWordDoc.Content.Text;


myWordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
myWordApp.Quit(ref oMissing, ref oMissing, ref oMissing);
}

}

5.C#动态生成Word文档并填充数据

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Word;

namespace CreateWordFile
{
class Program
{
static void Main(string[] args)
{
CreateWordFile("");
}

//下面的例子中包括C#对Word文档的创建、插入表格、设置样式等操作:

//(例子中代码有些涉及数据信息部分被省略,重要是介绍一些C#操作word文档的方法)

public static string CreateWordFile(string CheckedInfo)
{
string message = "";
try
{
Object Nothing = System.Reflection.Missing.Value;
Directory.CreateDirectory("C:/CNSI"); //创建文件所在目录
string name = "CNSI_" + "53asdf" + ".doc";
object filename = "C://CNSI//" + name; //文件保存路径
//创建Word文档
Word.Application WordApp = new Word.ApplicationClass();
Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

//添加页眉
WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[页眉内容]");
WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置


WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距

//移动焦点并换行
object count = 14;
object WdLine = Word.WdUnits.wdLine;//换一行;
WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点
WordApp.Selection.TypeParagraph();//插入段落

//文档中创建表格
Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 12, 3, ref Nothing, ref Nothing);
//设置表格样式
newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleThickThinLargeGap;
newTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
newTable.Columns[1].Width = 100f;
newTable.Columns[2].Width = 220f;
newTable.Columns[3].Width = 105f;

//填充表格内容
newTable.Cell(1, 1).Range.Text = "产品详细信息表";
newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体
//合并单元格
newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中

//填充表格内容
newTable.Cell(2, 1).Range.Text = "产品基本信息";
newTable.Cell(2, 1).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
//合并单元格
newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));
WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

//填充表格内容
newTable.Cell(3, 1).Range.Text = "品牌名称:";
newTable.Cell(3, 2).Range.Text = "BrandName";
//纵向合并单元格
newTable.Cell(3, 3).Select();//选中一行
object moveUnit = Word.WdUnits.wdLine;
object moveCount = 5;
object moveExtend = Word.WdMovementType.wdExtend;
WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend);
WordApp.Selection.Cells.Merge();
//插入图片
string FileName = "c:\\Winter.jpg";//图片所在路径
object LinkToFile = false;
object SaveWithDocument = true;
object Anchor = WordDoc.Application.Selection.Range;
WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 10

0f;//图片宽度
WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度
//将图片设置为四周环绕型
Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
s.WrapFormat.Type = Word.WdWrapType.wdWrapSquare;

newTable.Cell(12, 1).Range.Text = "产品特殊属性";
newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));
//在表格中增加行
WordDoc.Content.Tables[1].Rows.Add(ref Nothing);

https://www.sodocs.net/doc/9e12796704.html,st.Range.Text = "文档创建时间:" + DateTime.Now.ToString();//“落款”
https://www.sodocs.net/doc/9e12796704.html,st.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;

//文件保存
WordDoc.SaveAs(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);
WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
message = name + "文档生成成功,以保存到C:CNSI下";
}
catch
{
message = "文件导出异常!";

}
Console.WriteLine(message);
return message;
}


C#操作word文档(二) 收藏
1.C#操作Word完全功略

导入COM库:Microsoft word 11.0 Object Library.
引用里面就增加了:

创建新Word
object oMissing = System.Reflection.Missing.Value;
Word._Application oWord;
Word._Document oDoc;
oWord = new Word.Application();
oWord.Visible = true;
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
ref oMissing, ref oMissing);
打开文档:
object oMissing = System.Reflection.Missing.Value;
Word._Application oWord;
Word._Document oDoc;
oWord = new Word.Application();
oWord.Visible = true;
object fileName = @"E:\CCCXCXX\TestDoc.doc";
oDoc = oWord.Documents.Open(ref fileName,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
导入模板
object oMissing = System.Reflection.Missing.Value;
Word._Application oWord;
Word._Document oDoc;
oWord = new Word.Application();
oWord.Visible = true;
object fileName = @"E:\XXXCCX\Test.doc";
oDoc = oWord.Documents.Add(ref fileName,

ref oMissing,
ref oMissing, ref oMissing);

.添加新表
object oMissing = System.Reflection.Missing.Value;
Word._Application oWord;
Word._Document oDoc;
oWord = new Word.Application();
oWord.Visible = true;
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
ref oMissing, ref oMissing);

object start = 0;
object end = 0;
Word.Range tableLocation = oDoc.Range(ref start, ref end);
oDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing);
.表插入行
object oMissing = System.Reflection.Missing.Value;
Word._Application oWord;
Word._Document oDoc;
oWord = new Word.Application();
oWord.Visible = true;
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
ref oMissing, ref oMissing);

object start = 0;
object end = 0;
Word.Range tableLocation = oDoc.Range(ref start, ref end);
oDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing);

Word.Table newTable = oDoc.Tables[1];
object beforeRow = newTable.Rows[1];
newTable.Rows.Add(ref beforeRow);
.单元格合并
object oMissing = System.Reflection.Missing.Value;
Word._Application oWord;
Word._Document oDoc;
oWord = new Word.Application();
oWord.Visible = true;
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
ref oMissing, ref oMissing);

object start = 0;
object end = 0;
Word.Range tableLocation = oDoc.Range(ref start, ref end);
oDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing);

Word.Table newTable = oDoc.Tables[1];
object beforeRow = newTable.Rows[1];
newTable.Rows.Add(ref beforeRow);

Word.Cell cell = newTable.Cell(1, 1);
cell.Merge(newTable.Cell(1, 2));
.单元格分离
object oMissing = System.Reflection.Missing.Value;
Word._Application oWord;
Word._Document oDoc;
oWord = new Word.Application();
oWord.Visible = true;
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
ref oMissing, ref oMissing);

object start = 0;
object end = 0;
Word.Range tableLocation = oDoc.Range(ref start, ref end);
oDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing);

Word.Table newTable = oDoc.Tables[1];
object beforeRow = newTable.Rows[1];
newTable.Rows.Add(ref beforeRow);

Word.Cell

cell = newTable.Cell(1, 1);
cell.Merge(newTable.Cell(1, 2));

object Rownum = 2;
object Columnnum = 2;
cell.Split(ref Rownum, ref Columnnum);

通过段落控制插入
object oMissing = System.Reflection.Missing.Value;
object oEndOfDoc = "\\endofdoc"; /**//* \endofdoc is a predefined bookmark */

//Start Word and create a new document.
Word._Application oWord;
Word._Document oDoc;
oWord = new Word.Application();
oWord.Visible = true;
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
ref oMissing, ref oMissing);

//Insert a paragraph at the beginning of the document.
Word.Paragraph oPara1;
oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
oPara1.Range.Text = "Heading 1";
oPara1.Range.Font.Bold = 1;
oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph.
oPara1.Range.InsertParagraphAfter();
https://www.sodocs.net/doc/9e12796704.html,(C#)将数据导出到Word或Excel

命名空间:
using System.IO;
using System.Text;
将DataGrid的数据导出到Excel
string excelname="excel文件名";
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment;filename=" + excelname + ".xls");
dr1.Page.EnableViewState = false;
StringWriter sw = new StringWriter();
HtmlTextWriter tw = new HtmlTextWriter(sw);
dr1.RenderControl(tw);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();



将DataGrid的数据导出到Word
string excelname="word文件名";
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/ms-winword";
HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment;filename=" + excelname + ".doc");
dr1.Page.EnableViewState = false;
StringWriter sw = new StringWriter();
HtmlTextWriter tw = new HtmlTextWriter(sw);
dr1.RenderControl(tw);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
3.c# 如何将获得的数据.导入(写入) word里
导入com库:microsoft word 11.0 object library.

将数据绑定到datagrid然后从datagrid中将数据导出代码如下:

Response.Clear();
Response.Buffer= true;
Response.Charset="GB2312";
Response.AppendHeader("Content-Disposition","attachment;filename=fileOut(" + System.DateTime.Now.Year

+System.DateTime.Now.Month + System.DateTime.Now.Day+").doc");
Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
Response.ContentType = "application/ms-word";//设置输出文件类型为word文件。
this.EnableViewState = false;
System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN",true);
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
DataGrid1.Visible = true;
this.DataGrid1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
DataGrid1.Visible = false;
Response.End();

4.c#.net中通过关键字检索指定文件夹中的word文档

private static object nullobj = System.Reflection.Missing.Value;

//


/// search in a DOC file(查询DOC文件的内容)
///

///
/// 要搜索的文本
/// 是否区分大小写
///
public static bool SearchInDoc(string fileName,string searchForText,bool CaseSensitive)
{
bool Result = (searchForText.Length == 0);
object filename = fileName; //要打开的文档路径
object MissingValue=System.Reflection.Missing.Value;//Type.Missing;
object readOnly = false;
Microsoft.Office.Interop.Word.Application wp = null;
Microsoft.Office.Interop.Word.Document wd = null;

try
{
wp = new Microsoft.Office.Interop.Word.ApplicationClass();
wd = wp.Documents.Open(ref filename,ref MissingValue,
ref readOnly,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue);

int i=0,iCount=0;
Microsoft.Office.Interop.Word.Find wfnd;

if (wd.Paragraphs != null && wd.Paragraphs.Count>0)
{
iCount = wd.Paragraphs.Count;
for(i=1;i<=iCount;i++)
{
wfnd=wd.Paragraphs[i].Range.Find;
wfnd.ClearFormatting();
wfnd.MatchCase = CaseSensitive;
wfnd.Text = searchForText;

if (wfnd.Execute(ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref Missing

Value,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue))
{
Result = true;
break;
}
}
}
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
if(wd != null)
{
wd.Close(ref nullobj,ref nullobj,ref nullobj);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wd);
wd = null;
}

if(wp != null)
{
wp.Quit(ref nullobj,ref nullobj,ref nullobj);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wp);
wp = null;
}

GC.Collect();
}

return Result;
}

5.C#也能动态生成Word文档并填充数据(1)

要使用C#操作word,首先要添加引用:

1、添加引用->COM->Microsoft Word 11.0 Object Library

2、在.cs文件中添加using Word;
下面的例子中包括C#对Word文档的创建、插入表格、设置样式等操作:

(例子中代码有些涉及数据信息部分被省略,重要是介绍一些C#操作word文档的方法)

public string CreateWordFile(string CheckedInfo)
...{
string message = "";
try
...{
Object Nothing = System.Reflection.Missing.Value;
Directory.CreateDirectory("C:/CNSI"); //创建文件所在目录
string name = "CNSI_" + DateTime.Now.ToShortString()+".doc";
object filename = "C://CNSI//" + name; //文件保存路径
//创建Word文档
Word.Application WordApp = new Word.ApplicationClass();
Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

//添加页眉
WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[页眉内容]");
WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置

WordApp.Selection.ParagraphFormat.LineSpa

cing = 15f;//设置文档的行间距

//移动焦点并换行
object count = 14;
object WdLine = Word.WdUnits.wdLine;//换一行;
WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点
WordApp.Selection.TypeParagraph();//插入段落

6.C#也能动态生成Word文档并填充数据(2)

//文档中创建表格
Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 12, 3, ref Nothing, ref Nothing);
//设置表格样式
newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleThickThinLargeGap;
newTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
newTable.Columns[1].Width = 100f;
newTable.Columns[2].Width = 220f;
newTable.Columns[3].Width = 105f;

//填充表格内容
newTable.Cell(1, 1).Range.Text = "产品详细信息表";
newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体
//合并单元格
newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中

//填充表格内容
newTable.Cell(2, 1).Range.Text = "产品基本信息";
newTable.Cell(2, 1).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
//合并单元格
newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));
WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

//填充表格内容
newTable.Cell(3, 1).Range.Text = "品牌名称:";
newTable.Cell(3, 2).Range.Text = BrandName;
//纵向合并单元格
newTable.Cell(3, 3).Select();//选中一行
object moveUnit = Word.WdUnits.wdLine;
object moveCount = 5;
object moveExtend = Word.WdMovementType.wdExtend;
WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend);
WordApp.Selection.Cells.Merge();
//插入图片
string FileName = Picture;//图片所在路径
object LinkToFile = false;
object SaveWithDocument = true;
object Anchor = WordDoc.Application.Selection.Range;
WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, r

ef Anchor);
WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//图片宽度
WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度
//将图片设置为四周环绕型
Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
s.WrapFormat.Type = Word.WdWrapType.wdWrapSquare;

newTable.Cell(12, 1).Range.Text = "产品特殊属性";
newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));
//在表格中增加行
WordDoc.Content.Tables[1].Rows.Add(ref Nothing);

https://www.sodocs.net/doc/9e12796704.html,st.Range.Text = "文档创建时间:" + DateTime.Now.ToString();//“落款”
https://www.sodocs.net/doc/9e12796704.html,st.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;

//文件保存
WordDoc.SaveAs(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);
WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
message=name+"文档生成成功,以保存到C:CNSI下";
}
catch
{
message = "文件导出异常!";
}
return message;
}
7.C#操作Word、Excel

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using Word;
using Microsoft;

namespace ZHRAIMS.Logic
{
public class FillManager
{
private Dictionary 封面 = null;
private Dictionary 背脊 = null;

private object oMissing = System.Reflection.Missing.Value;

private object 封面模板 = System.Windows.Forms.Application.StartupPath + @"\Template\封面模板.doc";
private string 目录模板 = System.Windows.Forms.Application.StartupPath + @"\Template\目录模板.xls";
private object 脊背模板 = System.Windows.Forms.Application.StartupPath + @"\Template\脊背模板.doc";

private object 封面R = System.Windows.Forms.Application.StartupPath + @"\Temp\";
private string 目录R = System.Windows.Forms.Application.StartupPath + @"\Temp\";
private object 脊背R = System.Windows.Forms.Application.StartupPath + @"\Temp\";

public void Fill封面模板(DataTable result)
{
try
{
this.封面R += DateTime.Now.ToString("yyyyMMddHHmmssms") + ".doc";

this.封面 = new Dictionary

>();

this.封面.Add("dh", result.Rows[0]["档号"].ToString().Length > 0 ? result.Rows[0]["档号"].ToString() : "");
this.封面.Add("zrdw", result.Rows[0]["编制单位"].ToString().Length > 0 ? result.Rows[0]["编制单位"].ToString() : "");
this.封面.Add("jdrq", DateTime.Parse(result.Rows[0]["建档日期"].ToString()).ToShortDateString());
this.封面.Add("bgqx", result.Rows[0]["保管期限"].ToString().Length > 0 ? result.Rows[0]["保管期限"].ToString() : "");
this.封面.Add("mj", result.Rows[0]["秘密等级"].ToString());

string ajtm1 = null;
string ajtm2 = null;

if (result.Rows[0]["案卷题名"].ToString().Length > 20)
{
ajtm1 = result.Rows[0]["案卷题名"].ToString().Substring(0, 20);

this.封面.Add("ajtm1", ajtm1);

ajtm2 = result.Rows[0]["案卷题名"].ToString().Substring(20);

this.封面.Add("ajtm2", ajtm2);
}

else
{
ajtm1 = result.Rows[0]["案卷题名"].ToString().Length > 0 ? result.Rows[0]["案卷题名"].ToString() : "";

this.封面.Add("ajtm1", ajtm1);
}


Word.ApplicationClass objWordApp = new ApplicationClass();

objWordApp.Visible = false;

Word.Document objWordDoc = objWordApp.Documents.Open(ref this.封面模板,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing);

this.WordReplace(objWordApp, objWordDoc, oMissing, "dh", this.封面["dh"], false);
this.WordReplace(objWordApp, objWordDoc, oMissing, "zrdw", this.封面["zrdw"], false);
this.WordReplace(objWordApp, objWordDoc, oMissing, "jdrq", this.封面["jdrq"], false);
this.WordReplace(objWordApp, objWordDoc, oMissing, "bgqx", this.封面["bgqx"], false);
this.WordReplace(objWordApp, objWordDoc, oMissing, "mj", this.封面["mj"], false);

if (String.IsNullOrEmpty(ajtm2))
{
this.WordReplace(objWordApp, objWordDoc, oMissing, "ajtm1", this.封面["ajtm1"], false);
this.WordReplace(objWordApp, objWordDoc, oMissing, "ajtm2", "", false);
}

else
{
this.WordReplace(objWordApp, objWordDoc, oMissing, "ajtm1", this.封面["ajtm1"], false);
this.WordReplace(objWordApp, objWordDoc, oMissing, "ajtm2", this.封面["ajtm2"], false);
}

objWordDoc.SaveAs(ref 封面R, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing);

objWordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
objWordApp.Quit(ref oMissing, ref oMissing, ref oMissing);

System.Diagnostics.Process.Start(this.封面R.ToString());
}

catch (Exception objException)
{
throw objException;
}
}

public void Fill目录模板(DataTable result)
{
try
{
this.目录R += DateTime.Now.ToString("yyyyMMddHHmmssms") + ".xls";

Excel.Application objExcelApp = new Excel.Application();

objExcelApp.Visible = false;

Excel.Workbook objExcelWB = objExcelApp.Workbooks.Open(目录模板, oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing,
oMissing, oMissing);

Excel.Worksheet objExcelWS = objExcelWB.Sheets[1] as Excel.Worksheet;

for (int row = 0; row < result.Rows.Count; row++)
{
objExcelWS.Cells[row + 4, 1] = result.Rows[row]["文件顺序号"].ToString().Length > 0 ? result.Rows[row]["文件顺序号"].ToString() : "";
objExcelWS.Cells[row + 4, 2] = result.Rows[row]["文件编号"].ToString().Length > 0 ? result.Rows[row]["文件编号"].ToString() : "";
objExcelWS.Cells[row + 4, 3] = result.Rows[row]["责任人"].ToString().Length > 0 ? result.Rows[row]["责任人"].ToString() : "";
objExcelWS.Cells[row + 4, 4] = result.Rows[row]["文件题名"].ToString().Length > 0 ? result.Rows[row]["文件题名"].ToString() : "";
objExcelWS.Cells[row + 4, 5] = DateTime.Parse(result.Rows[row]["日期"].ToString()).ToShortDateString();
objExcelWS.Ce

lls[row + 4, 6] = result.Rows[row]["页号"].ToString().Length > 0 ? result.Rows[row]["页号"].ToString() : "";
objExcelWS.Cells[row + 4, 7] = result.Rows[row]["附注"].ToString().Length > 0 ? result.Rows[row]["附注"].ToString() : "";
}

objExcelWB.SaveAs(目录R, oMissing, oMissing, oMissing,
oMissing, oMissing, Excel.XlSaveAsAccessMode.xlNoChange,
oMissing, oMissing, oMissing, oMissing, oMissing);

objExcelWB.Close(oMissing, oMissing, oMissing);
objExcelApp.Quit();

System.Diagnostics.Process.Start(this.目录R);
}

catch (Exception objException)
{
throw objException;
}
}

public void Fill脊背模板(DataTable result)
{
try
{
this.脊背R += DateTime.Now.ToString("yyyyMMddHHmmssms") + ".doc";

this.背脊 = new Dictionary();

this.背脊.Add("dh", result.Rows[0]["档号"].ToString());
this.背脊.Add("ajtm", result.Rows[0]["案卷题名"].ToString().Length > 0 ? result.Rows[0]["案卷题名"].ToString() : "");

Word.ApplicationClass objWordApp = new ApplicationClass();

objWordApp.Visible = false;

Word.Document objWordDoc = objWordApp.Documents.Open(ref this.脊背模板,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing);

this.WordReplace(objWordApp, objWordDoc, oMissing, "dh", this.背脊["dh"], false);
this.WordReplace(objWordApp, objWordDoc, oMissing, "ajtm", this.背脊["ajtm"], false);

objWordDoc.SaveAs(ref 脊背R, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing);

objWordDoc.Close(ref oMissing, ref oMissing, ref oMissing);
objWordApp.Quit(ref oMissing, ref oMissing, ref oMissing);


System.Diagnostics.Process.Start(this.脊背R.ToString());
}

catch (Exception objException)
{
throw objException;
}
}

private void CheckFile(string filePath)
{
try
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}

catch (Exception objException)
{
throw objException;
}
}

private void WordReplace(Word.ApplicationClass objWordApp, Word.Document objWordDoc, object oMissing, string findText, string replaceText, bool matchCase)
{
object FindText = findText;
object MatchCase = matchCase;
object ReplaceWith = replaceText;
object Replace = Word.WdReplace.wdReplaceAll;

objWordApp.Selection.Find.Execute(ref FindText, ref MatchCase, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref ReplaceWith, ref Replace, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
}
}
}


本文来自CSDN博客,转载请标明出处:https://www.sodocs.net/doc/9e12796704.html,/liusen5555/archive/2008/01/17/2048799.aspx
1. C#调用word打印信封

public static bool PrintEnvelope(string from, string to)
{
//
//string temp = Properties.Resources.EnvelopeTemplate.Replace("?ReturnAddress?", from).Replace("?ReceiverAddress?", to);
string temp = Properties.Resources.EnvelopeTemplate;
string TempPath = System.Windows.Forms.Application.ExecutablePath.ToString().Trim().Substring(0, System.Windows.Forms.Application.ExecutablePath.ToString().Trim().LastIndexOf(@"\\") + 1) + "\\\\Envelope.xml";

if (File.Exists(TempPath)) File.Delete(TempPath);
System.IO.FileStream fs = new System.IO.FileStream(TempPath, System.IO.FileMode.CreateNew);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs,Encoding.UTF8);

sw.Write(temp);
sw.Close();

object fileName = TempPath;
object readOnly = false;
object isVisible = true;
object missing = System.Reflection.Missing.Value;
object range = Microsoft.Office.Interop.Word.WdPrintOutRange.wdPrintCurrentPage;
Microsoft.Office.Interop.Word.Application wordApp;
//Document d = new DocumentClass();
try
...{
object o = Marshal.GetActiveObject("Word.Application");
wordApp = o as Microsoft.Office.Interop.Word.Application;
}
catch
...{
wordApp = new ApplicationClass();
}

Document d = wordApp.Documents.Open(ref fileName, 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);
//replace
d.Envelope.ReturnAddress.Text = from;
d.Envelope.Address.Text = to;

//object findText="?ReturnAddress?";
//object replac

eWidth=from;
//wordApp.Selection.Find.Execute(ref findText, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWidth, ref missing, ref missing, ref missing, ref missing, ref missing);

//object findText2 = "?ReceiverAddress?";
//object replaceWidth2 = to;


//wordApp.Selection.Find.Execute(ref findText2, ref missing, ref missing, ref missing, ref missing, ref missing, ref readOnly, ref missing, ref missing, ref replaceWidth2, ref missing, ref missing, ref missing, ref missing, ref missing);

//
d.Activate();
d.PrintOut(ref missing, ref missing, ref range, 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);
d.Close(ref readOnly, ref missing, ref missing);
File.Delete(TempPath);
return true;

}

2.C#实现Word中表格信息读取

很多时候,会有很多信息存放在Word文档中。而我们需要把这些信息提取出来,另做它用。而Word的格式是ms的机密,不知道有没有NB人可以对其做字符流的分析,反正我是没这能力也没这打算。所以就只能用ms提供的组件来进行编程。但ms没有提供托管的类库,而是提供了对com组件的PIA转换。具体添加,使用和相关知识,可以参见kaneboy's blog中的https://www.sodocs.net/doc/9e12796704.html,/kaneboy/articles/67688.aspx。高手的讲解,很是清晰。
而我想做的是对word文档中的表信息进行提取。网上很难找到相关的代码(打开一个已有文档,对其内容进行分析),但我觉得这种工作是很有意义的。写了一段小的Demo,如下:

object oFileName = @"C:\Documents and Settings\liush\My Documents\TestDoc.doc";
object oReadOnly = true;
object oMissing = System.Reflection.Missing.Value;

Word._Application oWord;
Word._Document oDoc;
oWord = new Word.Application();
oWord.Visible = true;//只是为了方便观察
oDoc = oWord.Documents.Open(ref oFileName, ref oMissing, ref oReadOnly, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

//MessageBox.Show(oDoc.Tables.Count.ToString());
for (int tablePos = 1; tablePos <= oDoc.Tables.Count; tablePos++)
{
Word.Table nowTable = oDoc.Tables[tablePos];
string tableMessage = string.Format("第{0}/{1}个表:\n", tablePos, oDoc.Tables.Count);

for (int rowPos = 1; rowPos <= nowTable.Rows.Count; rowPos++)
{
for (int columPos = 1; columPos <= nowTable.Columns.Count; columPos++)
{
tableMessage += nowTable.Cell(rowPos, columPos).Range.Text;
tableMessage = tableMessage.Remove(tableMessage.Length - 2, 2);//remove \r\a
tableMessage += "\t";
}

tableMessage += "\n";
}

MessageBox.Show(tableMessage);
}

如果看过了上面kaneboy的文章(这是一个系列的之一),再

看这段代码应该不会很难理解。打开一个已有文档,然后遍历其中的所有的表。这里只是简单的将信息显示出来,具体实践上可以对这些信息进行分析。做完这些后,终于找到了一些官方的支持文档,地址如下:
https://www.sodocs.net/doc/9e12796704.html,/zh-CN/library/y1xatbkd.aspx
其中的word任务有对word各种操作的简单代码事例,用vb和c#写的。看完之后,我想每个人都会明白vb对com的支持比c#不是简单明了一点两点。(可以看下这个https://www.sodocs.net/doc/9e12796704.html,/kaneboy/archive/2005/08/03/61489.aspx)同样的代码,用vb实现打开word文档的操作,代码如下:

Dim fileName As String = "C:\Documents and Settings\liush\My Documents\TestDoc.doc"
Dim isReadOnly As Boolean = True

Dim wordApplication As Word.Application = New Word.Application()
Dim wordDocument As Word.Document
wordApplication.Visible = True
wordDocument = wordApplication.Documents.Open(fileName, , isReadOnly)

所以,下次我要做COM操作的时候,我还会回归我可爱的VB的。但是,用了太久的C#毛病越来越多了,动不动就习惯性加括号,加分号。。。

3.C#读取Word中的表格

其实,MicroSoft提供了很多类和借口供程序员们使用。最近一个项目中,需要对Word中的表格进行操作:因为老板要求将内部控管系统做成Web版的,以便更好地跟台湾沟通,但是网络很慢,所以在网页上输入一些数据就很讨厌,SO,需要制订一个规格的文文件,比如Word,填写好文档后上传到FTP上,我们再用一支程序扫描这些文文件,自动添加到数据库中。。。一开始的时候,觉得好没方向啊,到网上搜了一下,发现原来有很多前辈早在N年前就已经开始这方面的工作了。

1.开始之前,请先加入参考MicroSoft Word 11.0 Object Library:
"参考"右键 ------> 加入参考 --------> "加入参考"对话框选择 "COM" 页 --------> 在列表中找到MicroSoft Word 11.0 Object Library双击选取后确定,会发现参考中多出来两项:VBIDE和Word。/p>
2. 请添加using:
using Word;
3.读取Word中的表格
private void btnIn_Click(object sender, System.EventArgs e)
{
try
{
object fileName = "E:\\BB.doc";
object readOnly = false;
object isVisible = true;
object missing = System.Reflection.Missing.Value;
Word.ApplicationClass oWordApp = new Word.ApplicationClass(); //开启应用程序WINWORD.EXE
//打开要操作的Word文檔
Word.Document oWordDoc = oWordApp.Documents.Open(ref fileName, ref missing,ref readOnly,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref isVisible,ref missing,ref missing,ref missing,ref missing);
oWordDoc.Activate();
//int i = oWordDoc.Tables.Count; //文文件中表格的个数
Word.

Table nowTable = oWordDoc.Tables[1]; //文文件中第一个表格
//读取表格内容
string strProjName = nowTable.Cell(2, 2).Range.Text.ToString();
string strAssignEmployeeName = nowTable.Cell(3, 2).Range.Text.ToString();
string strAssignDate = nowTable.Cell(3, 4).Range.Text.ToString();
string strPreFinishDate = nowTable.Cell(4, 2).Range.Text.ToString();
string strChargeEmployeeName = nowTable.Cell(5, 2).Range.Text.ToString();
string strType = nowTable.Cell(8, 1).Range.Text.ToString();
string strDesc = nowTable.Cell(8, 2).Range.Text.ToString();
string strRem = nowTable.Cell(8, 3).Range.Text.ToString();
//填充DataSet
/**********************************************************************************************************
//上面已经将表格中的内容读出来了,当然可以将它们填到一个DataSet中了。。略过。。*_*
**********************************************************************************************************/
4.c# 生成 word
转载自 微软MSDN

private void button1_Click(object sender, System.EventArgs e)
{
object oMissing = System.Reflection.Missing.Value;
object oEndOfDoc = "\\endofdoc";

/* \endofdoc是预定义的bookmark */

//创建一个document.
Word._Application oWord;
Word._Document oDoc;
oWord = new Word.Application();
oWord.Visible = true;
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
ref oMissing, ref oMissing);

//在document的开始部分添加一个paragraph.
Word.Paragraph oPara1;
oPara1 = oDoc.Content.Paragraphs.Add(ref oMissing);
oPara1.Range.Text = "Heading 1";
oPara1.Range.Font.Bold = 1;
oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph.
oPara1.Range.InsertParagraphAfter();

//在当前document的最后添加一个paragraph

Word.Paragraph oPara2;
object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara2 = oDoc.Content.Paragraphs.Add(ref oRng);
oPara2.Range.Text = "Heading 2";
oPara2.Format.SpaceAfter = 6;
oPara2.Range.InsertParagraphAfter();

//接着添加一个paragraph
Word.Paragraph oPara3;
oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara3 = oDoc.Content.Paragraphs.Add(ref oRng);
oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:";
oPara3.Range.Font.Bold = 0;
oPara3.Format.SpaceAfter = 24;
oPara3.Range.InsertParagraphAfter();


//添加一个3行5列的表格,填充数据,并且设定第一行的样式

Word.Table oTable;
Word.Range wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oTable = oDoc.Tables.Add(wrdRng, 3, 5, ref oMissing, ref oMissing);
oTable.Range.ParagraphFormat.SpaceAfter = 6;
int r, c;
string strText;
for(r = 1; r <= 3; r++)
for(c = 1; c <= 5; c++)
{
strText = "r" + r + "c" + c;
oTable.Cell(r, c).Range.Text = strText;
}
oTable.Rows[1].Range.Font.Bold = 1;
oTable.Rows[1].Range.Font.Italic = 1;

//接着添加一些文字

Word.Parag

raph oPara4;
oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oPara4 = oDoc.Content.Paragraphs.Add(ref oRng);
oPara4.Range.InsertParagraphBefore();
oPara4.Range.Text = "And here's another table:";
oPara4.Format.SpaceAfter = 24;
oPara4.Range.InsertParagraphAfter();


//添加一个5行2列的表,填充数据并且改变列宽
wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oTable = oDoc.Tables.Add(wrdRng, 5, 2, ref oMissing, ref oMissing);
oTable.Range.ParagraphFormat.SpaceAfter = 6;
for(r = 1; r <= 5; r++)
for(c = 1; c <= 2; c++)
{
strText = "r" + r + "c" + c;
oTable.Cell(r, c).Range.Text = strText;
}
oTable.Columns[1].Width = oWord.InchesToPoints(2); //Change width of columns 1 & 2
oTable.Columns[2].Width = oWord.InchesToPoints(3);

//Keep inserting text. When you get to 7 inches from top of the
//document, insert a hard page break.
object oPos;
double dPos = oWord.InchesToPoints(7);
oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range.InsertParagraphAfter();
do
{
wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
wrdRng.ParagraphFormat.SpaceAfter = 6;
wrdRng.InsertAfter("A line of text");
wrdRng.InsertParagraphAfter();
oPos = wrdRng.get_Information
(Word.WdInformation.wdVerticalPositionRelativeToPage);
}
while(dPos >= Convert.ToDouble(oPos));
object oCollapseEnd = Word.WdCollapseDirection.wdCollapseEnd;
object oPageBreak = Word.WdBreakType.wdPageBreak;
wrdRng.Collapse(ref oCollapseEnd);
wrdRng.InsertBreak(ref oPageBreak);
wrdRng.Collapse(ref oCollapseEnd);
wrdRng.InsertAfter("We're now on page 2. Here's my chart:");
wrdRng.InsertParagraphAfter();

//添加一个chart

Word.InlineShape oShape;
object oClassType = "MSGraph.Chart.8";
wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
oShape = wrdRng.InlineShapes.AddOLEObject(ref oClassType, ref oMissing,
ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing);

//Demonstrate use of late bound oChart and oChartApp objects to
//manipulate the chart object with MSGraph.
object oChart;
object oChartApp;
oChart = oShape.OLEFormat.Object;
oChartApp = oChart.GetType().InvokeMember("Application",
BindingFlags.GetProperty, null, oChart, null);

//Change the chart type to Line.
object[] Parameters = new Object[1];
Parameters[0] = 4; //xlLine = 4
oChart.GetType().InvokeMember("ChartType", BindingFlags.SetProperty,
null, oChart, Parameters);

//Update the chart image and quit MSGraph.
oChartApp.GetType().InvokeMember("Update",
BindingFlags.InvokeMethod, null, oChartApp, null);
oChartApp.GetType().InvokeMember("Quit",
BindingFlags.InvokeMethod, null, oChartApp, null);
//... If desired, you can proceed from here using the Microsoft Graph
//Object model on the oChart and oChartApp objects to make additional
//changes to the chart.

//Set the width of the chart.
oShape.Width = oWord.InchesToPoints(6.25f);
oShape.Height = oWord.InchesToPoints(3.57f);

//Add text aft

er the chart.
wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;
wrdRng.InsertParagraphAfter();
wrdRng.InsertAfter("THE END.");

//Close this form.
this.Close();
}


使用模板
如果您要使用自动化功能创建的文档都是通用格式,则利用基于预设格式的模板的新文档来开始创建过程会更加容易。与从头创建文档相比,将某个模板与 Word 自动化客户端配合使用有两大优点: ? 您可以对整个文档中的对象的格式设置和布局施加更多控制。
? 可以使用较少的代码创建文档。
通过使用模板,可以精确地调整表格、段落和其他对象在文档中的布局,并可为这些对象添加格式设置。通过使用自动化功能,可以基于包含下面这样的代码的模板创建新文档: 在模板中,可以定义书签,这样,自动化客户端就可以在文档的特定位置加入可变文本,如下所示: 使用模板的另一个优点在于,您可以创建和存储希望在运行时应用的格式样式,如下所示: - 或者 -


object oTemplate = "c:\\MyTemplate.dot";
oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing,
ref oMissing, ref oMissing);
object oBookMark = "MyBookmark";
oDoc.Bookmarks.Item(ref oBookMark).Range.Text = "Some Text Here";
object oStyleName = "MyStyle";
oDoc.Bookmarks.Item(ref oBookMark).Range.set_Style(ref oStyleName);
object oStyleName = "MyStyle";
oWord.Selection.set_Style(ref oStyleName);
5.总结下C#将WORD转PDF首先安装WORD和WPS(2005个人版就OK了)操作WPS配置说明using WPS;1.运行Dcomcnfg.exe 2.组件服务――计算机――我的电脑――DCOM配置――找到WPS文档 3.点击属性 4.选择“安全性” 5.选定“使用自定义访问权限”和“使用自定义启动权限” 6.分别编辑权限,添加Everyone(ASPNET,VS Developers,Debugger User)7.选择“身份标识”,在选定“交互式用户” 即可 9.在Web.config里加 转换为WPS打开,转化为PDF WPS.Application WPSApp; object MissingValue=Type.Missing; WPSApp = new WPS.ApplicationClass(); WPSApp.Visible = false; object Unknown =Type.Missing; String upPath; upPath=Server.MapPath("tempup\\" +Request.Cookies["code"].Value +"\\"); if(!Directory.Exists(upPath)) Directory.CreateDirectory(upPath); object wpsurl = upPath +upfile.PostedFile.FileName.Substring(https://www.sodocs.net/doc/9e12796704.html,stIndexOf("\\"),upfile.PostedFile.FileName.Length - https://www.sodocs.net/doc/9e12796704.html,stIndexOf("\\")); //string wpsurl=Source2.ToString(); object wpsurls=wpsurl+".pdf"; WPS.Document WPSDocument = WPSApp.Documents.Add(ref wpsurl, false, 0, true); WPSDocument.ExportPdf(wpsurl+".pdf","",""); db.dbconn conn = new dbconn(); string sql; sql=@"update maindata set pdf_furl='"+wpsurls+"'"; conn.doexecsql(sql); object save = false; WPSApp.Quit(ref save,ref

相关主题