我在我的表單中有一個DataGridView
。我想要做的是如果用戶選擇一行並按Button(button_1)
應將來自該行的數據發送到word文檔並根據column[i]
替換數字。 現在的代碼如下
問題1當我選擇一行並單擊按鈕時,數據發現並替換了Word文件中的數字,但它取代了所有例如「1」的出現,但我只希望它是做了一次,因爲我想爲每一行做它。 問題2如果用戶選擇多於一行,則僅導出最後選擇的行數據。有任何想法嗎??C#導出datagridview選定的行到Word
private void button1_Click(object sender, EventArgs e)
{
string SendPath = "";
if (openFileDialogWord.ShowDialog(this) == DialogResult.OK)
{
SendPath = (openFileDialogWord.InitialDirectory + openFileDialogWord.FileName).ToString();
}
WordDoc(SendPath);
}
public void WordDoc(string getfilename)
{
object FileName = getfilename; //The filepath goes here
//Create word Application Object
Word.Application word = new Word.Application();
//Create word document Object
Word.Document doc = null;
//Create word Missing Object
object missing = System.Type.Missing;
object readOnly = false;
object isVisible = false;
// make visible Word application
word.Visible = true;
try
{
doc = word.Documents.Open(ref FileName, 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, ref missing);
doc.Activate();
string Column1;
string Column2;
foreach (DataGridViewRow rows in dataGridView1.SelectedRows)
{
Column1 = rows.Cells[1].Value.ToString();
Column2 = rows.Cells[2].Value.ToString();
this.FindAndReplace(word, "1", Column1);
this.FindAndReplace(word, "2", Column2);
}
MessageBox.Show("Complete");
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
}
private void FindAndReplace(Word.Application word, object findText, object replaceText)
{
object matchCase = true;
object matchWholeWord = true;
object matchWildCards = false;
object matchSoundsLike = false;
object matchAllWordForms = false;
object forward = true;
object format = false;
object matchKashida = false;
object matchDiacritics = false;
object matchAlefHamza = false;
object matchControl = false;
object read_only = false;
object visible = true;
object replace = 2;
object wrap = 1;
word.Selection.Find.Execute(ref findText, ref matchCase,
ref matchWholeWord, ref matchWildCards, ref matchSoundsLike,
ref matchAllWordForms, ref forward, ref wrap, ref format,
ref replaceText, ref replace, ref matchKashida,
ref matchDiacritics,
ref matchAlefHamza, ref matchControl);
}
有人???????? – user2345661 2013-05-07 14:19:27
問題屬於本部分 object replace = 2; 我在DreaminCode找到了解決方案 替換對象replace = 2;與對象替換= 1;它正在運作完美。 – user2345661 2013-05-07 16:10:18