C# 调用 origin 批量作图

C# 调用 origin 批量作图

质谱数据处理软件中,需要批量粘贴 Origin的矢量图到Word和PPT中,由于出图量大,需要用代码生成。

代码参考了Origin 9.2中自带的Automation Server示例代码。

本文涉及两部分内容,如何通过C#调用Origin.dll 和 interop.word对word 的读写操作。

目标:

文件是一个.opj文件,内容如下。我们通过C#调用相关接口来修改数据和标签。

 并且输出矢量图 自动粘贴到word里。

 

 注意:

http://originlab.com/Orglab/dl.aspx

这个是origin官方的com组件dll文件。这个官网的文件版本是1.0.0版本,没法用。要用origin 9 以上安装目录中自带的8.0.0.0版本 origin.dll。

这个是origin官方的com组件dll文件。这个官网的文件版本是1.0.0版本,没法用。要用origin 9 以上安装目录中自带的8.0.0.0版本 origin.dll。

这个是origin官方的com组件dll文件。这个官网的文件版本是1.0.0版本,没法用。要用origin 9 以上安装目录中自带的8.0.0.0版本 origin.dll。

orgin的外部程序调用Origin指南在这里:

 http://www.originlab.com/doc/COM/

http://www.originlab.com/doc/LabTalk

思路:

C#调用Origin 类库 将opj文件加载,获取对象后

origin 有Labtalk函数和X-Function函数两大系列的外部调用,

我们利用C#调用这些命令实现内容的修改。

      private Origin.IOApplication App;
      private Origin.Worksheet m_targetWks;
      private Origin.GraphLayer gl;

//单击一个按钮 创建或关闭origin实例。

   private void button9_Click(object sender, EventArgs e)
        {
            if (CheckMesg3())
            {
                if (!IsConnectedToOrigin())
                {
                    if (ConnectToOrigin())
                    {
                        if (!PrepareOrigin())
                        {
                            DisconnectFromOrigin();
                        }
                    }
                }
            }
        }
   //origin 单击事件中用到的准备函数实现如下
  //这系列函数的原版在origin的automation Server文件夹中。
