C#操控word和IE实现上传文章
场景:
OA系统用了在线office插件,只能用IE浏览器,打开网页时显示在线版word,但是用F12开发工具看取不到元素。用chrome浏览器无法操作。
手工上传文件的做法是:在电脑上打开word文章,CTRL+A全选,CTRL+C复制;然后打开网页,CTRL+V粘贴。
另外,网页上还有input和submit元素,好在这两个元素可以用开发工具选取和提交。
思路:C#读取word,全选并复制到剪贴板,关闭word;用SHDocVw.InternetExplorer打开IE,打开后焦点在网页word控件中,发送CTRL+V;再填写input和submit提交。
代码:
private void 发稿件ToolStripMenuItem_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; //打开word文件所在目录 //获得该文件夹下的文件,返回类型为FileInfo string path = @"I:\mynews"; DirectoryInfo root = new DirectoryInfo(path); FileInfo[] files = root.GetFiles(); Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application(); object fname = files[0].FullName; string fnamestr = files[0].Name; var doc = app.Documents.Open(ref fname); Range range = doc.Range();//如果Range()不传入实参,则表示获取整个Document范围的Range range.Copy(); doc.Close(); app.Quit(); app = null; System.Threading.Thread.Sleep(300); //流程-发文-切换文档类型word SHDocVw.InternetExplorer IE = new SHDocVw.InternetExplorer(); object Empty = 0; object URL = "http://192.168.132.80/docs/docs/DocAddExt.jsp?mainid=15&secid=1143&subid=49&topage=&showsubmit=1&prjid=&coworkid=&crmid=&hrmid=&docType=.doc&docsubject=&from=&userCategory=0&invalidationdate="; IE.Visible = true; IE.Navigate2(ref URL, ref Empty, ref Empty, ref Empty, ref Empty); System.Threading.Thread.Sleep(10000); //System.Windows.Forms.SendKeys.Send("^v");//这个命令似乎会导致焦点切换,不可靠。 KeyBordClick kc = new KeyBordClick(); kc.KeyBordPaste(); //填入文件名 fnamestr = fnamestr.Replace(".docx", ""); fnamestr = fnamestr.Replace(".doc", ""); ((IE.Document as mshtml.HTMLDocument).getElementById("docsubject") as mshtml.HTMLInputElement).value = fnamestr; System.Threading.Thread.Sleep(1000); //找提交按钮 var btnts = (IE.Document as mshtml.HTMLDocument).getElementsByTagName("button"); foreach (mshtml.HTMLButtonElement btnt in btnts) { if (btnt.innerText == "保存到服务器") { btnt.click(); files[0].Delete(); break; } } }
class KeyBordClick { [DllImport("user32.dll", EntryPoint = "keybd_event", SetLastError = true)] private static extern void keybd_event(Keys bVk, byte bScan, uint dwFlags, uint dwExtraInfo); const int KEYEVENTF_KEYUP = 0x02; const int KEYEVENTF_KEYDOWN = 0x00; //相当于按下ctrl+v,然后回车 public void KeyBordPaste() { keybd_event(Keys.ControlKey, 0, KEYEVENTF_KEYDOWN, 0); keybd_event(Keys.V, 0, 0, 0); keybd_event(Keys.ControlKey, 0, KEYEVENTF_KEYUP, 0); keybd_event(Keys.Enter, 0, 0, 0); } }