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