【发布时间】:2015-02-11 09:31:27
【问题描述】:
我有一个服务器可以通过套接字从客户端接收消息。
使用按钮 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
【问题讨论】:
标签: c# string server export-to-excel read-write