我有一台可以通过套接字从客户端接收消息的服务器 使用按钮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工作表。当文件打开或关闭文件时,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
不是,有人可以帮助我吗?
何时/或无法做到。然后我希望这个值(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
答案 0 :(得分:0)
在您的情况下,有助于包含(或更确切地说,研究)实际的编译器错误:
当前上下文中不存在名称“oSheet”
您似乎使用与您要使用它的方法不同的方法声明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;
}
}