我的表格中有一个DataGridView
。我要做的是,如果用户选择一行并按下Button(button_1)
该行中的数据,则应将其发送到 word 文档并根据column[i]
. 现在使用
问题 1下面的代码, 当我选择一行并单击按钮时,数据会在 Word 文件中查找并替换数字,但它会替换所有出现的例如“1”,但我只希望它执行一次,因为我想要为每一行做。
问题 2如果用户选择多于一行,则仅导出最后选择的行数据。有任何想法吗??
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);
}