C#的office文档操作(2)
来源:互联网 发布:詹姆斯2016为止总数据 编辑:程序博客网 时间:2024/05/16 12:41
4.目的说明
在Microsoft.Office.Interop.Word命名空间下有一个枚举名为WdSaveFormat,设定了可用于保存的形式,如图8.5所示。对应于如图8.6所示的Word保存格式。
图8.5 WdSaveFormat枚举 图8.6 保存格式
可以看到,WdSaveFormat枚举中定义的格式更为详细,下面介绍如何创建一个Microsoft Word 2007格式的文档。
5.操作步骤
(1)创建一个Windows控制台应用程序,命名为CreateWordXDemo。
(2)添加对Microsoft Word 12.0 Object Library的引用(同之前的步骤,不再详述)。
(3)在“Program.cs”文件中添加如下引用。
using MSWord = Microsoft.Office.Interop.Word;
using System.IO;
using System.Reflection;
(4)直接修改“Program.cs”文件的代码如下。
class Program
{
static void Main(string[] args)
{
object path; //文件路径变量
string strContent; //文本内容变量
MSWord.Application wordApp; //Word应用程序变量
MSWord.Document wordDoc; //Word文档变量
path = @"C:/MyWord.docx"; //路径
wordApp = new MSWord.ApplicationClass(); //初始化
//如果已存在,则删除
if (File.Exists((string)path))
{
File.Delete((string)path);
}
//由于使用的是COM库,因此有许多变量需要用Missing.Value代替
Object Nothing = Missing.Value;
wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
//strContent = "你好!/n";
//wordDoc.Paragraphs.Last.Range.Text = strContent;
//strContent = "Hello World";
//wordDoc.Paragraphs.Last.Range.Text = strContent;
//WdSaveFormat为Word 2007文档的保存格式
object format =MSWord.WdSaveFormat.wdFormatDocumentDefault;
//将wordDoc文档对象的内容保存为DOCX文档
wordDoc.SaveAs(ref path, 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);
//关闭wordDoc文档对象
wordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
//关闭wordApp组件对象
wordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
Console.WriteLine(path + " 创建完毕!");
}
}
6.运行结果
运行程序,结果如图8.7所示。
图8.7 运行结果
打开C盘根目录,如图8.8所示。
图8.8 创建成功
可以看到,已经成功地创建了一个名为MyWord.docx的Word文档。该文档是Microsoft Word 2007默认的文档格式,大小约为11KB。
- C#的office文档操作(2)
- C#的office文档操作(3)
- C#的office文档操作(4)
- C#的office文档操作(5)
- C#的office文档操作
- C#的office文档操作
- C#的office文档操作
- C#的office word文档的操作(1)
- C#操作Word文档(Office 2007)
- C#操作Word文档(Office 2007)
- C#操作Word文档(Office 2007)
- C#操作Word文档(Office 2007)
- C#操作Word文档(Office 2007)
- C#操作Word文档(Office 2007)
- C#操作Word文档(Office 2007)
- 操作服务器端的OFFICE文档
- C#操作office技术总结(2)
- WPF打开操作Office文档的解决办法
- 如何解决JSP页面乱码问题
- C#的office word文档的操作(1)
- Android 中显示 Gif 格式图
- 从web转向软件的感触
- Flex 批量替换字符串,方法
- C#的office文档操作(2)
- linux icotl函数解析
- 为什么需要安装USB驱动
- C#的office文档操作(3)
- Javascript 中的false、0、null、undefined和空字符串对象
- C#的office文档操作(4)
- Android中往手机自带的存储空间写入文件
- 想买房的人必看!踢爆眼下售楼小姐的新骗局
- C#的office文档操作(5)