0

I wrote a C# winforms program which opens an excel spreadsheet and writes integer value "total" into a cell (I9 in this case). Is there any way I can choose a cell in the spreadsheet and write my integer value in the now active cell?

Here is the code pertaining to my question:

    private static Excel.Workbook MyBook = null;
    private static Excel.Application excelApp = null;
    private static Excel.Worksheet MySheet = null;
    private void button4_Click(object sender, EventArgs e)
    {
        OpenFileDialog openb = new OpenFileDialog();
        if (openb.ShowDialog() == DialogResult.OK)
        {
            var name = openb.FileName;
            String filename = DialogResult.ToString();

            excelApp = new Excel.Application();
            excelApp.Visible = true;
            MyBook = excelApp.Workbooks.Open(name);
            MySheet = (Excel.Worksheet)MyBook.Sheets[1]; // Explicit cast is not required here
            MySheet.Cells[9, 9] = total;
            MyBook.Save();
        }
    }

1 Answers1

0

You would need a second button.

First one opens (and leaves open) the file you need, as you already have it:

private void button4_Click(object sender, EventArgs e)
{
    OpenFileDialog openb = new OpenFileDialog();
    if (openb.ShowDialog() == DialogResult.OK)
    {
        var name = openb.FileName;
        String filename = DialogResult.ToString();

        excelApp = new Excel.Application();
        excelApp.Visible = true;
    }

Second button writes the value of total in the cell the user has selected:

    private void button5_Click(object sender, EventArgs e)
    {
        if (excelApp != null && MyBook != null) //sanity check
        {
            MySheet = (Worksheet)MyBook.Sheets[1]; // Explicit cast is not required here
            MySheet.Cells[excelApp.ActiveCell.Row, excelApp.ActiveCell.Column] = total;
            MyBook.Save();
        }
    }
Josh Part
  • 2,154
  • 12
  • 15