public void ServerStart2() { Trace.WriteLine("------------------------进入ServerStart2"); ClientAPP.ClientUSRP_Telemetry.ClientIP = ConfigurationManager.AppSettings["Client_USRP_Ip"]; ServerOn_YC = true; ClientAPP.ClientUSRP_Telemetry.IsConnected = false; ServerPort2 = int.Parse(ConfigurationManager.AppSettings["LocalPort1_YC"]); ServerSocket2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress address2 = IPAddress.Parse(ConfigurationManager.AppSettings["LocalIP1"]); try { ServerSocket2.Bind(new IPEndPoint(address2, ServerPort2)); ServerSocket2.Listen(10); ServerSocket2.BeginAccept(new AsyncCallback(onCall_telemetry), ServerSocket2); } catch (Exception ex) { MyLog.Error("启动<--遥测<--服务器监听USRP线程失败,检查IP设置和网络连接"); Trace.WriteLine(ex.Message); ServerOn_YC = false; } Trace.WriteLine("------------------------退出ServerStart2"); }
public void ServerStop() { Trace.WriteLine("------------------------进入ServerStop"); ServerOn = false; Data.USRP_telecmd_IsConnected = false; ClientAPP.ClientUSRP_Telecmd.IsConnected = false; Data.ServerConnectEvent.Set(); try { ServerSocket.Close(); foreach (var sock in ClientSocketList) { if (sock.Connected) { sock.Shutdown(SocketShutdown.Both); sock.Close(); } } } catch (Exception ex) { MyLog.Error("ServerStop无法关闭,错误原因:" + ex.Message); } Trace.WriteLine("------------------------退出ServerStop"); }
private void btn_SendYC_Click(object sender, EventArgs e) { string Str_Content = this.textBox1.Text.Replace(" ", ""); int AddAlen = 16 - (Str_Content.Length % 16); Str_Content = Str_Content.PadRight(AddAlen, 'A'); Trace.WriteLine("遥控发送数据:" + Str_Content); byte[] temp = StrToHexByte(Str_Content); if (temp.Length == 35) { DataRow dr = Data.dtYKLog.NewRow(); dr["发送时间"] = string.Format("{0}-{1:D2}-{2:D2} {3:D2}:{4:D2}:{5:D2}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); dr["遥控名称"] = label_ykname.Text; dr["遥控源码"] = Str_Content; if (Data.USRP_telecmd_IsConnected) { dr["发送结果"] = "发送成功"; Data.DataQueue_USRP_telecmd.Enqueue(temp); } else { dr["发送结果"] = "发送失败,网络未连接"; } Data.dtYKLog.Rows.Add(dr); } else { //MessageBox.Show("遥控指令格式错误,无法发送!!"); MyLog.Error("遥控指令格式错误,无法发送!!"); } }
public void ServerStart() { Trace.WriteLine("------------------------进入ServerStart"); ClientAPP.ClientUSRP_Telecmd.ClientIP = ConfigurationManager.AppSettings["Client_USRP_Ip"]; ServerOn = true; ClientAPP.ClientUSRP_Telecmd.IsConnected = false; // new Thread(() => { WhichZKOn(); }).Start(); ServerPort = int.Parse(ConfigurationManager.AppSettings["LocalPort1_YK"]); ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress address = IPAddress.Parse(ConfigurationManager.AppSettings["LocalIP1"]); try { ServerSocket.Bind(new IPEndPoint(address, ServerPort)); ServerSocket.Listen(10); ServerSocket.BeginAccept(new AsyncCallback(onCall_telecmd), ServerSocket);//继续接受其他客户端的连接 } catch (Exception ex) { MyLog.Error("启动-->遥控-->服务器监听USRP线程失败,检查IP设置和网络连接"); Trace.WriteLine(ex.Message); ServerOn = false; } Trace.WriteLine("------------------------退出ServerStart"); }
/// <summary> /// 在收到总控的K令数据包时,根据K令号获得K令实际内容 /// </summary> /// <param name="j"></param> /// <param name="ch"></param> /// <returns></returns> public static string Get_KcmdText(int j, ref byte[] ch) { byte[] temp = new byte[5]; try { temp[0] = Data.KcmdText[4 * (j - 1)]; temp[1] = Data.KcmdText[4 * (j - 1) + 1]; temp[2] = Data.KcmdText[4 * (j - 1) + 2]; temp[3] = Data.KcmdText[4 * (j - 1) + 3]; } catch (Exception ex) { MyLog.Error("执行本地发送K令失败,未加载K令码表" + ex.Message); return("Error"); } ch[0] = temp[0]; ch[1] = (byte)((temp[1] & 0xf0) + ((temp[2] & 0xf0) >> 4)); ch[2] = (byte)(((temp[2] & 0x0f) << 4) + ((temp[3] & 0xf0) >> 4)); ch[3] = ch[0]; ch[4] = ch[1]; ch[5] = ch[2]; ch[6] = ch[0]; ch[7] = ch[1]; ch[8] = ch[2]; string KcmdStr = null; for (int i = 0; i < 9; i++) { KcmdStr += ch[i].ToString("x2"); } return(KcmdStr); }
private void listView1_DoubleClick(object sender, EventArgs e) { System.Windows.Forms.ListView lw = (System.Windows.Forms.ListView)sender; try { string filename = lw.FocusedItem.SubItems[1].Text; System.Diagnostics.Process.Start(filename); } catch { MyLog.Error("openfile err"); //textBox.Text += "openfile err\r\n"; return; } }
private void btn_addlist_Click(object sender, EventArgs e) { TreeNode node; string type = "False"; switch (comboBox1.Text) { case "常用指令": node = node1; type = "Normal"; break; case "重要指令": node = node2; type = "Important"; break; case "其它指令": node = node3; type = "Other"; break; default: node = node3; type = "False"; break; } string str = textBox1.Text.Replace(" ", ""); if (str.Length == 70 && comboBox1.Text != "False" && textBox3.Text != "") { DialogResult dr = MessageBox.Show(this, "是否确定添加:" + comboBox1.Text + ":" + textBox3.Text + ":" + textBox1.Text, "添加自定义指令", MessageBoxButtons.YesNo); if (dr == DialogResult.Yes) { node.Nodes.Add(new TreeNode(textBox3.Text)); Data.SaveConfigStr(Data.YKconfigPath, type, textBox3.Text, "value", textBox1.Text); } else { } } else { // MessageBox.Show(this, "自定义指令长度或名称错误,无法添加!", "错误提示", MessageBoxButtons.YesNo); MyLog.Error("自定义指令长度或名称错误,无法添加!"); } }
private void button1_Click(object sender, EventArgs e) { ListViewItem item; ListViewItem.ListViewSubItem subitem1; ListViewItem.ListViewSubItem subitem2; listView1.Items.Clear(); string path = Program.GetStartupPath() + comboBox1.Text; switch (comboBox1.Text) { case "接收": path += "\\" + comboBox2.Text + "\\Telemetry"; break; case "发送": path += "\\" + comboBox2.Text + "\\Telecmd"; break; default: break; } DirectoryInfo folder = new DirectoryInfo(path); try { foreach (FileInfo file in folder.GetFiles("*.*")) { item = new ListViewItem(); item.Text = file.Name; subitem1 = new ListViewItem.ListViewSubItem(); subitem1.Text = file.FullName; item.SubItems.Add(subitem1); subitem2 = new ListViewItem.ListViewSubItem(); subitem2.Text = file.Length.ToString(); item.SubItems.Add(subitem2); listView1.Items.Add(item); } } catch (Exception ex) { MyLog.Error(ex.Message); } }
//----------设置系统时间---------- public static void Set_Time(byte[] data) { try { byte[] gettime = new byte[23]; for (int datai = 0; datai < data.Length; datai++) { gettime[datai] = byte.Parse(data[datai].ToString()); } string dt_str = Encoding.ASCII.GetString(gettime); string str = dt_str.Substring(0, 4); SystemTime systime = new SystemTime(); systime.vYear = ushort.Parse(str); str = dt_str.Substring(5, 2); systime.vMonth = ushort.Parse(str); str = dt_str.Substring(8, 2); systime.vDay = ushort.Parse(str); str = dt_str.Substring(11, 2); systime.vHour = ushort.Parse(str); str = dt_str.Substring(14, 2); systime.vMinute = ushort.Parse(str); str = dt_str.Substring(17, 2); systime.vSecond = ushort.Parse(str); str = dt_str.Substring(20, 3); systime.vMilliseconds = ushort.Parse(str); //--------更改系统时间-------- SetLocalTime(ref systime); } catch { MyLog.Error("设置系统时间失败!"); } }
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { comboBox2.Enabled = true; switch (comboBox1.Text) { case "接收": comboBox2.Items.Clear(); comboBox2.Items.Add("USRP"); comboBox2.SelectedIndex = 0; break; case "发送": comboBox2.Items.Clear(); comboBox2.Items.Add("USRP"); comboBox2.SelectedIndex = 0; break; default: MyLog.Error("查询条件无效,无法查询文件"); break; } }
/// <summary> /// 接受USRP的遥测数据 /// </summary> /// <param name="ClientSocket"></param> private void RecvFromClientUSRP(object ClientSocket) { Trace.WriteLine("RecvFromUSRP_telemetry!!"); Socket myClientSocket = (Socket)ClientSocket; while (ServerOn_YC && myClientSocket.Connected) { try { byte[] RecvBufZK1 = new byte[2048]; int RecvNum = myClientSocket.Receive(RecvBufZK1); if (RecvNum > 0) { String tempstr = ""; byte[] RecvBufToFile = new byte[RecvNum]; for (int i = 0; i < RecvNum; i++) { RecvBufToFile[i] = RecvBufZK1[i]; tempstr += RecvBufZK1[i].ToString("x2"); } Trace.WriteLine(tempstr); string timestr = string.Format("{0}-{1:D2}-{2:D2} {3:D2}:{4:D2}:{5:D2}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); Data.TelemetryRealShowBox.BeginInvoke( new Action(() => { Data.TelemetryRealShowBox.AppendText(timestr + "\n" + tempstr + "\n"); })); //存储从USRP发来的遥测数据 SaveFile.DataQueue_out1.Enqueue(RecvBufToFile); //数据库存储 IPEndPoint tmppoint = (IPEndPoint)myClientSocket.RemoteEndPoint; String RemoteIpStr = tmppoint.Address.ToString(); if (RecvNum > 22) { MyLog.Info("收到遥测数据量:" + RecvNum.ToString()); try { deal_zk_data(RecvBufZK1, RecvNum, timestr, RemoteIpStr); } catch (Exception e) { Trace.WriteLine("RecvFromClientZK_YC--deal_zk_data Exception:" + e.Message); } Data.dtUSRP.Rows[0][1] = (int)Data.dtUSRP.Rows[0][1] + 1; } else { MyLog.Error("收到遥测数据帧长度异常:" + RecvNum.ToString()); } } else { Trace.WriteLine("收到数据少于等于0!"); break; } } catch (Exception e) { Trace.WriteLine("RecvFromClientZK_YC Exception:" + e.Message); if (myClientSocket.Connected) { myClientSocket.Shutdown(SocketShutdown.Both); myClientSocket.Close(); } ClientAPP.ClientUSRP_Telemetry.IsConnected = false; break; } } if (myClientSocket.Connected) { Trace.WriteLine("服务器主动关闭socket!"); myClientSocket.Shutdown(SocketShutdown.Both); myClientSocket.Close(); } ClientAPP.ClientUSRP_Telemetry.IsConnected = false; Trace.WriteLine("leave Server YC!!"); Data.ServerConnectEvent2.Set(); }
private void DisPatchEpdu() {//根据APID分配EPDU while (Data.AllThreadTag) { if (Data.EpduBuf_List.Count > 6) { int epdu_len = Data.EpduBuf_List[4] * 256 + Data.EpduBuf_List[5]; if (epdu_len < 1024)//避免出现异常情况时,由于epdu_len长度太长一直不处理 { int epdu_apid = (int)((Data.EpduBuf_List[0] & 0x07) << 8) + (int)Data.EpduBuf_List[1]; string epdu_APID = "0x" + epdu_apid.ToString("x3"); bool NeedClearTag = true;//若List头位置不是合理的APID,则清空List foreach (DataRow dr in Data.dtAPID.Rows) { if ((string)dr["APID"] == epdu_APID) { NeedClearTag = false; break; } } if (NeedClearTag) { MyLog.Error("不连续EPDU检测到,清空缓存"); lock (Data.EpduBuf_List) { Data.EpduBuf_List.Clear(); } } //////alter by cz lock (Data.EpduBuf_List) { if (Data.EpduBuf_List.Count >= epdu_len + 7) { byte[] Epdu_Frame = new byte[epdu_len + 7]; Data.EpduBuf_List.CopyTo(0, Epdu_Frame, 0, epdu_len + 7); Data.EpduBuf_List.RemoveRange(0, epdu_len + 7); #region 处理EPDU string Version = Convert.ToString(Epdu_Frame[0], 2).PadLeft(8, '0').Substring(0, 3); string Type = Convert.ToString(Epdu_Frame[0], 2).PadLeft(8, '0').Substring(3, 1); string DataTag = Convert.ToString(Epdu_Frame[0], 2).PadLeft(8, '0').Substring(4, 1); int apid = (int)((Epdu_Frame[0] & 0x07) << 8) + (int)Epdu_Frame[1]; string APID = "0x" + apid.ToString("x3"); string DivTag = Convert.ToString(Epdu_Frame[2], 2).PadLeft(8, '0').Substring(0, 2); int bagcount = (int)((Epdu_Frame[2] & 0x3f) << 8) + (int)Epdu_Frame[3]; string BagCount = "0x" + apid.ToString("x3"); string BagLen = "0x" + Epdu_Frame[4].ToString("x2") + Epdu_Frame[5].ToString("x2"); String DataStr = ""; for (int i = 6; i < epdu_len + 1; i++) { DataStr += Epdu_Frame[i].ToString("x2"); } string timestr = string.Format("{0}-{1:D2}-{2:D2} {3:D2}:{4:D2}:{5:D2}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); Data.sql.InsertValues("table_Epdu", new string[] { "EPDU", timestr, Version, Type, DataTag, APID, DivTag, BagCount, BagLen, DataStr }); Trace.WriteLine("DealEpdu---APID-------" + APID); foreach (DataRow dr in Data.dtAPID.Rows)/// { if ((string)dr["APID"] == APID) { dr["数量"] = (int)dr["数量"] + 1; foreach (Data.APID_Struct item in Data.ApidList) { if (item.apidName == (string)dr["名称"]) { item.apidForm.DataQueue.Enqueue(Epdu_Frame); } } } } #endregion 处理EPDU } } Thread.Sleep(1); } else { lock (Data.EpduBuf_List) { Data.EpduBuf_List.Clear(); } } } else { Thread.Sleep(1); } } }
void DealCRT_Off(ref Data.CRT_STRUCT myCRT) { myCRT.LedOff(); MyLog.Error("无法连接--" + myCRT.CRTName); }
private void DealWithEPDU() { while (Data.AllThreadTag) { if (DataQueue.Count > 0) { byte[] Epdu = DataQueue.Dequeue(); //string timestr = string.Format("{0}-{1:D2}-{2:D2} {3:D2}:{4:D2}:{5:D2}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); //string epdustr = null; //for (int i = 0; i < Epdu.Length; i++) //{ // epdustr += Epdu[i].ToString("x2"); //} if ((Epdu.Length - 6) < TotalLen) { //MessageBox.Show(CurrentApidName + "收到EPDU长度错误,无法解析!!"); MyLog.Error("收到EPDU长度错误,无法解析!!"); } else { string tempstr = "";//将EPDU转化为二进制string for (int i = 6; i < Epdu.Length; i++) { tempstr += Convert.ToString(Epdu[i], 2).PadLeft(8, '0'); } Trace.WriteLine(tempstr.Length); string[] TempStringList = new string[dtAPid.Rows.Count + 1]; string timestr = string.Format("{0}-{1:D2}-{2:D2} {3:D2}:{4:D2}:{5:D2}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); TempStringList[0] = timestr; string[] TempStringList2 = new string[dtAPid.Rows.Count + 1]; TempStringList2[0] = timestr; for (int j = 0; j < dtAPid.Rows.Count; j++) { int len = int.Parse((string)dtAPid.Rows[j]["占位"]); long t = Convert.ToInt64(tempstr.Substring(0, len), 2); int padleft = int.Parse((string)dtAPid.Rows[j]["占位"]); if (padleft == 8 || padleft == 16 || padleft == 32 || padleft == 48) { padleft = 2 * (padleft / 8); } else { padleft = 2 * (padleft / 8) + 2; } string initialvalue = "0x" + t.ToString("x").PadLeft(padleft, '0'); dtAPid.Rows[j]["值"] = initialvalue; ///////////////////////////////////////////////////// string typestr = Data.GetConfigStr(Data.APIDconfigPath, CurrentApidName, (string)dtAPid.Rows[j]["名称"], "fmul"); string analystr = Data.GetAnalystr(typestr, initialvalue); ////////////////////////////////////////////////////////////////// dtAPid.Rows[j]["解析值"] = analystr; tempstr = tempstr.Substring(len, tempstr.Length - len); TempStringList[j + 1] = (string)dtAPid.Rows[j]["值"]; TempStringList2[j + 1] = (string)dtAPid.Rows[j]["解析值"]; } Data.sql.InsertValues("table_" + CurrentApidName + "_源码", TempStringList); Data.sql.InsertValues("table_" + CurrentApidName + "_解析值", TempStringList2); } //int index = this.dataGridView_EPDU.Rows.Add(); //this.dataGridView_EPDU.Rows[index].Cells[0].Value = timestr; //this.dataGridView_EPDU.Rows[index].Cells[1].Value = epdustr; } else { Thread.Sleep(500); } } }
private void DealWithEPDU() { while (Data.AllThreadTag) { if (DataQueue.Count > 0) { byte[] Epdu = DataQueue.Dequeue(); try { if ((Epdu.Length - 6) < TotalLen) { MessageBox.Show(CurrentApidName + "收到EPDU长度错误,无法解析!!"); } else { string tempstr = "";//将EPDU转化为二进制string for (int i = 6; i < Epdu.Length; i++) { tempstr += Convert.ToString(Epdu[i], 2).PadLeft(8, '0'); } Trace.WriteLine(tempstr.Length); string[] TempStringList = new string[dtAPid.Rows.Count + 1]; string timestr = string.Format("{0}-{1:D2}-{2:D2} {3:D2}:{4:D2}:{5:D2}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); TempStringList[0] = timestr; for (int j = 0; j < dtAPid.Rows.Count; j++) { int len = int.Parse((string)dtAPid.Rows[j]["占位"]); long t = Convert.ToInt64(tempstr.Substring(0, len), 2); int padleft = int.Parse((string)dtAPid.Rows[j]["占位"]); if (padleft == 8 || padleft == 16 || padleft == 32 || padleft == 48) { padleft = 2 * (padleft / 8); } else { padleft = 2 * (padleft / 8) + 2; } dtAPid.Rows[j]["值"] = "0x" + t.ToString("x").PadLeft(padleft, '0'); dtAPid.Rows[j]["解析值"] = "0x" + t.ToString("x").PadLeft(padleft, '0'); tempstr = tempstr.Substring(len, tempstr.Length - len); TempStringList[j + 1] = (string)dtAPid.Rows[j]["值"]; } Data.sql.InsertValues("table_" + CurrentApidName, TempStringList); } } catch (Exception ex) { MyLog.Error("DealWithEPDU:" + ex.Message); } } else { Thread.Sleep(100); } } }
private void Fun_RecvFromCRT_Return(ref Data.CRT_STRUCT myCRT, ref ClientAPP.TCP_STRUCT Server_CRT) { Trace.WriteLine("++++++++++Entering" + myCRT.CRTName + "Fun_RecvFromCRT_Return!!"); while (Server_CRT.IsConnected) { try { byte[] RecvBufCRTa = new byte[1092]; int RecvNum = Server_CRT.sck.Receive(RecvBufCRTa); if (RecvNum > 0) { //TempRecvBuf 本次收到的数据 byte[] TempRecvBuf = new byte[RecvNum]; Array.Copy(RecvBufCRTa, TempRecvBuf, RecvNum); SaveFile.Lock_Dat3.EnterWriteLock(); SaveFile.DataQueue_out3.Enqueue(TempRecvBuf); SaveFile.Lock_Dat3.ExitWriteLock(); String tempstr = ""; for (int i = 0; i < TempRecvBuf.Length; i++) { tempstr += TempRecvBuf[i].ToString("x2"); } //Trace.WriteLine("Recvd:" + RecvNum.ToString() + ":" + tempstr); //this.textBox_SCShow.BeginInvoke( // new Action(() => // { // if (textBox_SCShow.Lines.Count() > 10) // textBox_SCShow.Clear(); // textBox_SCShow.AppendText(tempstr + "\n"); // } // ) // ); try { Data.dtYC.Rows[0]["数量"] = (int)Data.dtYC.Rows[0]["数量"] + 1; //收到总数 } catch (Exception ex) { MyLog.Error(ex.Message); } if (RecvNum > 68) { //YCBuf 本次收到的实际遥测数据 byte[] YCBuf = new byte[RecvNum - 68]; Array.Copy(RecvBufCRTa, 64, YCBuf, 0, RecvNum - 68); SaveFile.Lock_Dat4.EnterWriteLock(); SaveFile.DataQueue_out4.Enqueue(YCBuf); SaveFile.Lock_Dat4.ExitWriteLock(); String tempstr2 = ""; for (int i = 0; i < YCBuf.Length; i++) { tempstr2 += YCBuf[i].ToString("x2"); } // Trace.WriteLine(tempstr2); //ushort CRC = 0xffff; //ushort genpoly = 0x1021; //for (int i = 0; i < YCBuf.Length-2; i = i + 1) //{ // CRC = Function.CRChware(YCBuf[i], genpoly, CRC); //} //// MyLog.Info("Calc 通道1 CRC = " + CRC.ToString("x4")); //Trace.WriteLine("Calc 通道1 CRC = " + CRC.ToString("x4")); } } else { Trace.WriteLine("收到数据少于等于0!"); break; } } catch (Exception e) { Trace.WriteLine(e.Message); break; } } Trace.WriteLine("----------Leaving" + myCRT.CRTName + "Fun_RecvFromCRT_Return!!"); }
private void button1_Click(object sender, EventArgs e) { string TableName = "table_Telemetry"; switch (comboBox1.Text) { case "接收遥测VCDU": TableName = "table_Telemetry"; break; case "解析EPDU": TableName = "table_Epdu"; break; case "发送遥控": TableName = "table_Telecmd"; break; default: TableName = comboBox1.Text; break; } //select * from table_All where CreateTime >= '2018-03-23 17:07:19' and CreateTime < '2019-08-02 00:00:00' string Str_Condition_time = "CreateTime >= '" + dateTimePicker1.Value.ToString("yyyy-MM-dd HH:mm:ss") + "'" + "and CreateTime <= '" + dateTimePicker2.Value.ToString("yyyy-MM-dd HH:mm:ss") + "'"; string Str_Conditon1 = ""; if (textBox2.Text != null && textBox2.Text.Length >= 4) { string TypedStr = textBox2.Text; string[] list = TypedStr.Split('='); Str_Conditon1 = "and " + list[0] + " = " + "'" + list[1] + "'"; } string Str_Conditon2 = ""; if (textBox3.Text != null && textBox3.Text.Length >= 4) { string TypedStr = textBox3.Text; string[] list = TypedStr.Split('='); Str_Conditon2 = "and " + list[0] + " = " + "'" + list[1] + "'"; } try { SQLiteConnection dbConnection = new SQLiteConnection("data source=mydb.db"); string cmd = "Select * From " + TableName + " where " + Str_Condition_time + Str_Conditon1 + Str_Conditon2; Trace.WriteLine(cmd); SQLiteDataAdapter mAdapter = new SQLiteDataAdapter(cmd, dbConnection); DataTable mTable = new DataTable(); // Don't forget initialize! mAdapter.Fill(mTable); // 绑定数据到DataGridView dataGridView1.DataSource = mTable; dataGridView1.Columns[0].Width = 50; dataGridView1.Columns[dataGridView1.ColumnCount - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; dataGridView1.Columns[1].Width = 150; } catch (Exception ex) { MessageBox.Show("输入的条件不符合格式,请重新输入!"); MyLog.Error(ex.Message); } }
private void button2_Click(object sender, EventArgs e) { string fileName = ""; string saveFileName = ""; SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.DefaultExt = "xlsx"; saveDialog.Filter = "Excel文件|*.xlsx"; saveDialog.FileName = fileName; String Path = Program.GetStartupPath() + @"数据库导出\"; if (!Directory.Exists(Path)) { Directory.CreateDirectory(Path); } saveDialog.InitialDirectory = Path; saveDialog.ShowDialog(); saveFileName = saveDialog.FileName; if (saveFileName.IndexOf(":") < 0) { return; //被点了取消 } Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null) { //MessageBox.Show("无法创建Excel对象,您的电脑可能未安装Excel"); MyLog.Error("无法创建Excel对象,您的电脑可能未安装Excel"); return; } Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks; Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; //取得sheet1 //写入标题 for (int i = 0; i < dataGridView1.ColumnCount; i++) { worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText; } //写入数值 for (int r = 0; r < dataGridView1.Rows.Count; r++) { for (int i = 0; i < dataGridView1.ColumnCount; i++) { worksheet.Cells[r + 2, i + 1] = dataGridView1.Rows[r].Cells[i].Value; } System.Windows.Forms.Application.DoEvents(); } worksheet.Columns.EntireColumn.AutoFit();//列宽自适应 //MessageBox.Show(fileName + "资料保存成功", "提示", MessageBoxButtons.OK); MyLog.Info(fileName + "资料保存成功"); if (saveFileName != "") { try { workbook.Saved = true; workbook.SaveCopyAs(saveFileName); //fileSaved = true; } catch (Exception ex) {//fileSaved = false; //MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message); MyLog.Error("导出文件时出错,文件可能正被打开!\n" + ex.Message); } } xlApp.Quit(); GC.Collect();//强行销毁 }