日期:2014-05-18  浏览次数:20876 次

利用C#操作WORD
很久没有接触.NET了,最近考虑好了,还是继续我的.NET;接着之前的任务,利用C#操作WORD文档;今天上午研究了很一会儿,但还是没有弄明白,虽然有些原理明白了,但是,有些代码始终都是敲不出来,比如Word……,我也添加了COM组件,但是还是没有效果,命名空间添加了:using Microsoft.Office.Interop.Word;在网上找了相关资料,但始终没有效果,因此就向各位大佬请教;那位大佬可以把源文件发给我参考下嘛,本人定当重谢!
  491077947@qq.com

------解决方案--------------------
C# code

using Microsoft.Office.Interop.Word;//引用
public Application Word;
public Document Doc;
public object miss = System.Reflection.Missing.Value;

object path = System.Web.HttpContext.Current.Server.MapPath("~/TemplateFile/Import/" + fileName + ".doc");
Object Nothing = System.Reflection.Missing.Value;//内容
//创建文档
Word = new ApplicationClass();
Doc = Word.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
                #region 添加页眉
                //添加页眉
                Word.ActiveWindow.View.Type = WdViewType.wdOutlineView;
                Word.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
                Word.ActiveWindow.ActivePane.Selection.InsertAfter("[页眉内容]");
                Word.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐
                Word.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置
                //Word.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距
                Doc.PageSetup.PageHeight = Word.CentimetersToPoints(29.7f);
                Doc.PageSetup.PageWidth = Word.CentimetersToPoints(21f);
                Doc.PageSetup.LeftMargin = 5f;
                Doc.PageSetup.TopMargin = 0f;
                //Doc.PageSetup.TopMargin = 57;//设置上边距
                //Doc.PageSetup.BottomMargin = 57;//下边距
                //Doc.PageSetup.LeftMargin = 57;//左边距
                //Doc.PageSetup.RightMargin = 57;//右边距
                #endregion

//文档中创建表格
                Table newTable = Doc.Tables.Add(Word.Selection.Range, allRoews, 4, ref Nothing, ref Nothing);
                //设置表格样式
                newTable.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;
                newTable.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
                newTable.Columns[1].Width = 142f;
                newTable.Columns[2].Width = 142f;
                newTable.Columns[3].Width = 142f;
                newTable.Columns[4].Width = 142f;

                newTable.Cell(2, 1).Range.Text ="内容";
Doc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString("yyyy-MM-dd");//落款
                Doc.Paragraphs.Last.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
                //文件保存
                Doc.SaveAs(ref path, 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);
                Doc.Close(ref Nothing, ref Nothing, ref Nothing);
                Word.Quit(ref Nothing ,ref Nothing, ref Nothing);

------解决方案--------------------
http://download.csdn.net/tag/word.dll