C#与halcon混合编程(6)

生成报表

**    1、  生成 Excel 表格用以保存检测结果,使用NPOI工具,调用其动态链接库实现 Excel 操作;

**    2、  项目名称上右键 管理NuGet 程序包,添加 NPOI 程序包,该包似乎由于 .NET 框架原因(不同版本的 NPOI 所兼容的 .NET 版本也不相同),.NET4.8 需要先安装 SixLabors.Fonts ( 搜索时需勾选包括预发行版 ); 1中所指为旧版.NET框架;

**    3、  阐述检测设定窗口的实现原理,下节代码讲述;

**    注: NET框架(特定于Windows),然后使用Windows Forms App (.NET Framework)。(似乎只有该程序下可以工具栏可以正常显示 halcon 窗口)

                NET核心/ .NET(跨平台),然后使用Windows Forms App(虽版本更高,但似乎该框架下无法在工具箱加载显示 halcon 窗口,故无法实现跨平台)。

//  mainform.cs

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 HalconDotNet;
using System.Xml;
using NPOI.HSSF.UserModel;//读写 Excel 的命名空间
using NPOI.SS.UserModel;//读写 Excel 的命名空间
using System.IO;//用于系统输入输出
using System.Globalization;//用于获取系统时间

namespace vision
{
    public partial class mainform : Form
    {
        public List<Camera> cameras;
        public static string CurrentCCD;
        public Dictionary<string, Camera> CCD;

        Dictionary<string, HWindowControl> findhwin = new Dictionary<string, HWindowControl>();

        public static DataSet ds=new DataSet();

        public DataSet posdata;

