【发布时间】:2022-04-22 18:34:56
【问题描述】:
我正在尝试使用 c# 代码将一些文本写入 word 文档。但是,每当我打开文档时,它都会以只读模式打开。以下是我的代码:-
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Microsoft.Office.Interop.Word;
namespace WFA1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string textboxText = textBox1.Text.ToString();
InsertToFile(textboxText);
}
void InsertToFile(string inputString) // function to insert string to word doc
{
object missing = System.Reflection.Missing.Value;
object readOnly = false;
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc = app.Documents.Open("C:\\Users\\SS5014874\\Desktop\\JohnH.docx", ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
app.ActiveDocument.Characters.Last.Select();
app.Selection.Collapse();
app.Selection.TypeText(inputString.ToString());
app.ActiveDocument.Save();
MessageBox.Show("Inserted");
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string comboBoxText = comboBox1.Text.ToString();
string comboBoxTextExpanded = "";
if (comboBoxText == "BP")
{
comboBoxTextExpanded = "Balance paid";
}
else
{
if (comboBoxText == "FA")
{
comboBoxTextExpanded = "Financial advisor";
}
}
InsertToFile(comboBoxTextExpanded);
}
private void button2_Click(object sender, EventArgs e)
{
string searchKeyword = textBox2.Text.ToString();
searchText(searchKeyword);
}
void searchText(string txt) // function to search string and delete line
{
Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc = app.Documents.Open("C:\\Users\\SS5014874\\Desktop\\JohnH.docx");
object missing = System.Reflection.Missing.Value;
doc.Content.Find.ClearFormatting();
object keyword = txt.ToString();
var range = doc.Content;
if (range.Find.Execute(ref keyword, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing))
{
range.Expand(WdUnits.wdParagraph);
range.Delete();
MessageBox.Show("removed para");
}
else
{
MessageBox.Show("Not found");
}
//doc.Close(ref missing, ref missing, ref missing);
//app.Quit(ref missing, ref missing, ref missing);
}
}
}
你能帮我解决这个问题吗?我在app.ActiveDocument.Save(); 行发现异常@
【问题讨论】:
-
您是否尝试过使用不同的文档?确保文档本身在文件属性框中没有只读检查
-
@slayernoah- 是的,我也尝试使用新文档,但是,它们也以只读模式打开。代码第一次运行后,文档将变为只读。第一次工作。
-
保存后尝试使用
app.ActiveDocument.Close(); -
在你尝试之前,你必须去任务管理器并结束所有
winword.exe进程,因为之前的文档没有关闭。并在关闭文档后使用app.Quit(); -
这对您有帮助吗?