在串口C#中发送/接收Excel表格 [英] excel sheet sending /receiving in serialport C#

查看:135
本文介绍了在串口C#中发送/接收Excel表格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





正在开发手持系统项目。现在我正在使用两个c#应用程序来测试它们是否通过串口发送/接收数据。



第一个应用程序在COM5上 - >端口,首先,第一个应用程序将逐行发送excel数据,当第二个应用程序收到一行应该发送$ machID#回到第一个应用程序。

这里的机器人在exceldata无论收到什么。



第二件事是:我需要加载从第二个应用程序到第一个应用程序的excel数据。在这种情况下

第一个应用程序应该读取正确的formet并保存在Excel工作表中。



这里我的问题是:第一件事情有点好,第二件事我需要在第一个应用程序中编写代码。它是在serialPortDatareceived事件中还是在某些地方





第一个应用程序代码是



am developing project on handheld system. now am using two c# applications just for testing whether they are sending /receiving data through serial port.

1st application is on COM5-->port ,first ,1st application will send excel data row by row ,when one row is received by 2nd application that should send $ machID # back to first application.
Here machid is in exceldata whatever it is received.

second thing is : i need to load excel data from 2nd apllication to 1st application.in that case
1st application should read in correct formet and save in excel sheet.

here my question is:upto first thing am somewhat ok, coming to second thing where i need to write the code in 1st application.is it in serialPortDatareceived event or in some where


1st application code is

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 Excel=Microsoft.Office.Interop.Excel;
using System.IO;
using System.Threading;
using System.IO.Ports;



namespace Hand_Held_Data_Transporter
{
    public partial class Form1 : Form
    {
        int[] stream_buffer;
        String final = null;
        String machId = null, custId = null, name = null, totalBal = null, paid = null, lastPaid = null, due = null;
        String inputdata;
    
        public Form1()
        {
            InitializeComponent();
            progressBar1.Enabled = false;
            progressBar2.Enabled = false;
            

          //  serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);
           
        }



        private void Browse_Click(object sender, EventArgs e)
        {

            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.Filter = "All Files(*.*)|*.*";
            if (fdlg.ShowDialog() == DialogResult.OK)
            {


                textBox1.Text = fdlg.FileName;
                File.ReadAllText(textBox1.Text);

            }
        }

       



        private void Upload_Click(object sender, EventArgs e)
        {

           // StringBuilder sb = new StringBuilder();
  

            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(textBox1.Text, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
            Excel.Range xlRange = xlWorksheet.UsedRange;

            int rowCount = xlRange.Rows.Count;
            int colCount = xlRange.Columns.Count;
            progressBar1.Visible = true;
            

            int k = 100 / rowCount;

            for (int i = 2; i <= rowCount; i++)
            {

               
                for (int j = 1; j <= colCount; j++)
                {

                    if (j == 1)
                     machId = xlRange.Cells[i, j].Value.ToString();
                 

                        //upload1 = xlRange.Cells[i, j].Value.ToString();
                    if (j == 2)
                        custId = xlRange.Cells[i, j].Value.ToString();
                   
                  
                    if (j == 3)
                        name = xlRange.Cells[i, j].Value.ToString();
                
                    if (j == 4)
                        totalBal= xlRange.Cells[i, j].Value.ToString();
                    
                     if (j == 5)
                        paid = xlRange.Cells[i, j].Value.ToString();

                     if (j == 6)
                         lastPaid = xlRange.Cells[i, j].Value.ToString("dd/MM/yyyy");
                    //MessageBox.Show("lastpaid:"+lastPaid);
                  
                    if (j == 7)
                       due = xlRange.Cells[i, j].Value.ToString();


                    final = "$ POST," + machId + "," + custId + "," + name + "," + totalBal + "," + paid + "," + lastPaid + "," + due + " # ";


                }

                if (serialPort1.IsOpen)
                {
                  if(machId.Length<=5 && custId.Length<=10 && name.Length<=15 && totalBal.Length<=7 && paid.Length<=7 && lastPaid.Length<=14 && due.Length<=7 )
                  serialPort1.Write(final);
                    

            }     serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);

              // MessageBox.Show(final);
                if (progressBar1.Value < 100)
                {
                    Thread.Sleep(100);
                    progressBar1.Value += k;
                }


            }
            progressBar1.Value = 100;

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            progressBar1.Visible = false;
            progressBar2.Visible = false;
           serialPort1.Open();

           string[] ArrayComPortsNames = null;
           int index = -1;
           string ComPortName = null;

           ArrayComPortsNames = SerialPort.GetPortNames();
           do
           {
               index += 1;
               comboBox1.Items.Add(ArrayComPortsNames[index]);
           }

           while (!((ArrayComPortsNames[index] == ComPortName)
                         || (index == ArrayComPortsNames.GetUpperBound(0))));
           Array.Sort(ArrayComPortsNames);

           //want to get first out
           if (index == ArrayComPortsNames.GetUpperBound(0))
           {
               ComPortName = ArrayComPortsNames[0];
           }
           comboBox1.Text = ArrayComPortsNames[0];

          
          

         
        }