        //旧配置加载
        public mainform()
        {
            InitializeComponent();
            findhwin.Clear();
            findhwin.Add("CCD1", hWindowControl2);
            findhwin.Add("CCD2", hWindowControl3);
            findhwin.Add("CCD3", hWindowControl4);
            findhwin.Add("CCD4", hWindowControl5);
            findhwin.Add("CCD5", hWindowControl6);
            posdata = new DataSet();
            cameras = new List<Camera>();
            CCD = new Dictionary<string, Camera>();

            CurrentCCD = "CCD1";
            loadCamera();

            foreach (Camera c in cameras)
            {
                c.toollist = pathtool.ReadFromdat(pathtool.currentProductPath + @"\" + c.logicName + ".dat");
            }
            label6.Text = pathtool.currentProduct;
            posdata.ReadXml(pathtool.currentProductPath + @"\Posdata.xml");

        //这里可以检查控制方面的连接是否正常,相机是否正常,如果不正常就提示
            InitialDataGrid(gridControl1, ds);
            updatedataset();
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                gridView1.ExpandMasterRow(i);
            }
            this.ShowDialog();
        }
        //新配置
        public mainform(int a)
        {
            InitializeComponent();
            findhwin.Clear();
            findhwin.Add("CCD1", hWindowControl2);
            findhwin.Add("CCD2", hWindowControl3);
            findhwin.Add("CCD3", hWindowControl4);
            findhwin.Add("CCD4", hWindowControl5);
            findhwin.Add("CCD5", hWindowControl6);

            posdata = new DataSet();
            cameras = new List<Camera>();
            CCD = new Dictionary<string, Camera>();

            CurrentCCD = "CCD1";
            loadCamera();

            foreach (Camera c in cameras)
            {
                string cpath = pathtool.currentProductPath + @"\" + c.logicName + ".dat";
                pathtool.SaveTodat(c.toollist, cpath);
            }
            label6.Text = pathtool.currentProduct;
            InitPos();
            MessageBox.Show("是新建配置!");
            this.ShowDialog();
        }
        private void loadCamera()
        {
            //cameras.Clear();
            try
            {
                panel2.BackColor = Color.AliceBlue;

                XmlDocument xmlDocCamera = new XmlDocument();
                xmlDocCamera.Load("./Data/" + "camset.xml");
                XmlNodeList xnl;
                XmlNode xn;
                xn = xmlDocCamera.GetElementsByTagName("Camera")[0];
                xnl = xn.ChildNodes;
                int i = 1;
                if (cameras.Count == 0)
                {
                    foreach (XmlNode x in xnl)
                    {
                        Camera c = new Camera();
                        c.logicName = "CCD" + i;
                        c.halconwin.Add(findhwin[c.logicName]);
                        c.name = x.Attributes["name"].Value;
                        c.ExposureTime = int.Parse(x.Attributes["ExposureTime"].Value);
                        c.Gain = int.Parse(x.Attributes["Gain"].Value);
                        c.PixelDist = double.Parse(x.Attributes["PixelDist"].Value);
                        c.fps = int.Parse(x.Attributes["FPS"].Value);

                        c.rectifytype = int.Parse(x.Attributes["type"].Value);
                        c.halconwin.Clear();
                        c.halconwin.Add(findhwin[c.logicName]);

                        // c.OnImageProcessedEvent += new Camera.OnImageProcessedEventHandler(OnImageProcessedEvent);
                        cameras.Add(c);
                        i++;
                    }
                }
                for (int ci = 0; ci < cameras.Count; ci++)
                {
                    CCD.Add("CCD" + (ci + 1).ToString(), cameras[ci]);
                }
                CCD["CCD1"].halconwin.Add(hWindowControl1);
            }
            catch (Exception e)
            {
                MessageBox.Show("相机加载错误");
            }
        }
        private void InitPos()
        {  //新配置时候,生成一个位置全0的posdata,并写入xml
            posdata = new DataSet("posdata");
            DataTable dt = new DataTable("pos");
            dt.Columns.Add("cam1");
            dt.Columns.Add("cam2");
            dt.Columns.Add("cam3");
            dt.Columns.Add("cam4");
            dt.Columns.Add("cam5");
            dt.Columns.Add("cam6");

            dt.Columns.Add("ng");
            dt.Columns.Add("ok");

            dt.Columns.Add("blowwidth");

            dt.Columns.Add("speed");
            dt.Columns.Add("cam1expo");
            dt.Columns.Add("cam2expo");
            dt.Columns.Add("cam3expo");
            dt.Columns.Add("cam4expo");
            dt.Columns.Add("cam5expo");
            dt.Columns.Add("cam6expo");

            dt.Columns.Add("cam1gain");
            dt.Columns.Add("cam2gain");
            dt.Columns.Add("cam3gain");
            dt.Columns.Add("cam4gain");
            dt.Columns.Add("cam5gain");
            dt.Columns.Add("cam6gain");
            dt.Columns.Add("dist");

            DataRow row1 = dt.NewRow();
            row1["cam1"] = "0";
            row1["cam2"] = "0";
            row1["cam3"] = "0";
            row1["cam4"] = "0";
            row1["cam5"] = "0";
            row1["cam6"] = "0";
            row1["ng"] = "1000";
            row1["ok"] = "1500";
            row1["blowwidth"] = "500";
            row1["speed"] = "1000";

            row1["cam1expo"] = "20";
            row1["cam2expo"] = "20";
            row1["cam3expo"] = "20";
            row1["cam4expo"] = "20";
            row1["cam5expo"] = "20";
            row1["cam6expo"] = "20";

            row1["cam1gain"] = "280";
            row1["cam2gain"] = "280";
            row1["cam3gain"] = "280";
            row1["cam4gain"] = "280";
            row1["cam5gain"] = "280";
            row1["cam6gain"] = "280";
            row1["dist"] = "50";

            dt.Rows.Add(row1);

            posdata.Tables.Add(dt);

            posdata.WriteXml(pathtool.currentProductPath + @"\Posdata.xml");
        }
        private void button5_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            Form1 setform = new Form1();

