C#操作word文档(三)

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 replaceWidth=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中的http://blog.joycode.com/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的文章(这是一个系列的之一),再看这段代码应该不会很难理解。打开一个已有文档,然后遍历其中的所有的表。这里只是简单的将信息显示出来,具体实践上可以对这些信息进行分析。做完这些后,终于找到了一些官方的支持文档,地址如下:
http://msdn2.microsoft.com/zh-CN/library/y1xatbkd.aspx
其中的word任务有对word各种操作的简单代码事例,用vb和c#写的。看完之后,我想每个人都会明白vb对com的支持比c#不是简单明了一点两点。(可以看下这个http://blog.joycode.com/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.Paragraph 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 after 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里加 <identity impersonate="true"/> 转换为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(upfile.PostedFile.FileName.LastIndexOf("//"),upfile.PostedFile.FileName.Length - upfile.PostedFile.FileName.LastIndexOf("//"));    //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 Unknown,ref Unknown);    System.Runtime.InteropServices.Marshal.ReleaseComObject(WPSApp); 6.C#操作word,如何进行查找和替换?说明:请在工程中引用“Microsoft Word 9.0 object library”的Microsoft COM组件。该组件提供的类和方法来读取Word文档。using System;using System.IO;using System.Reflection;using Word;   //----------------------------------------------------------------------     string WordContent = "";      object saveChanges = WdSaveOptions.wdDoNotSaveChanges;     Word.Application app = new ApplicationClass();      try     {      object fileName = fileDoc.Value;       object optional= Missing.Value;       object visible=true;       if(File.Exists(fileName.ToString()))       {        Word.Document doc = app.Documents.Open(        ref fileName,         ref optional,         ref optional,         ref optional,         ref optional,         ref optional,         ref optional,         ref optional,        ref optional,        ref optional,        ref optional,        ref visible);       object first = 0;        object units = WdUnits.wdCharacter;        object last=doc.Characters.Count;          Range    range= doc.Range(ref first, ref last);        //替换       #region 方法一,特点是非常简单       //Word.range.Text = range.Text.Replace(txtOldValue.Text, txtNewValue.Text);       #endregion       #region 方法二,特别是可以实现复杂的查找替换       Word.Find finder = range.Find;       finder.ClearFormatting();            object missingValue = Type.Missing;        object findStr = txtOldValue.Text;        object replaceStr = txtNewValue.Text;       object replaceArea = Word.WdReplace.wdReplaceAll;       if (finder.Execute(ref findStr, ref missingValue, ref missingValue,         ref missingValue, ref missingValue, ref missingValue,        ref missingValue, ref missingValue, ref missingValue,         ref replaceStr, ref replaceArea, ref missingValue,         ref missingValue, ref missingValue, ref missingValue))        {         //Text found,and replaceed        //range.Select();       }        #endregion       WordContent = "成功替换 " + txtOldValue.Text + " at " + DateTime.Now.ToString();       saveChanges = WdSaveOptions.wdSaveChanges;         }       else       {        WordContent = "指定目录下的无该文件";       }       txtContent.Text = WordContent;           }      catch(Exception Ex)      {       txtContent.Text =     Ex.Message ;      }     finally     {      //退出保存      object originalFormat = Missing.Value;       object routeDocument = Missing.Value;       app.Quit(ref saveChanges, ref originalFormat, ref routeDocument);       app = null;     }8.ASP.NET 2.0,C#----利用GridView控件导出其他文件(导出Excel,导出Word文件)// 注意,在Visual Studio2005平台下,如果使用GridView导出文件,         //就必须重载VerifyRenderingInServerForm方法        public override void VerifyRenderingInServerForm(Control control)        {                   }         /// <summary>        ///  导出到文件的方法,        /// </summary>        /// <param name="Model">Model=1:导出为Execl,Model=2:导出为Word</param>        private void toFiles(int Model)        {            string strFileName = DateTime.Now.ToString("yyyyMMdd-hhmmss");            System.Web.HttpContext HC = System.Web.HttpContext.Current;             HC.Response.Clear();             HC.Response.Buffer = true;             HC.Response.ContentEncoding = System.Text.Encoding.UTF8;//设置输出流为简体中文             if (Model == 1)            {                //---导出为Excel文件                 HC.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8) + ".xls");                 HC.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。            }            else            {                //--- 导出为Word文件                 HC.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8) + ".doc");                 HC.Response.ContentType = "application/ms-word";//设置输出文件类型为Word文件。            }             System.IO.StringWriter sw = new System.IO.StringWriter();            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);            this.GridView1.RenderControl(htw);              HC.Response.Write(sw.ToString());             HC.Response.End();                   }        //-导出为Excel文件        protected void ToExecl_Click(object sender, EventArgs e)        {            toFiles(1);        }        //-导出为Word文件        protected void Button1_Click(object sender, EventArgs e)        {            toFiles(2);        } 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/liusen5555/archive/2008/01/17/2048837.aspx

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值