关于c#操作word类的奇怪问题

mouse791020 2010-02-20 10:50:27
按照网上的例子,我写了个简单的替换word中某一字符串的程序

static void Main(string[] args)
{
Program cls = new Program();

Microsoft.Office.Interop.Word.ApplicationClass wdApp = new Microsoft.Office.Interop.Word.ApplicationClass();
Microsoft.Office.Interop.Word.Document wdDoc = null;
object missing = System.Reflection.Missing.Value;
object MissingValue = System.Reflection.Missing.Value;

string strFileName = @"e:\test.doc";
string strOld = @"ddd";
string strNew = @"abc";
wdDoc.Content.Find.Text = strOld;
object FindText, ReplaceWith, Replace;
FindText = strOld;
ReplaceWith = strNew;
Replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceOne;
object FileName = strFileName;
object readOnly = false;
object isVisible = true;
object index = 0;

try
{
wdDoc = wdApp.Documents.Open(ref FileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
ref isVisible, ref missing, ref missing, ref missing, ref missing);

wdDoc.ActiveWindow.Selection.WholeStory();
wdDoc.ActiveWindow.Selection.Copy();

wdDoc.Content.Find.ClearFormatting();
wdDoc.Content.Find.Execute(ref FindText, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue,
ref ReplaceWith, ref Replace, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue);
}

finally
{
if (wdDoc != null)
{
wdDoc.Close(ref missing, ref missing, ref missing);
wdDoc = null;
}
if (wdApp != null)
{
wdApp.Quit(ref missing, ref missing, ref missing);
wdApp = null;
}
}
}

但是问题在于,编译通过后,一运行就说wdDoc.Content.Find.Text = strOld;出错,说是内存不能读写。但是这个都是和网上的例子一致的,不知道什么地方出了问题,请指教。

如果这样不行的话,那么该如何使用C#对WORD文件中特定字符进行替换操作呢?
...全文
154 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
mouse791020 2010-02-22
  • 打赏
  • 举报
回复
引用 7 楼 wan766405890 的回复:
为什么要用组件呢word实际上就是特定xml格式的二进制流,你通过这种格式写xml再写二进制不就行了!


我知道XML的中间技术。

但是我不用实现这么复杂的内容,我的要求仅仅是这样:

1、我有一篇word文档,(内容不定,任意word文档)
2、里面有些空白或者特定内容我需要用特定的内容替换。

就这么简单。
ITJaneLiu 2010-02-21
  • 打赏
  • 举报
回复
谢谢LZ了,又学到东西了.
wan766405890 2010-02-21
  • 打赏
  • 举报
回复
使用XML创建Excel文档       


原例子使用VB.Net写的,以下的用C#改写的代码

原文代码:

http://www.gotdotnet.com/Community/UserSamples/Details.aspx?SampleGuid=ddbaecb9-a260-4656-9f22-300b6a1ce66c

本例使用XML来创建Excel文档,但在运行时不需要安装Excel程序。

DataSet mDSData = new DataSet();
mDSData.Tables.Add("myTable");

mDSData.Tables["myTable"].Columns.Add("ID");
mDSData.Tables["myTable"].Columns.Add("Name");
mDSData.Tables["myTable"].Columns.Add("PassWord");

for (int i = 0; i < 10; i++)
{
DataRow dr = mDSData.Tables["myTable"].NewRow();
dr["ID"] = i;
dr["Name"] = i;
dr["PassWord"] = i;
mDSData.Tables["myTable"].Rows.Add(dr);
}