            setform.ShowDialog();
        }
        private void InitialDataGrid(DevExpress.XtraGrid.GridControl grid, DataSet ds)
        {
            // 定义主表
            DataTable masterTable = new DataTable("CameraTable");
            DataTable detailTable = new DataTable("DetailTable");
            DataColumn parentColumn = new DataColumn("CameraID", typeof(string));
            masterTable.Columns.Add(parentColumn);

            DataColumn childrenColumn = new DataColumn("CCD", typeof(string));
            detailTable.Columns.Add(childrenColumn);

            detailTable.Columns.AddRange(new DataColumn[] {  
             new DataColumn("检测项",typeof(string)),  
             new DataColumn("名称",typeof(string)),  
             new DataColumn("下限",typeof(double)),  
             new DataColumn("上限",typeof(double)),
             new DataColumn("测量",typeof(double)),
             new DataColumn("合格率",typeof(double)),
             });

            ds.Tables.AddRange(new DataTable[] { masterTable.Copy(), detailTable.Copy() });
            // 创建表关系  
            DataRelation relation = new DataRelation("detailTable", ds.Tables[0].Columns[0], ds.Tables[1].Columns[0], false);
            ds.Relations.Add(relation); // 添加  
            grid.DataSource = ds.Tables[0];  // 指定数据源  
            ds.Clear();
            gridView1.ExpandMasterRow(0);
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                gridView1.ExpandMasterRow(i);
            }
        }
        public void updatedataset()
        {
            //update写入时候,计算出当前tool的参数位置,结果显示位置,并传递给它
            
            ds.Clear();
            DataTable masterTable = new DataTable("CameraTable");
            DataTable detailTable = new DataTable("DetailTable");
            masterTable = ds.Tables["CameraTable"];
            detailTable = ds.Tables["DetailTable"];

            int rowcount = 0;

            for (int i = 0; i < cameras.Count; i++)
            {
                masterTable.Rows.Add(cameras[i].logicName);
            }
            for (int i = 0; i < cameras.Count; i++)
            {
                for (int j = 0; j < cameras[i].toollist.Count; j++)
                {
                    cameras[i].toollist[j].posdataset.Clear();
                    for (int k = 0; k < cameras[i].toollist[j].ischeck.Count; k++)
                    {
                        if (cameras[i].toollist[j].ischeck[k])
                        {
                            //测量名//用户自定义名       下限 上限 实际值 合格率
                            detailTable.Rows.Add(cameras[i].logicName, cameras[i].toollist[j].absname[k], cameras[i].toollist[j].defname[k], cameras[i].toollist[j].xx[k], cameras[i].toollist[j].sx[k], cameras[i].toollist[j].result[k], 0);
                            cameras[i].toollist[j].posdataset.Add(rowcount);
                            rowcount++;
                        }
                    }
                }
            }
            gridView1.ExpandMasterRow(0);
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                gridView1.ExpandMasterRow(i);
            }
        }
        private void button3_Click(object sender, EventArgs e)//实现 Excel 的输出
        {
            获取日期
            ///年月日时分秒
            string SaveFileName = DateTime.Now.Date.ToString("yyyy", DateTimeFormatInfo.InvariantInfo) + DateTime.Now.Date.ToString("MM", DateTimeFormatInfo.InvariantInfo);
            SaveFileName += DateTime.Now.Date.ToString("dd", DateTimeFormatInfo.InvariantInfo) + DateTime.Now.ToString("hh", DateTimeFormatInfo.InvariantInfo);
            SaveFileName += DateTime.Now.ToString("mm", DateTimeFormatInfo.InvariantInfo) + DateTime.Now.ToString("ss", DateTimeFormatInfo.InvariantInfo);

            string templatepath = String.Format(@"{0}\{1}", pathtool.exepath, SaveFileName);//等价于 exepath\SaveFileName ;"{0}\{1}" 前加 @ 不明原因;
            templatepath = templatepath + "统计报表.xls";//组成路径
            try
            {
                HSSFWorkbook wk = new HSSFWorkbook();//创建 Excel 工作薄
                //创建一个Sheet,对应 Excel 中的悬页;
                ISheet sheet = wk.CreateSheet("检测结果统计");
                //在第一行创建行  
                IRow row = sheet.CreateRow(0);
                //在第一行的第一列创建单元格  
                ICell cell = row.CreateCell(0);
                cell.SetCellValue("检测项");
                //在第一行第二列创建单元格
                cell = row.CreateCell(1);
                cell.SetCellValue("自定义名称");
                cell = row.CreateCell(2);
                cell.SetCellValue("上限");
                cell = row.CreateCell(3);
                cell.SetCellValue("下限");
                cell = row.CreateCell(4);
                cell.SetCellValue("OK");
                cell = row.CreateCell(5);
                cell.SetCellValue("NG");
                cell = row.CreateCell(6);
                cell.SetCellValue("合格率");
                
                //合并统计所有tool的 goodcount  badcount
                List<int> allgoodcount = new List<int>();//实例化所有合格件列表
                List<int> allbadcount = new List<int>();//实例化所有不合格件列表

                foreach (Camera c in cameras)
                {
                    foreach (ImageTool t in c.toollist)
                    {
                        for (int i = 0; i < t.goodcount.Count; i++)
                        {
                            allgoodcount.Add(t.goodcount[i]);
                            allbadcount.Add(t.badcount[i]);
                        }
                    }
                }
                DataRowCollection drc = ds.Tables["detailTable"].Rows;//读出数据集中的内容并写入上面创建的 sheet
                for (int i = 0; i < drc.Count; i++)
                {
                    DataRow dr = drc[i];
                    string s = dr[1].ToString();//检测项名称
                    string s1 = dr[2].ToString();//自定义名称

                    double xx = (double)dr[3];
                    double sx = (double)dr[4];

                    double hegelv = (double)dr[6];

                    row = sheet.CreateRow(i + 1);
                    cell = row.CreateCell(0);
                    cell.SetCellValue(s);
                    cell = row.CreateCell(1);
                    cell.SetCellValue(s1);
                    cell = row.CreateCell(2);
                    cell.SetCellValue(xx);
                    cell = row.CreateCell(3);
                    cell.SetCellValue(sx);
                    cell = row.CreateCell(4);
                    cell.SetCellValue(allgoodcount[i]);
                    cell = row.CreateCell(5);
                    cell.SetCellValue(allbadcount[i]);

                    cell = row.CreateCell(6);

                    cell.SetCellValue(hegelv);
                }

                using (FileStream fs = File.OpenWrite(templatepath))
                {
                    wk.Write(fs);//向打开的这个xls文件中写入并保存。  
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("报表生成发生异常");
            }
        }
    }
}

