找了很多资料,发现适用性不是很高,最后发现其中的一些对象不好定位,从文本框转成图文框后比较容易定位,可以用frame定位,表格也比较容易定位,不知道文本框该如何定位,如果有哪位大侠知道也可以提醒一下,而selection定位也云里雾里。
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Word= Microsoft.Office.Interop.Word;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string CreateWordFile(string CheckedInfo)
{
string message = "";
try
{
Object Nothing = System.Reflection.Missing.Value;
Directory.CreateDirectory("C:/CNSI"); //创建文件所在目录
string name = "CNSI_" + DateTime.Now.ToShortDateString()+".doc";
object filename = "d://" + "业务范围.doc"; //文件保存路径
object vis = false;
//创建Word文档
Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Open(ref filename, ref Nothing, ref Nothing, ref Nothing,ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,ref Nothing, ref vis, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
filename = "d://test.doc";
string s;
//s=WordDoc.Frames[2].Range.Text.ToString();
s = WordDoc.Frames[1].Range.Text.ToString();
WordDoc.Frames[1].Range.Text = "2009 09 23";
//frame改写时,需要word模板中存在图文框,而不是文本框,需要从文本框转换而来。
WordDoc.Tables[1].Cell(1, 2).Range.Text = "文字";
//word文档的表格定位
WordDoc.SaveAs(ref filename, 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, ref Nothing);
WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
//message=name+"文档生成成功,以保存到C:CNSI下";
Response.Redirect();
}
catch (Exception ex)
{
message += ex.ToString();
message = "文件导出异常!";
}
return message;
}
protected void Button1_Click(object sender, EventArgs e)
{
string sTemp = "";
sTemp= CreateWordFile("test");
}
}
本文介绍了一种使用C#实现Word文档自动化编辑的方法,包括如何创建、打开文档,修改特定位置的内容如图文框内的文本和表格单元格等。该方法适用于需要批量修改Word文档的场景。
1824

被折叠的 条评论
为什么被折叠?



