2
我想用c#代码将一些文本写入word文档。但是,无论何时打开文档,它都以只读模式打开。以下是我的代码: -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
@ slayernoah-中没有只读检查。是的,我也尝试过使用新文档,但是,这些文档也以只读模式打开。一旦代码第一次运行,之后,文档将变为只读。这是它第一次运作。 – Sourav
尝试使用'app.ActiveDocument.Close();'在尝试之前保存它 – slayernoah