日期:2014-05-18  浏览次数:20760 次

还有个小问题
C# code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;


namespace shangweiji
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
1:        Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
2:         Workbook wbook = app.Workbooks.Open("D:\\sun", Type.Missing);
3:         Worksheet worksheet = (Worksheet)wbook.Worksheets[1];

            worksheet.Cells[2,1] = "jiweiqiang";
            app.Visible = true;
            string temp = ((Range)worksheet.Cells[1, 2]).Text;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Workbook wbook = app.Workbooks.Open("D:\\sun", Type.Missing);
            Worksheet worksheet = (Worksheet)wbook.Worksheets[1];
            worksheet.Cells[9, 2] = "-20"; 
        }


    }
}

请问下1,2,3处的代码该放在什么地方,才能使定义的worksheet在每个事件应用程序下都能使用。现在我放在form_load下的话button_click是用不到的。
本来想放到form1()构造函数下的,可报错说不能引用非静态字段,属性和方法。
谢谢了

------解决方案--------------------
C# code


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;


namespace shangweiji
{
    public partial class Form1 : Form
    {
1:        Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
2:         Workbook wbook = app.Workbooks.Open("D:\\sun", Type.Missing);
3:         Worksheet worksheet = (Worksheet)wbook.Worksheets[1];

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            worksheet.Cells[2,1] = "jiweiqiang";
            app.Visible = true;
            string temp = ((Range)worksheet.Cells[1, 2]).Text;

        }

        private void button1_Click(object sender, EventArgs e)
        {
                        worksheet.Cells[9, 2] = "-20"; 
        }


    }
}