使用c#写入电子表格活动单元格

时间:2017-12-26 22:00:31

标签: c# excel winforms ms-office

我写了一个C#winforms程序,打开一个excel电子表格并写入整数值" total"进入一个单元格(在这种情况下为I9)。有没有什么办法可以在电子表格中选择一个单元格并在现在活动的单元格中写下我的整数值?

以下是与我的问题有关的代码:

    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 个答案:

答案 0 :(得分:0)

你需要第二个按钮。

首先打开(并打开)您需要的文件,就像您已经拥有的那样:

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;
    }

第二个按钮在用户选择的单元格中写入total的值:

    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();
        }
    }