        private void Download_Click(object sender, EventArgs e)
        {
                    Excel.Application xlApp = default(Excel.Application);
            Excel.Workbook xlWorkBook = default(Excel.Workbook);
            Excel.Worksheet xlWorkSheet = default(Excel.Worksheet);
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
            string fName = @"C:\STL\Download\Download_" + DateTime.Now.ToString("dd MMM YY HH mm").Trim() + ".xls ";
            try
            {
           
                object misValue = System.Reflection.Missing.Value;
                xlApp = new Excel.Application();
                xlWorkBook = xlApp.Workbooks.Add(misValue);
                xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
                xlWorkSheet.Cells[1, 1] = "Name";
                xlWorkSheet.Cells[1, 2] = "ID Number";
                xlWorkSheet.Cells[1, 3] = "Installment";
                xlWorkSheet.Cells[1, 4] = "Paid Amount";
                xlWorkSheet.Cells[1, 5] = "Due Amount";

                xlWorkSheet.Cells[1, 1].Interior.ColorIndex = 39;
                xlWorkSheet.Cells[1, 2].Interior.ColorIndex = 39;
                xlWorkSheet.Cells[1, 3].Interior.ColorIndex = 39;
                xlWorkSheet.Cells[1, 4].Interior.ColorIndex = 39;
                xlWorkSheet.Cells[1, 5].Interior.ColorIndex = 39;

               // serialPort1.Open();
               // String s = "$GET,Chsum#";
               // if (serialPort1.IsOpen)
              //  {
                  //  serialPort1.WriteLine(s);
                    
                  // String s1= serialPort1.ReadLine();
                  // MessageBox.Show(s1);
               // }


                xlWorkBook.SaveAs(fName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                xlWorkBook.Close(true, misValue, misValue);
                xlApp.Quit();
                releaseObject(xlWorkSheet);
                releaseObject(xlWorkBook);
                releaseObject(xlApp);
            }
            finally
            {
                if (xlApp != null)
                    releaseObject(xlApp);
                if (xlWorkBook != null)
                    releaseObject(xlWorkBook);
                if (xlWorkSheet != null)
                    releaseObject(xlWorkSheet);
            }
            if (System.IO.File.Exists(fName))
            {
                if (MessageBox.Show("Would you like to open the excel file?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    try
                    {
                        System.Diagnostics.Process.Start(fName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error opening the excel file." + Environment.NewLine +
                          ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            

            }
        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }

      private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
               
                inputdata = serialPort1.ReadLine();
               // MessageBox.Show("data received");
                MessageBox.Show("value is:" +inputdata);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }


            //this method will execute when buffer is full
          /*  stream_buffer[0] = serialPort1.ReadByte();   //read 1st byte
            stream_buffer[1] = serialPort1.ReadByte();   //read another byte and so on
            stream_buffer[2] = serialPort1.ReadByte();
            stream_buffer[3] = serialPort1.ReadByte();
            stream_buffer[4] = serialPort1.ReadByte();
            stream_buffer[5] = serialPort1.ReadByte();
            stream_buffer[6] = serialPort1.ReadByte();

             StreamWriter MyStreamWriter = new StreamWriter(@"c:\Testing.txt, true");
             for (int i = 0; i < 7;i++ )
                 MyStreamWriter.Write(stream_buffer[i]);

            MyStreamWriter.Flush();

            MyStreamWriter.Close();


            for (int j = 0; j < 7; j++)
                textBox1.Text = Convert.ToString(stream_buffer[j]);*/



        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            MessageBox.Show("Do you want to close this Application");
            serialPort1.Close();
        }

        

       

       
        }
    }





和第二次申请是







and 2nd application is

:

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 System.IO.Ports;
using System.Threading;
using System.IO;

namespace handheld_Responce
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            serialPort1.Open();
            serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);
     
       
        }

      
        private void Form1_Load(object sender, EventArgs e)
        {




        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
           
                if (serialPort1.IsOpen)
                {
                    String RecievedData;
                    RecievedData = serialPort1.ReadExisting();
                    if (!(RecievedData == ""))
                    {
                        //textBox2.Text += RecievedData;
                        textBox2.Invoke((MethodInvoker)delegate { textBox2.Text += RecievedData; });
                    }
                    Thread.Sleep(100);
                    serialPort1.WriteLine("$M121,0#");
            }
            
        }