SaveFileDialog dialog1 = new SaveFileDialog();
dialog1.AddExtension = true;
dialog1.CheckPathExists = true;
dialog1.Filter = "Excel Workbooks (*.xls) | *.xls";
dialog1.OverwritePrompt = true;
dialog1.Title = "Save Excel Formatted Report";
if (dialog1.ShowDialog() == DialogResult.OK)
{
int num2 = 0;
int num3 = mDSData.Tables[0].Rows.Count + 1;
int num1 = mDSData.Tables[0].Columns.Count;
num2 = 0;
string text1 = dialog1.FileName;
if (File.Exists(text1))
{
File.Delete(text1);
}
StreamWriter writer1 = new StreamWriter(text1, false);
StreamWriter writer2 = writer1;
writer2.WriteLine("<?xml version=\"1.0\"?>");
writer2.WriteLine("<?mso-application progid=\"Excel.Sheet\"?>");
writer2.WriteLine("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"");
writer2.WriteLine(" xmlns:o=\"urn:schemas-microsoft-com:office:office\"");
writer2.WriteLine(" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"");
writer2.WriteLine(" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"");
writer2.WriteLine(" xmlns:html=\"http://www.w3.org/TR/REC-html40\">");
writer2.WriteLine(" <DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">");
writer2.WriteLine(" <Author>Automated Report Generator Example</Author>");
writer2.WriteLine(string.Format(" <Created>{0}T{1}Z</Created>", DateTime.Now.ToString("yyyy-mm-dd"), DateTime.Now.ToString("HH:MM:SS")));
writer2.WriteLine(" <Company>Your Company Here</Company>");
writer2.WriteLine(" <Version>11.6408</Version>");
writer2.WriteLine(" </DocumentProperties>");
writer2.WriteLine(" <ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">");
writer2.WriteLine(" <WindowHeight>8955</WindowHeight>");
writer2.WriteLine(" <WindowWidth>11355</WindowWidth>");
writer2.WriteLine(" <WindowTopX>480</WindowTopX>");
writer2.WriteLine(" <WindowTopY>15</WindowTopY>");
writer2.WriteLine(" <ProtectStructure>False</ProtectStructure>");
writer2.WriteLine(" <ProtectWindows>False</ProtectWindows>");
writer2.WriteLine(" </ExcelWorkbook>");
writer2.WriteLine(" <Styles>");
writer2.WriteLine(" <Style ss:ID=\"Default\" ss:Name=\"Normal\">");
writer2.WriteLine(" <Alignment ss:Vertical=\"Bottom\"/>");
writer2.WriteLine(" <Borders/>");
writer2.WriteLine(" <Font/>");
writer2.WriteLine(" <Interior/>");
writer2.WriteLine(" <Protection/>");
writer2.WriteLine(" </Style>");
writer2.WriteLine(" <Style ss:ID=\"s21\">");
writer2.WriteLine(" <Alignment ss:Vertical=\"Bottom\" ss:WrapText=\"1\"/>");
writer2.WriteLine(" </Style>");
writer2.WriteLine(" </Styles>");
writer2.WriteLine(" <Worksheet ss:Name=\"MyReport\">");
writer2.WriteLine(string.Format(" <Table ss:ExpandedColumnCount=\"{0}\" ss:ExpandedRowCount=\"{1}\" x:FullColumns=\"1\"", num1.ToString(), num3.ToString()));
writer2.WriteLine(" x:FullRows=\"1\">");
foreach (DataRow row1 in mDSData.Tables[0].Rows)
{
writer2.WriteLine("<Row>");
for (num2 = 0; num2 != num1; num2++)
{
writer2.Write("<Cell ss:StyleID=\"s21\"><Data ss:Type=\"String\">");
writer2.Write(row1[num2].ToString());
writer2.WriteLine("</Data></Cell>");
}
writer2.WriteLine("</Row>");
}
writer2.WriteLine(" </Table>");
writer2.WriteLine(" <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">");
writer2.WriteLine(" <Selected/>");
writer2.WriteLine(" <Panes>");
writer2.WriteLine(" <Pane>");
writer2.WriteLine(" <Number>3</Number>");
writer2.WriteLine(" <ActiveRow>1</ActiveRow>");
writer2.WriteLine(" </Pane>");
writer2.WriteLine(" </Panes>");
writer2.WriteLine(" <ProtectObjects>False</ProtectObjects>");
writer2.WriteLine(" <ProtectScenarios>False</ProtectScenarios>");
writer2.WriteLine(" </WorksheetOptions>");
writer2.WriteLine(" </Worksheet>");
writer2.WriteLine(" <Worksheet ss:Name=\"Sheet2\">");
writer2.WriteLine(" <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">");
writer2.WriteLine(" <ProtectObjects>False</ProtectObjects>");
writer2.WriteLine(" <ProtectScenarios>False</ProtectScenarios>");
writer2.WriteLine(" </WorksheetOptions>");
writer2.WriteLine(" </Worksheet>");
writer2.WriteLine(" <Worksheet ss:Name=\"Sheet3\">");
writer2.WriteLine(" <WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">");
writer2.WriteLine(" <ProtectObjects>False</ProtectObjects>");
writer2.WriteLine(" <ProtectScenarios>False</ProtectScenarios>");
writer2.WriteLine(" </WorksheetOptions>");
writer2.WriteLine(" </Worksheet>");
writer2.WriteLine("</Workbook>");
writer2 = null;
writer1.Close();
MessageBox.Show("Report Created", "Success", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}



wan766405890 2010-02-21
  • 打赏
  • 举报
回复
为什么要用组件呢word实际上就是特定xml格式的二进制流,你通过这种格式写xml再写二进制不就行了!
mouse791020 2010-02-21
  • 打赏
  • 举报
回复
引用 5 楼 jason_dct 的回复:
哦 ?
你把文件的读写权限全部开放 --修改成 完全控制。
用户 拥有管理员权限。  试试。
也有可能是安全级别太高了。


已经打开了everyone权限了,应该不是这个问题吧
ZHOUGE 2010-02-20
  • 打赏
  • 举报
回复
我觉得应该考虑这几个问题: 1.是否有安装OFFICE-WORD;2.是否成功引用了组件;3.asp.net用户权限是否有开放。
guyehanxinlei 2010-02-20
  • 打赏
  • 举报
回复
注意一下组件权限问题。
段传涛 2010-02-20
  • 打赏
  • 举报
回复
哦 ?
你把文件的读写权限全部开放 --修改成 完全控制。
用户 拥有管理员权限。 试试。
也有可能是安全级别太高了。
mouse791020 2010-02-20
  • 打赏
  • 举报
回复
引用 3 楼 wuyq11 的回复:
int i=0,iCount=0;
Word.Find wfnd;
if (wd.Paragraphs!=null && wd.Paragraphs.Count>0)
{
iCount=wd.Paragraphs.Count;
for(i=1;i <=iCount;i++)
{
wfnd=wd.Paragraphs[i].Range.Find;
wfnd.ClearFormatting();
wfnd.Text=strKey;
if (wfnd.Execute(ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue))
{
MessageBox.Show("文档中包含指定的关键字!","搜索结果",MessageBoxButtons.OK);
break;
}
}
}

使用书签替换数据


我刚刚试过了,到wfnd.Text=strKey这句同样提示内存不可读,内存已经损坏。

我觉得还是权限的问题的。

word我装了,07的,组件已经引用了,否则打开文件就该报错,应该也不会有问题,最后那个权限的问题倒是没有看过,不知道该怎么开?

我的是win7
wuyq11 2010-02-20
  • 打赏
  • 举报
回复
int i=0,iCount=0;
Word.Find wfnd;
if (wd.Paragraphs!=null && wd.Paragraphs.Count>0)
{
iCount=wd.Paragraphs.Count;
for(i=1;i <=iCount;i++)
{
wfnd=wd.Paragraphs[i].Range.Find;
wfnd.ClearFormatting();
wfnd.Text=strKey;
if (wfnd.Execute(ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue,ref MissingValue,
ref MissingValue))
{
MessageBox.Show("文档中包含指定的关键字!","搜索结果",MessageBoxButtons.OK);
break;
}
}
}

使用书签替换数据

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