Serial_to_excel_to_chart

mail@pastecode.io avatar
unknown
csharp
2 months ago
2.5 kB
2
Indexable
Never
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    string data = serialPort.ReadLine();
    string[] values = data.Split(',');
    Excel.Range range = worksheet.UsedRange;
    int rowCount = range.Rows.Count;
    int colCount = range.Columns.Count;

    List<double> xValues = new List<double>();
    List<double> yValues = new List<double>();
    List<double> y2Values = new List<double>();

    if (values.Length >= 3)
    {
        this.Invoke((MethodInvoker)delegate
        {
            WriteToExcel(values[0],values[1],values[2]);
        
        });

        for (int row = 1; row <= rowCount; row++)
        {
            xValues.Add(Convert.ToDouble(range.Cells[row, 1].Value));
            yValues.Add(Convert.ToDouble(range.Cells[row, 2].Value));
            yValues.Add(Convert.ToDouble(range.Cells[row, 3].Value));
            series1.Points.AddXY(xValues,yValues);
            series2.Points.AddXY(xValues,y2Values);
        }

    }

}
private void WriteToExcel(string v1, string v2, string v3)
{
    if (excelApp == null)
    {
        excelApp = new Excel.Application();
        excelApp.Visible = true;
        workbook = excelApp.Workbooks.Add();
        worksheet = workbook.ActiveSheet;

        worksheet.Cells[1, 1] = "Voltage";
        worksheet.Cells[1, 2] = "Current";
        worksheet.Cells[1, 3] = "Power";
    }
    worksheet.Cells[rowIndex, 1] = v1;
    worksheet.Cells[rowIndex, 2] = v2;
    worksheet.Cells[rowIndex, 3] = v3;

    rowIndex++;
}
private void plotFromExcel()
{
    Excel.Application excelApp = new Excel.Application();
    Excel.Workbook workbook = excelApp.Workbooks.Open(excelFilePath);
    Excel._Worksheet worksheet = workbook.Sheets[1];
    Excel.Range range = worksheet.UsedRange;
    int rowCount = range.Rows.Count;

    for (int i = 2; i <= rowCount; i++)
    {
        double voltageValue = Convert.ToDouble(((Excel.Range)worksheet.Cells[i, 1]).Value);
        double currentValue = Convert.ToDouble(((Excel.Range)worksheet.Cells[i, 2]).Value);
        double powerValue = Convert.ToDouble(((Excel.Range)worksheet.Cells[i, 3]).Value);

        // Add data points to each series
        series1.Points.AddXY(voltageValue, currentValue);
        series2.Points.AddXY(voltageValue, powerValue);
    }

    // Add the series to the chart
    chart1.Series.Add(series1);
    chart1.Series.Add(series2);
}
Leave a Comment