        private void browse_Click(object sender, EventArgs e)
        {
            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.Filter = "All Files(*.*)|*.*";
            if (fdlg.ShowDialog() == DialogResult.OK)
            {


                textBox1.Text = fdlg.FileName;
                File.ReadAllText(textBox1.Text);

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
    }
}

推荐答案

machID#返回第一个应用程序。

无论收到什么,这里都是机器人。



第二件事是:我需要将excel数据从第二个应用程序加载到第一个应用程序。在这种情况下

第一个应用程序应该读取正确的formet并保存在excel表。



这里我的问题是:第一件事情有点好,第二件事我需要在第一个应用程序中编写代码。它在serialPortDatareceived活动或某些地方





第一个应用程序代码是
machID # back to first application.
Here machid is in exceldata whatever it is received.

second thing is : i need to load excel data from 2nd apllication to 1st application.in that case
1st application should read in correct formet and save in excel sheet.

here my question is:upto first thing am somewhat ok, coming to second thing where i need to write the code in 1st application.is it in serialPortDatareceived event or in some where


1st application code is
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 Excel=Microsoft.Office.Interop.Excel;
using System.IO;
using System.Threading;
using System.IO.Ports;



namespace Hand_Held_Data_Transporter
{
    public partial class Form1 : Form
    {
        int[] stream_buffer;
        String final = null;
        String machId = null, custId = null, name = null, totalBal = null, paid = null, lastPaid = null, due = null;
        String inputdata;
    
        public Form1()
        {
            InitializeComponent();
            progressBar1.Enabled = false;
            progressBar2.Enabled = false;
            

          //  serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);
           
        }



        private void Browse_Click(object sender, EventArgs e)
        {

            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.Filter = "All Files(*.*)|*.*";
            if (fdlg.ShowDialog() == DialogResult.OK)
            {


                textBox1.Text = fdlg.FileName;
                File.ReadAllText(textBox1.Text);

            }
        }

       



