在Excel文件中input数字,每个button点击C#

我想制作一个包含一个TextBox和一个Button “添加”的win应用程序。 当用户input一个数字并首次点击该button时,程序将创build一个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); } 

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

有没有人对此有所了解?

您需要在buttonAdd_Click函数外部创buildExcel表格。 在函数内部,您只能访问您的工作表。

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

当你的主应用程序closures时,你可以closures你的excel应用程序,而不是像我们当前的代码那样,每次我们写一些东西到表单上。 例如,您可以使用Window.Closing事件。