资源描述:
《WORD、EXCEL内容替换》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、WORD/EXCEL内容替换点击:386次 最近,在做一个小项目时,需要用到WORD/EXCEL(目前只针对OFFICE2003)文档中内容的替换,在网上搜寻了一番,找到了一些解决方法,自己再整理了一下,记录出来与大家共享。 1、在项目的引用中添加WORD和EXCEL的COM引用:Microsoft.Word11.0ObjectLibrary和Microsoft.Excel11.0ObjectLibrary; 2、在文件的USING部分加入以下命名空间:usingMicrosoft.Office.Core
2、;usingMicrosoft.Office.Interop.Word;usingMicrosoft.Office.Interop.Excel;usingSystem.IO;usingSystem.Reflection; 3、定义WORD和EXCEL内容替换函数: privatevoidWordReplace(stringfilePath,stringstrOld,stringstrNew) { Microsoft.Office.Interop.Word.Appli
3、cationapp=newMicrosoft.Office.Interop.Word.ApplicationClass(); objectnullobj=System.Reflection.Missing.Value; objectfile=filePath; Microsoft.Office.Interop.Word.Documentdoc=app.Documents.Open( reffile,refnullobj,refnull
4、obj, refnullobj,refnullobj,refnullobj, refnullobj,refnullobj,refnullobj, refnullobj,refnullobj,refnullobj, refnullobj,refnullobj,refnullobj,refnullobj); doc.Content.Text=doc.Content.Text.Replace(strOld,strNew)
5、; doc.Content.AutoFormat(); Microsoft.Office.Interop.Word.Rangerange=null; doc.Close(refnullobj,refnullobj,refnullobj); app.Quit(refnullobj,refnullobj,refnullobj); } privatevoidExcelReplace(stringfilePath,s
6、tringstrOld,stringstrNew) { Microsoft.Office.Interop.Excel.Applicationexcel=newMicrosoft.Office.Interop.Excel.ApplicationClass(); excel.Visible=false; stringmodelFile=filePath; //文件名 Workbookwb=excel.Workbooks._Op
7、en(modelFile,Missing.Value,Missing.Value,Missing.Value,Missing.Value ,Missing.Value,Missing.Value,Missing.Value,Missing.Value ,Missing.Value,Missing.Value,Missing.Value,Missing.Value); WorksheetxSheet=(Worksheet)wb.Sheets[1];
8、 inticount=wb.Sheets.Count; for(inti=1;i<=icount;i++) { try { xSheet=(Worksheet)wb.Sheets[i]; o