修改配置窗口

**    1、  对配置窗口的相关修改

//  Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using HalconDotNet;

namespace vision
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();//激活应用程序的显示风格,简单的说就是让你的控件(包括窗体)显示出来。
            Application.SetCompatibleTextRenderingDefault(false);//在应用程序范围内设置控件显示文本的默认方式(可以设为使用新的GDI+,还是旧的GDI),true使用GDI+方式显示文本,  false使用GDI方式显示文本。 
            HOperatorSet.SetSystem("clip_region", "false");//初始化halcon窗口控件,防止图片大于ROI被裁剪;
            Application.Run(new loadconfig());//在当前线程上开始运行标准应用程序消息循环
        }
    }
}
//  Form1.cs

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 HalconDotNet;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace vision
{
    public partial class Form1 : Form        // 对一些路径进行了修改,不在使用临时路径,改为pathtool中的路径方式
    {
        int CurrentCam = 1;
        string path = Application.StartupPath;
        string curpath;
 
        int curindex = 0;

        List<string> allim;
        HObject curimage;
        mainform mrf;//主窗口实例

        Camera curcam;
        List<ImageTool> temptool = new List<ImageTool>();
        public Form1(mainform mainf)
        {
            InitializeComponent();
            HOperatorSet.GenEmptyObj(out curimage);
            mrf = mainf;//将括号中的 mainform 主窗口传递给 mrf

            curcam = mrf.cameras[0];//将主窗口中的第 0 个相机设置为当前相机

            curpath = pathtool.currentProductPath + @"\" + "CCD1";//路径根据路径工具解析
            temptool = pathtool.ReadFromdat(curpath + ".dat");//加载工具配置文件

            for (int i = 0; i < temptool.Count; i++)  //读取检测工具
            {
                temptool[i].recon();//重生成控件界面
                temptool[i].init();//初始化
 
                temptool[i].issetting = true;//设置为检测状态
                temptool[i].hwin = hWindowControl1.HalconWindow;//窗口句柄赋值
                temptool[i].pannel = flowLayoutPanel1;//控件添加到 form1 中的控件上
                temptool[i].temp = temptool;//将工具队列传入
                flowLayoutPanel1.Controls.Add(temptool[i].con1);//
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //左切
            //ccdN ,N是否超出范围,不超出则减1
            int CurrentCam = int.Parse(curcam.logicName.Substring(3, 1));//取相机名称中的第3个(即数字)作为当前相机
            if (CurrentCam > 1)
            {
                string nextCameraName = "CCD" + (CurrentCam - 1).ToString();//相机序号减 1
                curcam = mrf.CCD[nextCameraName];//设置为下一个相机

                CurrentCam--;
                temptool = pathtool.ReadFromdat(pathtool.currentProductPath + @"\" + nextCameraName + ".dat");//读下一个相机的队列
                label1.Text = "相机" + CurrentCam.ToString();//界面上的相机名称进行替换

                getallim();//变得比之前复杂
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            int CurrentCam = int.Parse(curcam.logicName.Substring(3, 1));
            if (CurrentCam < mrf.cameras.Count)
            {
                string nextCameraName = "CCD" + (CurrentCam + 1).ToString();
                curcam = mrf.CCD[nextCameraName];//将主窗口中的下一个相机设置为当前相机
                CurrentCam++;

                temptool = pathtool.ReadFromdat(pathtool.currentProductPath + @"\" + nextCameraName + ".dat");
                label1.Text = "相机" + CurrentCam.ToString();
                getallim();
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            curpath = path + @"\CCD1";//先把当前相机1中的信息扫描一遍并展示
            allim = new List<string>();
            curpath = path + @"\CCD" + CurrentCam.ToString();
            getallim();
        }
        void getallim()
        {
            //重新绘制flowpanel
            button1.Enabled = true;
            button2.Enabled = true;

            flowLayoutPanel1.Controls.Clear();
            for (int i = 0; i < temptool.Count; i++)  //每个检测工具重新初始化
            {
                temptool[i].recon();//重新生成控件界面
                temptool[i].init();//参数初始化
                temptool[i].issetting = true;//当前检测状态


                //添加相应信息
                temptool[i].pannel = flowLayoutPanel1;
                temptool[i].temp = temptool;
                temptool[i].hwin = hWindowControl1.HalconWindow;
                flowLayoutPanel1.Controls.Add(temptool[i].con1);
            }

            //启动时候检查当前cam是否有存图文件夹,如果存在,检查是否有图
            
            //获取当前文件夹下bmp的数量和路径
          string   savepath = pathtool.currentProductPath + @"\" + curcam.logicName;
          if (Directory.Exists(savepath) == false)
          {
              Directory.CreateDirectory(savepath);
          }
          else
          {
              allim.Clear();
              DirectoryInfo Dir = new DirectoryInfo(savepath);
              foreach (FileInfo FI in Dir.GetFiles())
              {
                  // 这里写文件格式
                  if (System.IO.Path.GetExtension(FI.Name) == ".bmp")
                  {
                      allim.Add(FI.DirectoryName + @"\" + FI.Name);
                  }
              }
          }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (curindex - 1 > 0)
            {
                HOperatorSet.ReadImage(out curimage, allim[curindex - 1]);
                HTuple width, height;
                HOperatorSet.GetImageSize(curimage, out width, out height);
                HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, height - 1, width - 1);

                hWindowControl1.HalconWindow.DispObj(curimage);
                curindex--;
                button4.Enabled = true;
            }
            else if (curindex - 1 == 0)
            {
                HOperatorSet.ReadImage(out curimage, allim[curindex - 1]);
                HTuple width, height;
                HOperatorSet.GetImageSize(curimage, out width, out height);
                HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, height - 1, width - 1);

                hWindowControl1.HalconWindow.DispObj(curimage);
                curindex--;
                button3.Enabled = false;
            }
            else
            {
            }

            if (curimage != null)
            {
                foreach (ImageTool t in temptool)
                {
                    t.image = curimage;
                    t.method();
                    t.dispresult();
                }
            }
        }
        private void button4_Click(object sender, EventArgs e)
        {
            if (curindex + 1 < allim.Count - 1)
            {
                HOperatorSet.ReadImage(out curimage, allim[curindex + 1]);
                HTuple width, height;
                HOperatorSet.GetImageSize(curimage, out width, out height);
                HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, height - 1, width - 1);

                hWindowControl1.HalconWindow.DispObj(curimage);
                curindex++;
                button3.Enabled = true;
            }
            else if (curindex + 1 == allim.Count - 1)
            {
                HOperatorSet.ReadImage(out curimage, allim[curindex + 1]);
                HTuple width, height;
                HOperatorSet.GetImageSize(curimage, out width, out height);
                HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, height - 1, width - 1);

                hWindowControl1.HalconWindow.DispObj(curimage);
                curindex++;
                button4.Enabled = false;
            }
            else
            {
            }

            if (curimage != null)  //如果图片为空,则将图片进行逐一显示
            {
                foreach (ImageTool t in temptool)
                {
                    t.image = curimage;
                    t.method();
                    t.dispresult();
                }
              }
        }
        private void button5_Click(object sender, EventArgs e)
        {
            hWindowControl1.Focus();
            areatool areat = new areatool();

            areat.hwin = hWindowControl1.HalconWindow;
            areat.image = curimage;
            areat.pannel = flowLayoutPanel1;
            areat.issetting = true;
            areat.draw();
            areat.init();
            areat.method();

            temptool.Add(areat);
            flowLayoutPanel1.Controls.Add(areat.con);
            areat.temp = temptool;
        }
        private void button6_Click(object sender, EventArgs e)
        {
            mrf.CCD[curcam.logicName].toollist = temptool;
            mrf.updatedataset();//每次保存过后主界面的显示界面都要将list显示一遍
            //所有相机的全部重新保存
            foreach (Camera c in mrf.cameras)
            {
                pathtool.SaveTodat(c.toollist, pathtool.currentProductPath + @"\" + c.logicName + ".dat");//按照当前相机的路径进行保存
            }
        }
        private void button7_Click(object sender, EventArgs e)
        {
            FileStream fs = new FileStream(path + @"\" + CurrentCam + ".dat", FileMode.Open, FileAccess.Read);
            BinaryFormatter bf = new BinaryFormatter();

            temptool = (List<ImageTool>)bf.Deserialize(fs);
            fs.Close();

            foreach (ImageTool t in temptool)
            {
                t.init();
                t.image = curimage;
                t.temp = temptool;
                t.hwin = hWindowControl1.HalconWindow;
                t.pannel = flowLayoutPanel1;
                t.issetting = true;
                t.recon();
                flowLayoutPanel1.Controls.Add(t.con1);
            }
        }
    }
}
//  mainform.cs

//  增加检测设定窗口

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 HalconDotNet;
using System.Xml;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
using System.Globalization;

namespace vision
{
    public partial class mainform : Form
    {
        public List<Camera> cameras;
        public static string CurrentCCD;
        public Dictionary<string, Camera> CCD;

        Dictionary<string, HWindowControl> findhwin = new Dictionary<string, HWindowControl>();

        public static DataSet ds=new DataSet();

        public DataSet posdata;

        //旧配置加载
        public mainform()
        {
            InitializeComponent();
            findhwin.Clear();
            findhwin.Add("CCD1", hWindowControl2);
            findhwin.Add("CCD2", hWindowControl3);
            findhwin.Add("CCD3", hWindowControl4);
            findhwin.Add("CCD4", hWindowControl5);
            findhwin.Add("CCD5", hWindowControl6);
            posdata = new DataSet();
            cameras = new List<Camera>();
            CCD = new Dictionary<string, Camera>();

            CurrentCCD = "CCD1";
            loadCamera();

            foreach (Camera c in cameras)
            {
                c.toollist = pathtool.ReadFromdat(pathtool.currentProductPath + @"\" + c.logicName + ".dat");
            }
            label6.Text = pathtool.currentProduct;
            posdata.ReadXml(pathtool.currentProductPath + @"\Posdata.xml");

        //这里可以检查控制方面的连接是否正常,相机是否正常,如果不正常就提示

            InitialDataGrid(gridControl1, ds);

            updatedataset();

            for (int i = 0; i < gridView1.RowCount; i++)
            {
                gridView1.ExpandMasterRow(i);
            }
            this.ShowDialog();
        }
        //新配置
        public mainform(int a)
        {
            InitializeComponent();
            findhwin.Clear();
            findhwin.Add("CCD1", hWindowControl2);
            findhwin.Add("CCD2", hWindowControl3);
            findhwin.Add("CCD3", hWindowControl4);
            findhwin.Add("CCD4", hWindowControl5);
            findhwin.Add("CCD5", hWindowControl6);

            posdata = new DataSet();
            cameras = new List<Camera>();
            CCD = new Dictionary<string, Camera>();

            CurrentCCD = "CCD1";
            loadCamera();

            foreach (Camera c in cameras)
            {
                string cpath = pathtool.currentProductPath + @"\" + c.logicName + ".dat";
                pathtool.SaveTodat(c.toollist, cpath);
            }
            label6.Text = pathtool.currentProduct;
            InitPos();
            MessageBox.Show("是新建配置!");
            this.ShowDialog();
        }
        private void loadCamera()
        {
            //cameras.Clear();
            try
            {
                panel2.BackColor = Color.AliceBlue;

                XmlDocument xmlDocCamera = new XmlDocument();
                xmlDocCamera.Load("./Data/" + "camset.xml");
                XmlNodeList xnl;
                XmlNode xn;
                xn = xmlDocCamera.GetElementsByTagName("Camera")[0];
                xnl = xn.ChildNodes;
                int i = 1;
                if (cameras.Count == 0)
                {
                    foreach (XmlNode x in xnl)
                    {
                        Camera c = new Camera();
                        c.logicName = "CCD" + i;
                        c.halconwin.Add(findhwin[c.logicName]);
                        c.name = x.Attributes["name"].Value;
                        c.ExposureTime = int.Parse(x.Attributes["ExposureTime"].Value);
                        c.Gain = int.Parse(x.Attributes["Gain"].Value);
                        c.PixelDist = double.Parse(x.Attributes["PixelDist"].Value);
                        c.fps = int.Parse(x.Attributes["FPS"].Value);

                        c.rectifytype = int.Parse(x.Attributes["type"].Value);
                        c.halconwin.Clear();
                        c.halconwin.Add(findhwin[c.logicName]);

                        // c.OnImageProcessedEvent += new Camera.OnImageProcessedEventHandler(OnImageProcessedEvent);
                        cameras.Add(c);
                        i++;
                    }
                }
                for (int ci = 0; ci < cameras.Count; ci++)
                {
                    CCD.Add("CCD" + (ci + 1).ToString(), cameras[ci]);
                }
                
                CCD["CCD1"].halconwin.Add(hWindowControl1);
            }
            catch (Exception e)
            {
                MessageBox.Show("相机加载错误");
            }
        }
        private void InitPos()
        {  //新配置时候,生成一个位置全0的posdata,并写入xml
            posdata = new DataSet("posdata");
            DataTable dt = new DataTable("pos");
            dt.Columns.Add("cam1");
            dt.Columns.Add("cam2");
            dt.Columns.Add("cam3");
            dt.Columns.Add("cam4");
            dt.Columns.Add("cam5");
            dt.Columns.Add("cam6");

            dt.Columns.Add("ng");
            dt.Columns.Add("ok");

            dt.Columns.Add("blowwidth");

            dt.Columns.Add("speed");
            dt.Columns.Add("cam1expo");
            dt.Columns.Add("cam2expo");
            dt.Columns.Add("cam3expo");
            dt.Columns.Add("cam4expo");
            dt.Columns.Add("cam5expo");
            dt.Columns.Add("cam6expo");

            dt.Columns.Add("cam1gain");
            dt.Columns.Add("cam2gain");
            dt.Columns.Add("cam3gain");
            dt.Columns.Add("cam4gain");
            dt.Columns.Add("cam5gain");
            dt.Columns.Add("cam6gain");
            dt.Columns.Add("dist");

            DataRow row1 = dt.NewRow();
            row1["cam1"] = "0";
            row1["cam2"] = "0";
            row1["cam3"] = "0";
            row1["cam4"] = "0";
            row1["cam5"] = "0";
            row1["cam6"] = "0";
            row1["ng"] = "1000";
            row1["ok"] = "1500";
            row1["blowwidth"] = "500";
            row1["speed"] = "1000";

            row1["cam1expo"] = "20";
            row1["cam2expo"] = "20";
            row1["cam3expo"] = "20";
            row1["cam4expo"] = "20";
            row1["cam5expo"] = "20";
            row1["cam6expo"] = "20";

            row1["cam1gain"] = "280";
            row1["cam2gain"] = "280";
            row1["cam3gain"] = "280";
            row1["cam4gain"] = "280";
            row1["cam5gain"] = "280";
            row1["cam6gain"] = "280";
            row1["dist"] = "50";

            dt.Rows.Add(row1);

            posdata.Tables.Add(dt);

            posdata.WriteXml(pathtool.currentProductPath + @"\Posdata.xml");
        }
        private void button5_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void button2_Click(object sender, EventArgs e)//加载配置窗口
        {
            Form1 setform = new Form1(this);
            setform.ShowDialog();
        }
        private void InitialDataGrid(DevExpress.XtraGrid.GridControl grid, DataSet ds)
        {
            // 定义主表
            DataTable masterTable = new DataTable("CameraTable");
            DataTable detailTable = new DataTable("DetailTable");
            DataColumn parentColumn = new DataColumn("CameraID", typeof(string));
            masterTable.Columns.Add(parentColumn);

            DataColumn childrenColumn = new DataColumn("CCD", typeof(string));
            detailTable.Columns.Add(childrenColumn);

            detailTable.Columns.AddRange(new DataColumn[] {  
             new DataColumn("检测项",typeof(string)),  
             new DataColumn("名称",typeof(string)),  
             new DataColumn("下限",typeof(double)),  
             new DataColumn("上限",typeof(double)),
             new DataColumn("测量",typeof(double)),
             new DataColumn("合格率",typeof(double)),
             });

            ds.Tables.AddRange(new DataTable[] { masterTable.Copy(), detailTable.Copy() });
            // 创建表关系  
            DataRelation relation = new DataRelation("detailTable", ds.Tables[0].Columns[0], ds.Tables[1].Columns[0], false);
            ds.Relations.Add(relation); // 添加  
            grid.DataSource = ds.Tables[0];  // 指定数据源  
            ds.Clear();
            gridView1.ExpandMasterRow(0);
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                gridView1.ExpandMasterRow(i);
            }
        }
        public void updatedataset()
        {
            //update写入时候,计算出当前tool的参数位置,结果显示位置,并传递给它
            
            ds.Clear();
            DataTable masterTable = new DataTable("CameraTable");
            DataTable detailTable = new DataTable("DetailTable");
            masterTable = ds.Tables["CameraTable"];
            detailTable = ds.Tables["DetailTable"];

            int rowcount = 0;

            for (int i = 0; i < cameras.Count; i++)
            {
                masterTable.Rows.Add(cameras[i].logicName);
            }
            for (int i = 0; i < cameras.Count; i++)
            {
                for (int j = 0; j < cameras[i].toollist.Count; j++)
                {
                    cameras[i].toollist[j].posdataset.Clear();
                    for (int k = 0; k < cameras[i].toollist[j].ischeck.Count; k++)
                    {
                        if (cameras[i].toollist[j].ischeck[k])
                        {
                            //测量名//用户自定义名       下限 上限 实际值 合格率
                            detailTable.Rows.Add(cameras[i].logicName, cameras[i].toollist[j].absname[k], cameras[i].toollist[j].defname[k], cameras[i].toollist[j].xx[k], cameras[i].toollist[j].sx[k], cameras[i].toollist[j].result[k], 0);
                            cameras[i].toollist[j].posdataset.Add(rowcount);
                            rowcount++;
                        }
                    }
                }
            }
            gridView1.ExpandMasterRow(0);
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                gridView1.ExpandMasterRow(i);
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            获取日期  
            string SaveFileName = DateTime.Now.Date.ToString("yyyy", DateTimeFormatInfo.InvariantInfo) + DateTime.Now.Date.ToString("MM", DateTimeFormatInfo.InvariantInfo);
            SaveFileName += DateTime.Now.Date.ToString("dd", DateTimeFormatInfo.InvariantInfo) + DateTime.Now.ToString("hh", DateTimeFormatInfo.InvariantInfo);
            SaveFileName += DateTime.Now.ToString("mm", DateTimeFormatInfo.InvariantInfo) + DateTime.Now.ToString("ss", DateTimeFormatInfo.InvariantInfo);

            string templatepath = String.Format(@"{0}\{1}", pathtool.exepath, SaveFileName);
            templatepath = templatepath + "统计报表.xls";
            try
            {
                HSSFWorkbook wk = new HSSFWorkbook();
                //创建一个Sheet  
                ISheet sheet = wk.CreateSheet("检测结果统计");
                //在第一行创建行  
                IRow row = sheet.CreateRow(0);
                //在第一行的第一列创建单元格  
                ICell cell = row.CreateCell(0);
                cell.SetCellValue("检测项");
                cell = row.CreateCell(1);
                cell.SetCellValue("自定义名称");
                cell = row.CreateCell(2);
                cell.SetCellValue("上限");
                cell = row.CreateCell(3);
                cell.SetCellValue("下限");
                cell = row.CreateCell(4);
                cell.SetCellValue("OK");
                cell = row.CreateCell(5);
                cell.SetCellValue("NG");
                cell = row.CreateCell(6);
                cell.SetCellValue("合格率");
                合并所有tool的 goodcount  badcount
                List<int> allgoodcount = new List<int>();
                List<int> allbadcount = new List<int>();
                foreach (Camera c in cameras)
                {
                    foreach (ImageTool t in c.toollist)
                    {
                        for (int i = 0; i < t.goodcount.Count; i++)
                        {
                            allgoodcount.Add(t.goodcount[i]);
                            allbadcount.Add(t.badcount[i]);
                        }
                    }
                }
                
                DataRowCollection drc = ds.Tables["detailTable"].Rows;
                for (int i = 0; i < drc.Count; i++)
                {
                    DataRow dr = drc[i];
                    string s = dr[1].ToString();//检测项名称
                    string s1 = dr[2].ToString();//自定义名称

                    double xx = (double)dr[3];
                    double sx = (double)dr[4];

                    double hegelv = (double)dr[6];

                    row = sheet.CreateRow(i + 1);
                    cell = row.CreateCell(0);
                    cell.SetCellValue(s);
                    cell = row.CreateCell(1);
                    cell.SetCellValue(s1);
                    cell = row.CreateCell(2);
                    cell.SetCellValue(xx);
                    cell = row.CreateCell(3);
                    cell.SetCellValue(sx);
                    cell = row.CreateCell(4);
                    cell.SetCellValue(allgoodcount[i]);
                    cell = row.CreateCell(5);
                    cell.SetCellValue(allbadcount[i]);

                    cell = row.CreateCell(6);

                    cell.SetCellValue(hegelv);
                }

                using (FileStream fs = File.OpenWrite(templatepath))
                {
                    wk.Write(fs);//向打开的这个xls文件中写入并保存。  
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("报表生成发生异常");
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值