需要做一个用c#自动生成word文件的小程序,粗略的google了一些代码示例,有一个问题困扰了我半天,就是如何在生成时控制一个段落中有多种格式,比如:

   这是一个测试文件,由c#生成

里面包含有大小、加粗、斜体、颜色、下划线。

感觉用select然后设置格式可用,但是好像比较麻烦,后来想了一种变通的方法,就是先将各部分生成不同的段落,然后删除上一段的回车符,基本上可行吧。

                //调用word
                Word.Application wdx = new Word.Application();
                Object oMissing 
= System.Reflection.Missing.Value;
                
//新建文件
                Word.Document wdoc = wdx.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);
                
//写入内容
                wdoc.Paragraphs.Last.Range.Text = "这是\n";
                wdoc.Paragraphs.Last.Range.Text 
= "一个\n";
                
//调整格式
                wdoc.Paragraphs[wdoc.Paragraphs.Count - 1].Range.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineSingle;
                
//删除上行回车
                wdoc.Paragraphs[wdoc.Paragraphs.Count - 2].Range.Words.Last.Cut();
                
//写入内容
                wdoc.Paragraphs.Last.Range.Text = "测试文件,由c#\n";
                wdoc.Paragraphs.Last.Range.Text 
= "生成\n";
                
//调整格式
                wdoc.Paragraphs[wdoc.Paragraphs.Count - 1].Range.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineSingle;
                .
                wdoc.Paragraphs[wdoc.Paragraphs.Count 
- 2].Range.Words.Last.Cut();

                Object fileName 
= "test.docx";
                
//存盘退出
                wdoc.SaveAs(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);
                wdoc.Close(
ref oMissing, ref oMissing, ref oMissing);
                wdx.Quit(
ref oMissing, ref oMissing, ref oMissing);
发表于: 2008-03-13 14:38 肉香鱼丝 阅读(807) 评论(0)  收藏(0) 好文推荐

作者该类其他文章:


标题  
姓名  
主页
内容   
请输入验证码:
*
(如果看不到图片,请多刷新几次页面)
  登录   Top
[使用Ctrl+Enter键可以直接提交]