private bool IsConnectedToOrigin() { return App != null; } private bool ConnectToOrigin() { DisconnectFromOrigin(); try { // if (existingInstanceCheckBox.Checked) // App = new Origin.ApplicationSI(); // SI for existing instance // else App = new Origin.Application(); // non-SI for new instance } catch (Exception e) { string strMsg = "Failed to connect to Origin. " + e.Message; // ShowMessage(strMsg); } return App != null; } private void DisconnectFromOrigin() { if (IsConnectedToOrigin()) { System.Runtime.InteropServices.Marshal.FinalReleaseComObject(App); App = null; } } private bool PrepareOrigin() { string strFilePath = textBox.Text; App.Visible = Origin.MAINWND_VISIBLE.MAINWND_SHOW; // ---------- Open user specified project // GetOriginProjectFileName(ref str1);//原来是ref 进去处理了又返回引用类型 if (!App.Load(strFilePath, false)) { // ShowMessage("Failed to load Origin project " + str1); return false; } // ---------- Attach to target worksheet m_targetWks = GetOriginWorksheet("Book1", "Sheet1", true); // true = create if not found if (null == m_targetWks) { return false; } // ---------- Clear target worksheet m_targetWks.ClearData(0, -1); // ---------- Make sure target worksheet has 3 columns if (m_targetWks.Cols < 5) { m_targetWks.Columns.Add(); } // ---------- Set column long names and units // m_targetWks.Columns[0].LongName = "Time"; // m_targetWks.Columns[0].Units = "h"; // m_targetWks.Columns[1].LongName = "N29rate"; // m_targetWks.Columns[1].Units = "rate"; // m_targetWks.Columns[2].LongName = "N30rate"; // m_targetWks.Columns[2].Units = "rate."; // m_targetWks.Columns[3].LongName = "N30rateFit"; // m_targetWks.Columns[3].Units = "rate."; // ---------- Add data columns to Graph1 Origin.GraphPage gp = App.GraphPages["Graph1"]; if (null != gp) { gl = (Origin.GraphLayer)gp.Layers[0]; //先建立一个Graph1 将第一页设为gL if (null != gl) {
          //原版函数在此新建了涂层
// Origin.DataRange dr = m_targetWks.NewDataRange(0, 0, 0, 2); // gl.DataPlots.Add(dr, Origin.PLOTTYPES.IDM_PLOT_SCATTER); // gl.Execute("layer.x.to = 8;"); // gl.Execute("layer.y.from = 0.25; layer.y.to = 10.25;"); // Setup the Y axis to auto adjust the scale to fit any data // points that are less than or greater than the scale's range. // gl.Execute("layer.disp = layer.disp | hex(1000);"); } else { return true; // ShowMessage("Failed to get graph layer."); } } else // ShowMessage("Failed to get graph page named "Graph1"."); { return true; } return true; }
        private Origin.WorksheetPage GetOriginWorksheetPage(string strPageName, bool bCreateIfNotFound)
        {
            Origin.WorksheetPage wksPg = App.WorksheetPages[strPageName];
            if (null == wksPg && bCreateIfNotFound)
            {
                strPageName = App.CreatePage((int)Origin.PAGETYPES.OPT_WORKSHEET, strPageName, "W", 2);
                wksPg = App.WorksheetPages[strPageName];
            }
            return wksPg;
        }

        private Origin.Worksheet GetOriginWorksheet(string strPageName, string strSheetName, bool bCreateIfNotFound)
        {
            Origin.WorksheetPage wksPg = GetOriginWorksheetPage(strPageName, bCreateIfNotFound);
            if (null == wksPg)
                return null;

            Origin.Worksheet wks = (Origin.Worksheet)wksPg.Layers[strSheetName];
            if (null == wks && bCreateIfNotFound)
            {
                wks = (Origin.Worksheet)wksPg.Layers.Add(strSheetName, 0, null, 0, null);
                wks.Activate();
            }

            return wks;
        }
private void button15_Click(object sender, EventArgs e)
        {


            if (CheckMesg3())
            {//checkmesg3判断是否选中了输出目录
                string Str_timeCurrent = DateTime.Now.ToString("yyyy年MM月dd日HHmmss") + "批量拟合opj";
                string Str_path = textBox2.Text.Substring(textBox2.Text.LastIndexOf("\") + 1, textBox2.Text.LastIndexOf(".") - textBox2.Text.LastIndexOf("\") - 1);

                if (!Directory.Exists(textBox2.Text.Substring(0, textBox2.Text.LastIndexOf(".")) + Str_timeCurrent + "\"))
                {
                    Directory.CreateDirectory(textBox2.Text.Substring(0, textBox2.Text.LastIndexOf(".")) + Str_timeCurrent + "\");
                }
                //文件路径
                string str_Content;//文件内容
                MSWord.Application app_Word;//Word应用程序变量
                MSWord.Document document_Word;//Word文档变量
                                              //  object path = textBox2.Text.Substring(0, textBox2.Text.LastIndexOf(".")) + time333 + "\" + time333 + ".docx";//保存为Word2003文档
                object path = textBox2.Text.Substring(0, textBox2.Text.LastIndexOf(".")) + Str_timeCurrent + "\" + Str_path + Str_timeCurrent + ".docx";//保存为Word2003文档
                                                                                                                                                         // path = "d:\myWord.doc";//保存为Word2007文档
                app_Word = new MSWord.ApplicationClass();//初始化
                if (File.Exists((string)path))
                {
                    // File.Delete((string)path);
                }
                //由于使用的是COM 库,因此有许多变量需要用Missing.Value 代替
                Object Nothing = Missing.Value;
                //新建一个word对象
                document_Word = app_Word.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
                object format = MSWord.WdSaveFormat.wdFormatDocumentDefault;
                //WdSaveDocument为Word2003文档的保存格式(文档后缀.doc)wdFormatDocumentDefault为Word2007的保存格式(文档后缀.docx)

                //    OpenDocFile(textBox2.Text.Substring(0, textBox2.Text.LastIndexOf("\") + 1) + time333 + "\"+time333+".doc");
               // Origin.DataRange dr = m_targetWks.NewDataRange(0, 0, 0, 2);
                //   gl.DataPlots.Add(dr, Origin.PLOTTYPES.IDM_PLOT_SCATTER);
                for (int i = 0; i < ltl.Count; i++)
                {//从我的自定义数据类型listTupleList中循环读取数据并作图
                    m_targetWks.ClearData();
                    //先清空workbook1

                    var tl = ltl[i];
                    double[,] data = new double[tl.Item1.Count, 4]; //深度5 宽度4 的数组
                    for (int a = 0; a < tl.Item1.Count; a++)
                    {

                        data[a, 0] = tl.Item1[a];///x 赋值数组 这里是重点 给每列数分别赋值
                        data[a, 1] = tl.Item2[a];//y1赋值数组
                        data[a, 2] = tl.Item2[a];//y2赋值数组
                        data[a, 3] = tl.Item3[a];//y2赋值数组
                    }
                    m_targetWks.SetData(data, -1, 0); // -1 for append row, 0 for first column

                    Origin.GraphPage gp = App.GraphPages["Graph1"];
                    if (null != gp)
                    {
                        gl = (Origin.GraphLayer)gp.Layers[0];
                        //获取第一个图层为要修改的层
                        if (null != gl)
                        {

                            var max = maxValue2(tl.Item2.ToArray(), tl.Item3.ToArray());
                            var min = minValue2(tl.Item2.ToArray(), tl.Item3.ToArray());
                            var xmax = maxValue2(tl.Item1.ToArray(), tl.Item1.ToArray());
                            var xmin = minValue2(tl.Item1.ToArray(), tl.Item1.ToArray());
                            //   int inc=   100* Convert.ToInt32(max / 100);
                            string minRate = (min - 0.15 * (max - min)).ToString();
                            string maxRate = (max + (max - min) * 0.55).ToString();
                            string minAxis = (xmin - 0.1 * (xmax - xmin)).ToString();
                            string maxAxis = (xmax + (xmax - xmin) * 0.1).ToString();

                            //下面使用暴力穷举法调整刻度,解决问题最重要,算法想了很久想不出来 —— ——#
                            int inc = 40;
                            if (max > 100)
                            {
                                inc = 40;
                            }
                            if (max > 200)
                            {
                                inc = 60;
                            }
                            if (max > 400)
                            {
                                inc = 120;
                            }
                            if (max > 800)
                            {
                                inc = 220;
                            }

                            if (max > 1500)
                            {
                                inc = 400;
                            }
                            if (max > 2500)
                            {
                                inc = 500;
                            }
                            if (max > 2500)
                            {
                                inc = 600;
                            }
                            if (max > 4000)
                            {
                                inc = 1000;
                            }
                            if (max > 8000)
                            {
                                inc = 2000;
                            }


                            int incx = 2;
                            if (max > 10)
                            {
                                inc = 4;
                            }
                            if (max > 50)
                            {
                                inc = 10;
                            }
                            if (max > 200)
                            {
                                inc = 50;
                            }
                            if (max > 400)
                            {
                                inc = 120;
                            }

                            //每个对象都有 Execute函数 用来执行 LabTalk函数。
                            gl.Execute("layer.x.from =" + minAxis + ";" + "layer.x.to = " + maxAxis + ";");
                            gl.Execute("layer.y.from =" + minRate + ";layer.y.to =" + maxRate + ";");
                            gl.Execute("layer.y.inc = " + inc.ToString() + ";");
                            gl.Execute("layer.x.inc = " + incx.ToString() + ";");


                            gl.Execute("laylink igl:=1 destlayers:=2:0 XAxis:=1;");
                            gl.Execute("laylink igl:=1 destlayers:=2:0 YAxis:=1;");
                            // Setup the Y axis to auto adjust the scale to fit any data
                            // points that are less than or greater than the scale's range.
                            //   gl.Execute("layer.disp = layer.disp | hex(1000);");
                            //  gl.Execute("label - n text " + "Slope"  + ";");

                            gl.Execute("label - n text " + @"slope(61)" + tl.Item5[1].ToString("#0.00000") + ";");
                            gl.Execute("label - n text1 " + @"R+(2)(61)" + tl.Item5[2].ToString("#0.00000") + ";");
                            gl.Execute("label - n text2 " + @"p(61)" + tl.Item5[3].ToString("#0.00000") + ";");
                            gl.Execute("label - n XB " + tl.Item4[1] + ";");

                            // (61)这个写法是Lable 说明里的 ascii码写法
                            string s = textBox2.Text.Substring(0, textBox2.Text.LastIndexOf(".")) + Str_timeCurrent + "\" + tl.Item4[0] + ".opj";
                            word.Paragraph para1 = document_Word.Content.Paragraphs.Add(ref Nothing);
                            str_Content = tl.Item4[0] + "
";
                            para1.Range.Text = str_Content;
                            word.Paragraph para = document_Word.Content.Paragraphs.Add(ref Nothing);

                            App.Save(s);
                            Delay_my(1000);
                            gl.Execute("clipboard");
                            para.Range.Paste();
                            //   para.Range.Text = "
";
                            Delay_my(1000);
                            para.Range.InsertParagraphAfter();//添加一次回车

                            //   App.Save(s);
                            //将wordDoc 文档对象的内容保存为DOC 文档,并保存到path指定的路径
                            document_Word.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);


                        }


                    }
                }


                //     object format = MSWord.WdSaveFormat.wdFormatDocumentDefault;

                //将wordDoc 文档对象的内容保存为DOC 文档,并保存到path指定的路径
                document_Word.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
                //关闭wordDoc文档
                document_Word.Close(ref Nothing, ref Nothing, ref Nothing);
                //关闭wordApp组件对象
                app_Word.Quit(ref Nothing, ref Nothing, ref Nothing);

            }
        }
  public double maxValue2(double[] s, double[] s2)
        {
            double temp = s[0];
            for (int i = 0; i < s.Length; i++)
            {
                if (temp <= s[i])
                {
                    temp = s[i];
                }
            }

            double temp2 = s[0];
            for (int i = 0; i < s2.Length; i++)
            {
                if (temp2 <= s2[i])
                {
                    temp2 = s2[i];
                }
            }
            if (temp >= temp2)
            {
                return (temp);
            }

            else
            {
                return (temp2);
            }

        }

        public double minValue2(double[] s, double[] s2)
        {
            double temp = s[0];
            for (int i = 0; i < s.Length; i++)
            {
                if (temp >= s[i])
                {
                    temp = s[i];
                }
            }

            double temp2 = s[0];
            for (int i = 0; i < s2.Length; i++)
            {
                if (temp2 >= s2[i])
                {
                    temp2 = s2[i];
                }
            }
            if (temp <= temp2)
            {
                return (temp);
            }

            else
            {
                return (temp2);
            }

        }
原文地址:https://www.cnblogs.com/lyichemistry/p/6017149.html