将字符串写入 Excel 单元格不起作用

Writing string to Excel cell doesn't work

我有一个服务器可以通过套接字从客户端接收消息。
使用按钮 1,我打开服务器以便接收字符串。然后是 ReceiveCallback:

public void ReceiveCallback(IAsyncResult AR)
{
    try
    {
        Socket socket = (Socket)AR.AsyncState;
        int received = socket.EndReceive(AR);

        if (received == 0)
        {
            return;
        }

        byte[] dataBuf = new byte[received];
        Array.Copy(BuFfer, dataBuf, received);
        string text = Encoding.ASCII.GetString(dataBuf);
        writetotextbox("Client: " + text);
        //writetoExcel(text); <<<<<<<<<-------------
        socket.BeginReceive(BuFfer, 0, BuFfer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket); //deze zorgt voor problemen
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

public void writetotextbox(string text)
{
    MethodInvoker invoker = new MethodInvoker(delegate
    {
        textBox1.Text += text + "\r\n";
    });
    this.Invoke(invoker);
}

现在我想将相同的值写入 Excel。这对我来说仍然是个问题,到目前为止我得到了这个代码:

Excel.Application Start = null;
Excel._Workbook theWorkbook = null;
Excel.Range range = null;
object misValue = System.Reflection.Missing.Value;

我用按钮 2 打开 excel sheet。excel 文件在文件打开或要关闭时接收到值时会自行刷新吗?

try
{
    Start = new Excel.Application(); 
    theWorkbook = Start.Workbooks.Add(misValue);
    theWorkbook = Start.Workbooks.Open(@"C:\Users\Name\Downloads\Map1.xlsx", misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
    Excel._Worksheet oSheet =     (Excel._Worksheet)theWorkbook.Worksheets.get_Item(1);
    string strWorksheetName = oSheet.Name;
    oSheet.Cells[1, 1] = "Hello";
    oSheet.get_Range("A1", "Z1").Font.Bold = true;
    Start.Visible = true;
    Start.UserControl = true;
}
catch (Exception theException)
{
    MessageBox.Show(errorMessage, "Error");
}

public void writetoExcel(string text)
{
      oSheet.Cells[1, 2] = text; // <-- doenst work, i get an error
}                 //oSheet is not working.

单个程序有效,组合有效,但 writetoExcel 无效,有人可以帮我吗?

When/or这是不可能的。然后我想要那个值(a,b 只是我收到的一封信)进入这样的开关:

switch (text)
{
    case "a":
    oSheet.Cells[1, 2] = "Kees";
    break;
    case "b":
    oSheet.Cells[2, 2] = "piet";
    break;
} //and ofcourse write the string to excel

它有助于包括(或者更确切地说,研究)实际的编译器错误,在你的情况下:

The name 'oSheet' does not exist in the current context

您声明 Excel._Worksheet oSheet 的方法似乎与您要使用它的方法不同。

您可以将其设为表单上的一个字段并在第一种方法中分配它:

public partial class YourForm : Form
{
    private Excel._Worksheet oSheet;

    private void SomeMethod()
    {
        oSheet = (Excel._Worksheet)theWorkbook.Worksheets.get_Item(1);
    }

    public void writetoExcel(string text)
    {
      oSheet.Cells[1, 2] = text;
    }

}