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 omissing);
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 System.ComponentModel;
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";
myWordDoc.Paragraphs.Last.Range.Text = strContent;
strContent = "这是测试程序";
myWordDoc.Paragraphs.Last.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;
myWordDoc.Content.Font.Name = font.Name;
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 = 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);
WordDoc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString();//“落款”
WordDoc.Paragraphs.Last.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;
}
6.C# 将Word,Excel转换成Html
Word -〉Html
Microsoft.Office.Interop.Word.ApplicationClass appclass = new Microsoft.Office.Interop.Word.ApplicationClass();//实例化一个Word
Type wordtype = appclass.GetType();
Microsoft.Office.Interop.Word.Documents docs = appclass.Documents;//获取Document
Type docstype = docs.GetType();
object filename = ;//n.FullPath为Word文件的路径
Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docstype.InvokeMember("Open",System.Reflection.BindingFlags.InvokeMethod,null,docs,new object[]{filename,true,true});//打开文件
Type doctype = doc.GetType();
object savefilename = Application.StartupPath+@"/ccyt_chm/inform/"+n.FullPath.Split('.').GetValue(0)+".html";
doctype.InvokeMember("SaveAs",System.Reflection.BindingFlags.InvokeMethod,null,doc,new object[]{savefilename,Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML});//另存为Html格式
wordtype.InvokeMember("Quit",System.Reflection.BindingFlags.InvokeMethod,null,appclass,null);//退出
Thread.Sleep(3000);//为了使退出完全,这里阻塞3秒
StreamReader objreader = new StreamReader(savefilename.ToString(),System.Text.Encoding.GetEncoding("GB2312")); //以下内容是为了在Html中加入对本身Word文件的下载
FileStream fs = new FileStream(savefilename.ToString().Split('.').GetValue(0).ToString()+"$.html",FileMode.Create);
streamHtmlHelp = new System.IO.StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
streamHtmlHelp.WriteLine("<a href=/""+n.Text+"/">源文件下载</a><br>");
do
{
str = objreader.ReadLine();
streamHtmlHelp.WriteLine(str);
}
while (str != "</html>");
streamHtmlHelp.Close();
objreader.Close();
File.Delete(savefilename.ToString());
File.Move(savefilename.ToString().Split('.').GetValue(0).ToString()+"$.html",savefilename.ToString());Application.StartupPath+@"/ccyt_chm/inform/"+n.FullPath
Excel -〉Html(这个与Word不同,因为Excel为很多层,又并列很多层,必须都清空才能销毁实例,但实际中我发现并不是每次都能销毁,所以网上求解多次没有结果,只能杀没进程,为了保证只杀灭最近的进程,我用时间进行判断)
Microsoft.Office.Interop.Excel.Application repExcel = new Microsoft.Office.Interop.Excel.Application ();//实例化Excel
Microsoft.Office.Interop.Excel.Workbook workbook = null;
Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
workbook = repExcel.Application.Workbooks.Open();//打开文件,n.FullPath是文件路径
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
object htmlFile = Application.StartupPath+@"/ccyt_chm/inform/"+n.FullPath.Split('.').GetValue(0)+".html";
object ofmt = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
workbook.SaveAs(htmlFile,ofmt,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);//进行另存为操作
object osave = false;
workbook.Close(osave,Type.Missing,Type.Missing);//逐步关闭所有使用的对象
repExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
worksheet = null;
GC.Collect();//垃圾回收
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook=null;
GC.Collect();
System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel.Application.Workbooks);
GC.Collect();
System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel);
repExcel = null;
GC.Collect();
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("EXCEL");//依据时间杀灭进程
foreach ( System.Diagnostics.Process p in process)
{
if (DateTime.Now.Second - p.StartTime.Second > 0 && DateTime.Now.Second - p.StartTime.Second < 5)
{
p.Kill();
}
}
Thread.Sleep(3000);//保证完全关闭
StreamReader objreader = new StreamReader(htmlFile.ToString().Split('.').GetValue(0)+".files//sheet001.html",System.Text.Encoding.GetEncoding("GB2312"));//以下内容是在Html的第一个框架中添加下载原Excel的超链接
FileStream fs = new FileStream(htmlFile.ToString().Split('.').GetValue(0)+".files//sheet001$.html",FileMode.Create);
streamHtmlHelp = new System.IO.StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
streamHtmlHelp.WriteLine("<a href=/""+"../"+n.Text+"/">源文件下载</a><br>");
do
{
str = objreader.ReadLine();
streamHtmlHelp.WriteLine(str);
}
while (str != "</html>");
streamHtmlHelp.Close();
objreader.Close();
File.Delete(htmlFile.ToString().Split('.').GetValue(0)+".files//sheet001.html");
File.Move(htmlFile.ToString().Split('.').GetValue(0)+".files//sheet001$.html",htmlFile.ToString().Split('.').GetValue(0)+".files//sheet001.html");Application.StartupPath+@"/ccyt_chm/inform/"+n.FullPath,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing
7.c# 实现Word联接Excel的MailMerge功能
目标:使用word的MailMerge功能,数据源是Excel中的数据。这些资料在网上很少,只能自己慢慢测试了。
关于Word的MailMerge功能:
word提供邮件的模板,可以选择各种数据源,比如数据库,excel等,然后群发(或打印、另存文件)邮件。
为了实现这个功能,我的程序要能做的是
1:打开word文件对象
2:设置MailMerge数据源:指定Excel,指定查询语句,指定联接的列s
3:关闭保存
关于引用:
using Word = Microsoft.Office.Interop.Word;
using System.Reflection;
using System.Diagnostics;
using System.IO;
关于变量:word的com对象需要传入的参数定义
Word.Application WordApp = new Microsoft.Office.Interop.Word.Application();
object missing = System.Reflection.Missing.Value;
object falseValue = false;
object trueValue = true;
关于处理
需要注重的是
1:打开word的方式
2:query的写法。类似于sql一般,比较好玩。
3:设置列,。设置之后,在word中可以看见这些列。
4:关闭word之后,还得再copy一次excel。直接生成之后的excel文件size暴涨,文件还打不开,所以覆盖一遍了之。原因不详。
private void button1_Click(object sender, EventArgs e)
{
object fileName = CopyTemplateDoc();//copy doc in
Word.Document doc = WordApp.Documents.Open(ref fileName, ref missing, ref falseValue, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref trueValue, ref missing, ref missing, ref missing);
object linkTo = CopyExcelData();//copy excel data
object query = "SELECT * FROM `Sheet1$`";//data from sheet1
object header = "Name,Category,Address,Content";//filed list
try
{
doc.MailMerge.CreateDataSource(ref linkTo, ref missing, ref missing, ref header, ref falseValue, ref query, ref missing, ref missing, ref trueValue);
doc.MailMerge.Fields.Add(WordApp.Selection.Range, "Name");//add one filed to test
MessageBox.Show("success");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
doc.Save();//save word
CloseApp();//close word app
CopyExcelData();//copy data again,*******************
}
}
关于关闭word对象
public void CloseApp()
{
WordApp.Documents.Close(ref trueValue, ref missing, ref missing);
WordApp.Quit(ref trueValue, ref missing, ref missing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(WordApp);
GC.Collect();
//this.KillExcelProcess();
}
还有两个工具函数不再赘述,用来copy文件并且返回文件名private string CopyExcelData();和private string CopyTemplateDoc()。
8.c#操作word表格
对word中表格的操作,以下是部分代码,关于操作不规则表格的.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices ;
using System.Threading;
public void MakeMyTable(DataTable DT,string strFilePath)
{
string strEnd = this.txtEnd.Text.Trim().ToString();
string strStart = this.txtStart.Text.Trim().ToString();
//生成文档分页中的起始和终止页
string strSign = "("+strStart + "-" + strEnd + ")";
//杀掉所有word进程以保证速度
//KillWordProcess();
object Nothing = System.Reflection.Missing.Value;
object missing = System.Reflection.Missing.Value;
object filename= strFilePath;
Word.Application wordApp=new Word.ApplicationClass();
Word.Document wordDoc=wordApp.Documents.Add(ref Nothing,ref Nothing,ref Nothing,ref Nothing);
try
{
//生成过程中屏蔽返回按扭,不允许中途停止
Button2.Enabled = false;
#region 生成文档
//设置文档宽度
wordApp.Selection.PageSetup.LeftMargin = wordApp.CentimetersToPoints(float.Parse("2"));
wordApp.ActiveWindow.ActivePane.HorizontalPercentScrolled = 11 ;
wordApp.Selection.PageSetup.RightMargin = wordApp.CentimetersToPoints(float.Parse("2"));
Object start = Type.Missing;
Object end = Type.Missing;
Object unit = Type.Missing;
Object count = Type.Missing;
wordDoc.Range(ref start, ref end).Delete(ref unit, ref count);
object rng = Type.Missing;
string strInfo = this.txtNameCh.Text.ToString()+"明细表"+strSign+"/r/n";
start = 0;
end = 0;
wordDoc.Range(ref start, ref end).InsertBefore(strInfo);
wordDoc.Range(ref start, ref end).Font.Name = "Verdana";
wordDoc.Range(ref start, ref end).Font.Size = 20;
wordDoc.Range(ref start, ref end).ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
start = 8;
end = strInfo.Length;
wordDoc.Range(ref start, ref end).InsertParagraphAfter();//插入回车
if(DT.Rows.Count>0)
{
//存在数据项
//添加一个表格
object missingValue = Type.Missing;
object location = strInfo.Length; //注:若location超过已有字符的长度将会出错。一定要比"明细表"串多一个字符
Word.Range rng2 = wordDoc.Range(ref location, ref location);
wordDoc.Tables.Add(rng2, 13, 6, ref missingValue, ref missingValue);
wordDoc.Tables.Item(1).Rows.HeightRule = Word.WdRowHeightRule.wdRowHeightAtLeast;
wordDoc.Tables.Item(1).Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8"));
wordDoc.Tables.Item(1).Range.Font.Size = 10;
wordDoc.Tables.Item(1).Range.Font.Name = "宋体";
wordDoc.Tables.Item(1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
wordDoc.Tables.Item(1).Range.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
//设置表格样式
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderLeft).Color = Word.WdColor.wdColorAutomatic;
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderTop).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderTop).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderTop).Color = Word.WdColor.wdColorAutomatic;
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderBottom).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderBottom).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderBottom).Color = Word.WdColor.wdColorAutomatic;
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderHorizontal).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderHorizontal).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderHorizontal).Color = Word.WdColor.wdColorAutomatic;
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderVertical).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderVertical).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderVertical).Color = Word.WdColor.wdColorAutomatic;
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderRight).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderRight).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
wordDoc.Tables.Item(1).Borders.Item(Word.WdBorderType.wdBorderRight).Color = Word.WdColor.wdColorAutomatic;
// wordDoc.Tables.Item(k).Borders.Item(Word.WdBorderType.wdBorderDiagonalDown).LineStyle = Word.WdLineStyle.wdLineStyleSingle;
// wordDoc.Tables.Item(k).Borders.Item(Word.WdBorderType.wdBorderDiagonalDown).LineWidth = Word.WdLineWidth.wdLineWidth050pt;
// wordDoc.Tables.Item(k).Borders.Item(Word.WdBorderType.wdBorderDiagonalDown).Color = Word.WdColor.wdColorAutomatic;
//第一行显示
wordDoc.Tables.Item(1).Cell(1,2).Merge(wordDoc.Tables.Item(1).Cell(1,3));
wordDoc.Tables.Item(1).Cell(1,4).Merge(wordDoc.Tables.Item(1).Cell(1,5));
//第二行显示
wordDoc.Tables.Item(1).Cell(2,5).Merge(wordDoc.Tables.Item(1).Cell(2,6));
wordDoc.Tables.Item(1).Cell(1,4).Merge(wordDoc.Tables.Item(1).Cell(2,5));
#region 插入数据行
wordDoc.Tables.Item(1).Cell(1, 1).Range.Text = "cell11";
//wordDoc.Tables.Item(k).Cell(1, 2).Range.Text = DT.Rows[i]["cell11"].ToString();
////******************
wordDoc.Tables.Item(1).Cell(1, 3).Range.Text = "cell13";
//wordDoc.Tables.Item(k).Cell(1, 4).Range.Text = DT.Rows[i]["cell13"].ToString();
////******************
wordDoc.Tables.Item(1).Cell(2, 1).Range.Text = "cell21";
//wordDoc.Tables.Item(k).Cell(2, 2).Range.Text = DT.Rows[i]["cell21"].ToString();
////******************
wordDoc.Tables.Item(1).Cell(2, 3).Range.Text = "cell23";
//wordDoc.Tables.Item(k).Cell(2, 4).Range.Text = DT.Rows[i]["cell23"].ToString();
#endregion
#region 第三行显示
wordDoc.Tables.Item(1).Cell(3,2).Merge(wordDoc.Tables.Item(1).Cell(3,3));
wordDoc.Tables.Item(1).Cell(3,2).Merge(wordDoc.Tables.Item(1).Cell(3,3));
////******************
wordDoc.Tables.Item(1).Cell(3, 1).Range.Text = "cell31";
////******************
wordDoc.Tables.Item(1).Cell(3, 3).Range.Text = "cell33";
#endregion
#region 第五行显示
wordDoc.Tables.Item(1).Cell(5,2).Merge(wordDoc.Tables.Item(1).Cell(5,3));
wordDoc.Tables.Item(1).Cell(5,2).Merge(wordDoc.Tables.Item(1).Cell(5,3));
wordDoc.Tables.Item(1).Cell(5,2).Merge(wordDoc.Tables.Item(1).Cell(5,3));
wordDoc.Tables.Item(1).Cell(5,2).Merge(wordDoc.Tables.Item(1).Cell(5,3));
#endregion
#region 第四行显示
////******************
wordDoc.Tables.Item(1).Cell(4, 1).Range.Text = "cell41";
////******************
wordDoc.Tables.Item(1).Cell(4, 3).Range.Text = "cell43";
////******************
wordDoc.Tables.Item(1).Cell(4, 5).Range.Text = "cell45";
#endregion
#region 第六行显示
wordDoc.Tables.Item(1).Cell(6,2).Merge(wordDoc.Tables.Item(1).Cell(6,3));
wordDoc.Tables.Item(1).Cell(6,2).Merge(wordDoc.Tables.Item(1).Cell(6,3));
wordDoc.Tables.Item(1).Cell(6,2).Merge(wordDoc.Tables.Item(1).Cell(6,3));
wordDoc.Tables.Item(1).Cell(6,2).Merge(wordDoc.Tables.Item(1).Cell(6,3));
////******************
wordDoc.Tables.Item(1).Cell(5, 1).Range.Text = "cell51";
wordDoc.Tables.Item(1).Cell(5, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
////******************
wordDoc.Tables.Item(1).Cell(6, 1).Range.Text = "cdll61";
wordDoc.Tables.Item(1).Cell(6, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
#endregion
#region 第七行显示
wordDoc.Tables.Item(1).Cell(7,2).Merge(wordDoc.Tables.Item(1).Cell(7,3));
wordDoc.Tables.Item(1).Cell(7,2).Merge(wordDoc.Tables.Item(1).Cell(7,3));
wordDoc.Tables.Item(1).Cell(7,2).Merge(wordDoc.Tables.Item(1).Cell(7,3));
wordDoc.Tables.Item(1).Cell(7,2).Merge(wordDoc.Tables.Item(1).Cell(7,3));
////******************
wordDoc.Tables.Item(1).Cell(7, 1).Range.Text = "cell71";
wordDoc.Tables.Item(1).Cell(7, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
#endregion
#region 第八行显示
wordDoc.Tables.Item(1).Cell(8,1).Merge(wordDoc.Tables.Item(1).Cell(8,2));
wordDoc.Tables.Item(1).Cell(8,2).Merge(wordDoc.Tables.Item(1).Cell(8,3));
wordDoc.Tables.Item(1).Cell(8,2).Merge(wordDoc.Tables.Item(1).Cell(8,3));
wordDoc.Tables.Item(1).Cell(8,2).Merge(wordDoc.Tables.Item(1).Cell(8,3));
#endregion
#region 第九行显示
wordDoc.Tables.Item(1).Cell(9,1).Merge(wordDoc.Tables.Item(1).Cell(9,2));
wordDoc.Tables.Item(1).Cell(9,3).Merge(wordDoc.Tables.Item(1).Cell(9,4));
////******************
wordDoc.Tables.Item(1).Cell(9, 1).Range.Text = "cell91";
//wordDoc.Tables.Item(k).Cell(9, 2).Range.Text = (DT.Rows[i]["cell91"].ToString()=="1"?"有":"无");
////******************
wordDoc.Tables.Item(1).Cell(9, 3).Range.Text = "cell93";
#endregion
#region 第十行显示
wordDoc.Tables.Item(1).Cell(10,1).Merge(wordDoc.Tables.Item(1).Cell(10,2));
wordDoc.Tables.Item(1).Cell(10,3).Merge(wordDoc.Tables.Item(1).Cell(10,4));
////******************
wordDoc.Tables.Item(1).Cell(10, 1).Range.Text = "cell101";
////******************
wordDoc.Tables.Item(1).Cell(10, 3).Range.Text = "cdll103";
//wordDoc.Tables.Item(k).Cell(10, 4).Range.Text = (DT.Rows[i]["Label"].ToString()=="1"?"有":"无");
#endregion
#region 第十一行显示
wordDoc.Tables.Item(1).Cell(11,1).Merge(wordDoc.Tables.Item(1).Cell(11,2));
wordDoc.Tables.Item(1).Cell(11,3).Merge(wordDoc.Tables.Item(1).Cell(11,4));
////******************
wordDoc.Tables.Item(1).Cell(11, 1).Range.Text = "cell111";
////******************
wordDoc.Tables.Item(1).Cell(11, 3).Range.Text = "cell113";
#endregion
#region 第十二行显示
wordDoc.Tables.Item(1).Cell(12,1).Merge(wordDoc.Tables.Item(1).Cell(12,2));
wordDoc.Tables.Item(1).Cell(12,3).Merge(wordDoc.Tables.Item(1).Cell(12,4));
////******************
wordDoc.Tables.Item(1).Cell(12, 1).Range.Text = "cell121";
////******************
wordDoc.Tables.Item(1).Cell(12, 3).Range.Text = "cell123";
#endregion
#region 第十三行显示
wordDoc.Tables.Item(1).Cell(13,1).Merge(wordDoc.Tables.Item(1).Cell(13,2));
wordDoc.Tables.Item(1).Cell(13,3).Merge(wordDoc.Tables.Item(1).Cell(13,4));
////******************
wordDoc.Tables.Item(1).Cell(13, 1).Range.Text = "cell131";
////******************
wordDoc.Tables.Item(1).Cell(13, 3).Range.Text = "cell133";
#endregion
wordDoc.Tables.Item(1).Select();
wordApp.Application.Selection.Cut();
//重新成声所有表
for(int i = 0; i<=DT.Rows.Count-1;i++)
{
wordApp.Application.Selection.Paste();
int k = i+1;
#region 更新数据
#region 插入数据行
wordDoc.Tables.Item(k).Cell(1, 2).Range.Text = DT.Rows[i]["1"].ToString();
////******************
wordDoc.Tables.Item(k).Cell(1, 4).Range.Text = DT.Rows[i]["2"].ToString();
////******************
wordDoc.Tables.Item(k).Cell(2, 2).Range.Text = DT.Rows[i]["3"].ToString();
////******************
wordDoc.Tables.Item(k).Cell(2, 4).Range.Text = DT.Rows[i]["4"].ToString();
#endregion
#region 第三行显示
////******************
wordDoc.Tables.Item(k).Cell(3, 2).Range.Text = DT.Rows[i]["5"].ToString();
////******************
wordDoc.Tables.Item(k).Cell(3, 4).Range.Text = DT.Rows[i]["6"].ToString();
#endregion
#region 第五行显示
////******************
wordDoc.Tables.Item(k).Cell(5, 2).Range.Text = DT.Rows[i]["7"].ToString();
wordDoc.Tables.Item(k).Cell(5, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
#endregion
#region 第四行显示
////******************
wordDoc.Tables.Item(k).Cell(4, 2).Range.Text = DT.Rows[i]["8"].ToString();
////******************
wordDoc.Tables.Item(k).Cell(4, 4).Range.Text = DT.Rows[i]["9"].ToString();
////******************
wordDoc.Tables.Item(k).Cell(4, 6).Range.Text = DT.Rows[i]["0"].ToString();
#endregion
#region 第六行显示
////******************
wordDoc.Tables.Item(k).Cell(6, 2).Range.Text = DT.Rows[i]["11"].ToString();
wordDoc.Tables.Item(k).Cell(6, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
#endregion
#region 第七行显示
////******************
wordDoc.Tables.Item(k).Cell(7, 2).Range.Text = DT.Rows[i]["12"].ToString();
wordDoc.Tables.Item(k).Cell(7, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
#endregion
#region 第八行显示
////******************
string strTechlevel = DT.Rows[i]["Level"].ToString();
string returnTechlevel = "";
switch(strTechlevel)
{
case "1":
returnTechlevel = "Level1";
break;
case "2":
returnTechlevel = "Level2";
break;
case "3":
returnTechlevel = "Level3";
break;
case "0":
returnTechlevel = "Level4";
break;
default:
returnTechlevel = "Level5";
break;
}
wordDoc.Tables.Item(k).Cell(8, 2).Range.Text = returnTechlevel;
#endregion
#region 第九行显示
////******************
wordDoc.Tables.Item(k).Cell(9, 2).Range.Text = (DT.Rows[i]["14"].ToString()=="1"?"有":"无");
////******************
wordDoc.Tables.Item(k).Cell(9, 4).Range.Text = (DT.Rows[i]["15"].ToString()=="1"?"是":"否");
#endregion
#region 第十行显示
////******************
wordDoc.Tables.Item(k).Cell(10, 2).Range.Text = (DT.Rows[i]["16"].ToString()=="1"?"有":"无");
////******************
wordDoc.Tables.Item(k).Cell(10, 4).Range.Text = (DT.Rows[i]["17"].ToString()=="1"?"有":"无");
#endregion
#region 第十一行显示
////******************
wordDoc.Tables.Item(k).Cell(11, 2).Range.Text = (DT.Rows[i]["18"].ToString()=="1"?"是":"否");
////******************
wordDoc.Tables.Item(k).Cell(11, 4).Range.Text = (DT.Rows[i]["19"].ToString()=="1"?"是":"否");
#endregion
#region 第十二行显示
////******************
wordDoc.Tables.Item(k).Cell(12, 2).Range.Text = (DT.Rows[i]["20"].ToString()=="1"?"是":"否");
////******************
wordDoc.Tables.Item(k).Cell(12, 4).Range.Text = (DT.Rows[i]["21"].ToString()=="1"?"是":"否");
#endregion
#region 第十三行显示
wordDoc.Tables.Item(k).Cell(13, 2).Range.Text = (DT.Rows[i]["22"].ToString()=="1"?"是":"否");
////******************
wordDoc.Tables.Item(k).Cell(13, 4).Range.Text = (DT.Rows[i]["23"].ToString()=="1"?"是":"否");
#endregion
#endregion
//插入分页
if(i!=DT.Rows.Count-1)
{
object mymissing = System.Reflection.Missing.Value;
object myunit = Word.WdUnits.wdStory;
wordApp.Selection.EndKey(ref myunit,ref mymissing);
object pBreak= (int)Word.WdBreakType.wdPageBreak;
wordApp.Selection.InsertBreak( ref pBreak );
}
}
wordDoc.SaveAs(ref filename, ref missing,ref missing, ref missing,ref missing,ref missing,ref missing,ref missing,ref missing,ref missing, ref missing);
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
if ( wordDoc != null )
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc);
wordDoc = null;
}
if ( wordApp != null )
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
wordApp = null;
}
GC.Collect();
//KillWordProcess();
string strUrl = "MakeWordFile.aspx?username="+Request.QueryString["username"].ToString();
utility.ShowPopMessage("文档生成完毕!",strUrl);
}
else
{
utility.ShowPopMessage("无任何数据!");
}
#endregion
}
catch
{
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
if ( wordDoc != null )
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordDoc);
wordDoc = null;
}
if ( wordApp != null )
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
wordApp = null;
}
GC.Collect();
utility.ShowPopMessage("文档生成失败!");
}
}
9.c#读取Word
1:
对项目添加引用,Microsoft Word 11.0 Object Library
2:
在程序中添加 using Word = Microsoft.Office.Interop.Word;
3:
程序中添加
Word.Application app = new Microsoft.Office.Interop.Word.Application(); //可以打开word程序
Word.Document doc = null; //一会要记录word打开的文档
word文档和word程序可不是一回事奥!
4:
一般来说,对于抽取word内容,用的方法很少
public override void openFile(object fileName){} //打开文档
public override object readPar(int i){} //读取word文档的第i段
public override int getParCount(){} //返回word文档一共几段
public override void closeFile(){} //关闭文档
public override void quit(){} //关闭word程序
//从网页上拷贝的目录有时候会出现手动换行符^l,,先将其换成回车段落标记,才能正确读取
public void replaceChar(){}
5:代码
public override void openFile(object fileName)
{
try
{
if (app.Documents.Count > 0)
{
if (MessageBox.Show("已经打开了一个word文档,你想关闭重新打开该文档吗?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
object unknow = Type.Missing;
doc = app.ActiveDocument;
if (MessageBox.Show("你想保存吗?", "保存", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
app.ActiveDocument.Save();
}
app.ActiveDocument.Close(ref unknow, ref unknow, ref unknow);
app.Visible = false;
}
else
{
return;
}
}
}
catch (Exception)
{
//MessageBox.Show("您可能关闭了文档");
app = new Microsoft.Office.Interop.Word.Application();
}
try
{
object unknow = Type.Missing;
app.Visible = true;
doc = app.Documents.Open(ref fileName,
ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);
}
catch (Exception ex)
{
MessageBox.Show("出现错误:" + ex.ToString());
}
}
public override object readPar(int i)
{
try
{
string temp = doc.Paragraphs[i].Range.Text.Trim();
return temp;
}
catch (Exception e) {
MessageBox.Show("Error:"+e.ToString());
return null;
}
}
public override int getParCount()
{
return doc.Paragraphs.Count;
}
public override void closeFile()
{
try
{
object unknow = Type.Missing;
object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;
app.ActiveDocument.Close(ref saveChanges, ref unknow, ref unknow);
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.ToString());
}
}
public override void quit()
{
try
{
object unknow = Type.Missing;
object saveChanges = Word.WdSaveOptions.wdSaveChanges;
app.Quit(ref saveChanges, ref unknow, ref unknow);
}
catch (Exception)
{
}
}
public void replaceChar() {
try
{
object replaceAll = Word.WdReplace.wdReplaceAll;
object missing = Type.Missing;
app.Selection.Find.ClearFormatting();
app.Selection.Find.Text = "^l";
app.Selection.Find.Replacement.ClearFormatting();
app.Selection.Find.Replacement.Text = "^p";
app.Selection.Find.Execute(
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref replaceAll, ref missing, ref missing, ref missing, ref missing);
}
catch (Exception e)
{
MessageBox.Show("文档出现错误,请重新操作");
}
}
6:
刚才是用读取一段做的例子,如果要读取一句或一篇只需要把doc.Paragraphs[i](readPar中)改成doc.Sentences[i]或doc.content即可,因为都是微软的东东,所以用起来没有一点的障碍,再加上现在的vs2005做的很智能,所以先从java转到了c#上
7:
实际上,c#中读取word是不用那么麻烦的,但是如果考虑到可能还要抽取txt,ppt等多种格式,所以就写了一个抽象类,调用起来也方便,这就是为什么我的程序方法开头会有override的原因,总要考虑到通用,所以多了一些代码。
10.C#打开WORD文档内容并显示
private void button1_Click(object sender, System.EventArgs e)
{
//调用打开文件对话框获取要打开的文件WORD文件,RTF文件,文本文件路径名称
OpenFileDialog opd = new OpenFileDialog();
opd.InitialDirectory = "c://";
opd.Filter = "Word文档(*.doc)|*.doc|文本文档(*.txt)|*.txt|RTF文档(*.rtf)|*.rtf|所有文档(*.*)|*.*";
opd.FilterIndex = 1;
if (opd.ShowDialog() == DialogResult.OK && opd.FileName.Length > 0)
{
//建立Word类的实例,缺点:不能正确读取表格,图片等等的显示
Word.ApplicationClass app = new Word.ApplicationClass();
Word.Document doc = null;
object missing = System.Reflection.Missing.Value;
object FileName = opd.FileName;
object readOnly = false;
object isVisible = true;
object index = 0;
try
{
doc = app.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);
doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();
//从剪切板获取数据
IDataObject data=Clipboard.GetDataObject();
this.richTextBox1.Text=data.GetData(DataFormats.Text).ToString();
}
finally
{
if (doc != null)
{
doc.Close(ref missing, ref missing, ref missing);
doc = null;
}
if (app != null)
{
app.Quit(ref missing, ref missing, ref missing);
app = null;
}
}
}
}