当前位置: 编程技术>.net/c#/asp.net
C#生成word记录实例解析
来源: 互联网 发布时间:2014-11-01
本文导语: 本文以实例形式讲述了C#生成Word记录的方法,具体实现代码如下: private void button1_Click(object sender, System.EventArgs e) { object oMissing = System.Reflection.Missing.Value; object oEndOfDoc = "\endofdoc"; /* endofdoc是预定义的bookmark */ //创建一...
本文以实例形式讲述了C#生成Word记录的方法,具体实现代码如下:
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