net操作wps

最主要是这句dynamic comObject = Activator.CreateInstance(Type.GetTypeFromProgID(“kwps.Application”));

/*

  • 由SharpDevelop创建。
  • 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
    */
    using System;
    using System.Runtime.InteropServices;
    using System.IO;
    using System.Text.RegularExpressions;

namespace conert
{
///
/// Description of Class3.
///
public class Class3
{
const bool isVisible = false;

	public Class3()
	{
	}
	public void method1(String infile,String outfile){
			
	string extension = Path.GetExtension(infile);

    if (extension != null && Regex.IsMatch(extension, @"\.(doc|docx)$", RegexOptions.IgnoreCase))
    {
        Console.WriteLine(infile+" is a word file.");
    }
    else
    {
        Console.WriteLine("This is not a word file. 取消执行");
        return ;
    }
    
	bool fileExists = File.Exists(infile);
	Console.WriteLine("File.Exists:"+fileExists);
	if(!fileExists){ throw new Exception("文件不存在");}
   
		dynamic word = Activator.CreateInstance(Type.GetTypeFromProgID("kwps.Application"));
		    word.Visible=isVisible;
        	word.Documents.Open(infile);

// Console.WriteLine(word.Documents.Open(infile));
dynamic doc=word.ActiveDocument ;

            //处理编辑保护
            int isProtect=doc.ProtectionType;
            Console.WriteLine("protect: " + doc.ProtectionType );
			if (-1 != isProtect) {
				try {
					doc.Unprotect("");
				} catch (COMException comEx) {
//                Console.WriteLine("C调用失败: " + comEx.Message);
					Console.WriteLine("C调用失败码: " + comEx.ErrorCode);// -2146825275 无密码
					//    Console.WriteLine("C调用失败码: " + comEx.Data);
//                throw comEx;
					//-2146825274  密码不正确
					if (comEx.ErrorCode == -2146825274) {
						doc.Close();
						word.Quit();
						throw comEx;
					}
				}
			}//处理编辑保护 end
        try
        {

            dynamic section=doc.Sections.Item(1);
            
            for(int i=1;i<=section.Headers.count;i++){
            	if(null!=section.Headers.Item(i).Range)
				section.Headers.Item(i).Range.delete();
			}
            for(int i=1;i<=section.Footers.count;i++){
            	if(null!=section.Footers.Item(i))
				section.Footers.Item(i).Range.delete();
			}
            doc.SaveAs(outfile);//SaveAs

// doc.Save();
doc.Close();
word.Quit();
}
catch (COMException comEx)
{
Console.WriteLine("C调用失败: " + comEx.Message);
throw comEx;
}
}

	 static void Main2(string[] args)
    {
        dynamic comObject = Activator.CreateInstance(Type.GetTypeFromProgID("kwps.Application"));
        try
        {
            Console.WriteLine(comObject.SomeMethod());
        }
        catch (COMException comEx)
        {
            Console.WriteLine("COM调用失败: " + comEx.Message);
        }
    }
}

}

  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值