        private void Upload_Click(object sender, EventArgs e)
        {

           // StringBuilder sb = new StringBuilder();
  

            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(textBox1.Text, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
            Excel.Range xlRange = xlWorksheet.UsedRange;

            int rowCount = xlRange.Rows.Count;
            int colCount = xlRange.Columns.Count;
            progressBar1.Visible = true;
            

            int k = 100 / rowCount;

            for (int i = 2; i <= rowCount; i++)
            {

               
                for (int j = 1; j <= colCount; j++)
                {

                    if (j == 1)
                     machId = xlRange.Cells[i, j].Value.ToString();
                 

                        //upload1 = xlRange.Cells[i, j].Value.ToString();
                    if (j == 2)
                        custId = xlRange.Cells[i, j].Value.ToString();
                   
                  
                    if (j == 3)
                        name = xlRange.Cells[i, j].Value.ToString();
                
                    if (j == 4)
                        totalBal= xlRange.Cells[i, j].Value.ToString();
                    
                     if (j == 5)
                        paid = xlRange.Cells[i, j].Value.ToString();

                     if (j == 6)
                         lastPaid = xlRange.Cells[i, j].Value.ToString("dd/MM/yyyy");
                    //MessageBox.Show("lastpaid:"+lastPaid);
                  
                    if (j == 7)
                       due = xlRange.Cells[i, j].Value.ToString();


                    final = "


POST, + machId + + custId + + name + + totalBal + + paid + + lastPaid + + due + ;


}

if (serialPort1.IsOpen)
{
if (machId.Length< = 5 && custId.Length< = 10 && name.Length< = 15 && totalBal.Length< = 7 && paid.Length< = 7 && lastPaid.Length< = 14 && due.Length< = 7
serialPort1.Write(final);


} serialPort1.DataReceived + = new SerialDataReceivedEventHandler(serialPort1_DataReceived);

// MessageBox.Show(final);
< span class =code-keyword> if (progressBar1.Value < 100
{
Thread.Sleep( 100 );
progressBar1.Value + = k;
}


}
progressBar1.Value = 100 ;

}

private void Form1_Load(< span class =code-keyword> object sender,EventArgs e)
{
progressBar1.Visible = false ;
progressBar2.Visible = false ;
serialPort1.Open();

string [] ArrayComPortsNames = null ;
int index = -1;
string ComPortName = null ;

ArrayComPortsNames = SerialPort.GetPortNames();
执行
{
index + = 1 ;
comboBox1.Items.Add(ArrayComPortsNames [index]);
}

while (!((ArrayComPortsNames [index] == ComPortName)
||(index == ArrayComPortsNames.GetUpperBound( 0 ))));
Array.Sort(ArrayComPortsNames);

// 想要先出
if (index == ArrayComPortsNames.GetUpperBound( 0 ))
{
ComPortName = ArrayComPortsNames [ 0 ];
}
comboBox1.Text = ArrayComPortsNames [ 0 ];





}

private void Download_Click( object sender,EventArgs e)
{
Excel.Application xlApp = < span class =code-keyword> default (Excel.Application);
Excel.Workbook xlWorkBook = 默认(Excel.Workbook);
Excel.Worksheet xlWorkSheet = 默认(Excel.Worksheet);
serialPort1.DataReceived + = new SerialDataReceivedEventHandler(serialPort1_DataReceived);
string fName = @ C:\\ \\ stL \Download \Download _ + DateTime.Now.ToString( dd MMM YY HH mm )。修剪()+ 。xls;
尝试
{

object misValue = System .Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = \"Name\";
xlWorkSheet.Cells[1, 2] = \"ID Number\";
xlWorkSheet.Cells[1, 3] = \"Installment\";
xlWorkSheet.Cells[1, 4] = \"Paid Amount\";
xlWorkSheet.Cells[1, 5] = \"Due Amount\";

xlWorkSheet.Cells[1, 1].Interior.ColorIndex = 39;
xlWorkSheet.Cells[1, 2].Interior.ColorIndex = 39;
xlWorkSheet.Cells[1, 3].Interior.ColorIndex = 39;
xlWorkSheet.Cells[1, 4].Interior.ColorIndex = 39;
xlWorkSheet.Cells[1, 5].Interior.ColorIndex = 39;

// serialPort1.Open();
// String s = \"
POST," + machId + "," + custId + "," + name + "," + totalBal + "," + paid + "," + lastPaid + "," + due + " # "; } if (serialPort1.IsOpen) { if(machId.Length<=5 && custId.Length<=10 && name.Length<=15 && totalBal.Length<=7 && paid.Length<=7 && lastPaid.Length<=14 && due.Length<=7 ) serialPort1.Write(final); } serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived); // MessageBox.Show(final); if (progressBar1.Value < 100) { Thread.Sleep(100); progressBar1.Value += k; } } progressBar1.Value = 100; } private void Form1_Load(object sender, EventArgs e) { progressBar1.Visible = false; progressBar2.Visible = false; serialPort1.Open(); string[] ArrayComPortsNames = null; int index = -1; string ComPortName = null; ArrayComPortsNames = SerialPort.GetPortNames(); do { index += 1; comboBox1.Items.Add(ArrayComPortsNames[index]); } while (!((ArrayComPortsNames[index] == ComPortName) || (index == ArrayComPortsNames.GetUpperBound(0)))); Array.Sort(ArrayComPortsNames); //want to get first out if (index == ArrayComPortsNames.GetUpperBound(0)) { ComPortName = ArrayComPortsNames[0]; } comboBox1.Text = ArrayComPortsNames[0]; } private void Download_Click(object sender, EventArgs e) { Excel.Application xlApp = default(Excel.Application); Excel.Workbook xlWorkBook = default(Excel.Workbook); Excel.Worksheet xlWorkSheet = default(Excel.Worksheet); serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived); string fName = @"C:\STL\Download\Download_" + DateTime.Now.ToString("dd MMM YY HH mm").Trim() + ".xls "; try { object misValue = System.Reflection.Missing.Value; xlApp = new Excel.Application(); xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); xlWorkSheet.Cells[1, 1] = "Name"; xlWorkSheet.Cells[1, 2] = "ID Number"; xlWorkSheet.Cells[1, 3] = "Installment"; xlWorkSheet.Cells[1, 4] = "Paid Amount"; xlWorkSheet.Cells[1, 5] = "Due Amount"; xlWorkSheet.Cells[1, 1].Interior.ColorIndex = 39; xlWorkSheet.Cells[1, 2].Interior.ColorIndex = 39; xlWorkSheet.Cells[1, 3].Interior.ColorIndex = 39; xlWorkSheet.Cells[1, 4].Interior.ColorIndex = 39; xlWorkSheet.Cells[1, 5].Interior.ColorIndex = 39; // serialPort1.Open(); // String s = "


GET,Chsum#\";
// if (serialPort1.IsOpen)
// {
// serialPort1.WriteLine(s);

// String s1= serialPort1.ReadLine();
// MessageBox.Show(s1);
// }


xlWorkBook.S aveAs(fName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
}
finally
{
if (xlApp != null)
releaseObject(xlApp);
if (xlWorkBook != null)
releaseObject(xlWorkBook);
if (xlWorkSheet != null)
releaseObject(xlWorkSheet);
}
if (System.IO.File.Exists(fName))
{
if (MessageBox.Show(\"Would you like to open the excel file?\", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
System.Diagnostics.Process.Start(fName);
}
catch (Exception ex)
{
MessageBox.Show(\"Error opening the excel file.\" + Environment.NewLine +
ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}


}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show(\"Unable to release the Object \" + ex.ToString());
}
finally
{
GC.Collect();
}
}

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{

inputdata = serialPort1.ReadLine();
// MessageBox.Show(\"data received\");
MessageBox.Show(\"value is:\" +inputdata);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}


//this method will execute when buffer is full
/* stream_buffer[0] = serialPort1.ReadByte(); //read 1st byte
stream_buffer[1] = serialPort1.ReadByte(); //read another byte and so on
stream_buffer[2] = serialPort1.ReadByte();
stream_buffer[3] = serialPort1.ReadByte();
stream_buffer[4] = serialPort1.ReadByte();
stream_buffer[5] = serialPort1.ReadByte();
stream_buffer[6] = serialPort1.ReadByte();

StreamWriter MyStreamWriter = new StreamWriter(@\"c:\Testing.txt, true\");
for (int i = 0; i < 7;i++ )
MyStreamWriter.Write(stream_buffer[i]);

MyStreamWriter.Flush();

MyStreamWriter.Close();


for (int j = 0; j < 7; j++)
textBox1.Text = Convert.ToString(stream_buffer[j]);*/




}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
MessageBox.Show(\"Do you want to close this Application\");
serialPort1.Close();
}






}
}
GET,Chsum#"; // if (serialPort1.IsOpen) // { // serialPort1.WriteLine(s); // String s1= serialPort1.ReadLine(); // MessageBox.Show(s1); // } xlWorkBook.SaveAs(fName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); xlWorkBook.Close(true, misValue, misValue); xlApp.Quit(); releaseObject(xlWorkSheet); releaseObject(xlWorkBook); releaseObject(xlApp); } finally { if (xlApp != null) releaseObject(xlApp); if (xlWorkBook != null) releaseObject(xlWorkBook); if (xlWorkSheet != null) releaseObject(xlWorkSheet); } if (System.IO.File.Exists(fName)) { if (MessageBox.Show("Would you like to open the excel file?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { try { System.Diagnostics.Process.Start(fName); } catch (Exception ex) { MessageBox.Show("Error opening the excel file." + Environment.NewLine + ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } private void releaseObject(object obj) { try { System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); obj = null; } catch (Exception ex) { obj = null; MessageBox.Show("Unable to release the Object " + ex.ToString()); } finally { GC.Collect(); } } private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) { try { inputdata = serialPort1.ReadLine(); // MessageBox.Show("data received"); MessageBox.Show("value is:" +inputdata); } catch (Exception ex) { MessageBox.Show(ex.Message); } //this method will execute when buffer is full /* stream_buffer[0] = serialPort1.ReadByte(); //read 1st byte stream_buffer[1] = serialPort1.ReadByte(); //read another byte and so on stream_buffer[2] = serialPort1.ReadByte(); stream_buffer[3] = serialPort1.ReadByte(); stream_buffer[4] = serialPort1.ReadByte(); stream_buffer[5] = serialPort1.ReadByte(); stream_buffer[6] = serialPort1.ReadByte(); StreamWriter MyStreamWriter = new StreamWriter(@"c:\Testing.txt, true"); for (int i = 0; i < 7;i++ ) MyStreamWriter.Write(stream_buffer[i]); MyStreamWriter.Flush(); MyStreamWriter.Close(); for (int j = 0; j < 7; j++) textBox1.Text = Convert.ToString(stream_buffer[j]);*/ } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { MessageBox.Show("Do you want to close this Application"); serialPort1.Close(); } } }





and 2nd application is



:



and 2nd application is

:

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 System.IO.Ports;
using System.Threading;
using System.IO;

namespace handheld_Responce
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            serialPort1.Open();
            serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);
     
       
        }

      
        private void Form1_Load(object sender, EventArgs e)
        {




        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
           
                if (serialPort1.IsOpen)
                {
                    String RecievedData;
                    RecievedData = serialPort1.ReadExisting();
                    if (!(RecievedData == ""))
                    {
                        //textBox2.Text += RecievedData;
                        textBox2.Invoke((MethodInvoker)delegate { textBox2.Text += RecievedData; });
                    }
                    Thread.Sleep(100);
                    serialPort1.WriteLine("


这篇关于在串口C#中发送/接收Excel表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