在excel文件中输入输入的数字,在C#中单击每个按钮

时间:2014-10-25 16:09:54

标签: c# excel

我想制作一个包含一个TextBox和一个Button'添加'的获胜应用。当用户输入一个数字并第一次单击该按钮时,程序将创建一个excel文件,然后在每次单击时按顺序在该文件中写入数字。 这是我的buttonAdd:

private void buttonAdd_Click(object sender, EventArgs e)
{
    double num1;

    Excel.Application xlApp;
    Excel.Workbook xlWorkBook;
    Excel.Worksheet xlWorkSheet;

    xlApp = new Excel.Application();
    xlWorkBook = xlApp.Workbooks.Add();
    xlWorkSheet = (Excel.Worksheet)xlWorkBook.ActiveSheet;

    num1 = Convert.ToDouble(textBox1.Text);

    xlWorkSheet.Cells[i, 1] = num1;
    i++;

    xlWorkBook.SaveAs(path);
    xlWorkBook.Close(true);
}

我知道他的代码不起作用,因为在每次单击按钮时,程序都会尝试创建具有相同路径的新excel文件。我是面向对象编程的新手,所以我不知道如何在'buttonAdd_Click'之外创建一个excel文件,并在'buttonAdd_Click'中调用它。

有没有人对此有所了解?

1 个答案:

答案 0 :(得分:1)

您需要在buttonAdd_Click功能之外创建Excel工作表。在功能内部,您只能访问您的工作表。

public partial class MainWindow : Window
{
    // Declare a private member in your MainWindow
    Excel.Application xlApp;
    Excel.Workbook xlWorkBook;
    Excel.Worksheet xlWorkSheet;

    private void buttonAdd_Click(object sender, EventArgs e)
    {
        // Assign to our private member only once, at the first button click
        if (xlWorkSheet == null)
        {
            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Add();
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.ActiveSheet;
        }

        // After the second button click, we already have a reference 
        // to a work sheet, so we can just write to it.

        xlWorkSheet.Cells[1, 1] = 10; // Just an example.

        // DON'T close the excel application here.
    }

您可以在主应用程序关闭时关闭excel应用程序,而不是在每次我们向工作表写入内容时关闭,就像您当前的代码一样。例如,您可以使用Window.Closing事件。