EA 插件开发,winfrom dataGridView1 异步逐行添加数据

using EA;
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static UmlDemo1.UserControlFeatureList;

namespace UmlDemo1
{
    public partial class UserControlFeatureList : UserControl
    {
        public UserControlFeatureList()
        {
            InitializeComponent();
            // Add CellClick event listener
            dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);
            // 监听鼠标右键事件
            dataGridView1.MouseClick += new MouseEventHandler(dataGridView1_MouseClick);
        }
        public class Person
        {
            public string 系统 { get; set; }

            public string 功能 { get; set; }

            public string Note { get; set; }
        }
        private System.ComponentModel.BackgroundWorker worker;
        private delegate void AddDataGridViewRowDelegate(Person person);
        private async void UserControlFeatureList_Load(object sender, EventArgs e)
        {
            pictureBox1.Visible = true;
            //dataGridView1.Visible = false;
            // 先显示窗口
            this.Show();
            Control.CheckForIllegalCrossThreadCalls = false;
            // 实例化后台工作线程组件
            worker = new System.ComponentModel.BackgroundWorker();
            worker.DoWork += DoWork;
            worker.RunWorkerAsync();
            // 设置 ComboBoxControlType 的默认值为 "关系类型"
            comboBoxConnector_Type.SelectedItem = "关系类型";
            toolStripStatusLabel1.Text = "";

        }
        private int _dotIndex = 0;
        private enum Status { Busy, Ready };
        private Timer _timer;
        private System.Windows.Forms.Timer _hideProgressBarTimer;
        private void UpdateStatus(Status status)
        {
            if (this.statusStrip1.InvokeRequired)
            {
                this.statusStrip1.Invoke(new MethodInvoker(delegate { this.UpdateStatus(status); }));
            }
            else
            {
                switch (status)
                {
                    case Status.Busy:
                        _dotIndex = (_dotIndex + 1) % 4;
                        toolStripStatusLabel1.Text = "忙碌中" + new string('.', _dotIndex);
                        _timer.Start();
                        
                        break;
                    case Status.Ready:
                        toolStripStatusLabel1.Text = "";                        
                        _timer.Stop();
                        _hideProgressBarTimer.Start();
                        break;
                }
            }
        }

        private void _timer_Tick(object sender, EventArgs e)
        {
            _dotIndex = (_dotIndex + 1) % 4;
            toolStripStatusLabel1.Text = "忙碌中" + new string('.', _dotIndex);
        }
        private void _timer_hideProgressBar(object sender, EventArgs e)
        {
            toolStripProgressBar1.Visible = false;
            _hideProgressBarTimer.Stop();
        }

        private void DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            // 设置进度条最大值为100
            toolStripProgressBar1.Maximum = Maximum;
            // 设置进度条步长为1
            toolStripProgressBar1.Step = 1;
            _timer = new Timer();
            _timer.Interval = 500; // 设置定时器间隔为500ms
            _timer.Tick += _timer_Tick;

            _hideProgressBarTimer = new System.Windows.Forms.Timer();
            _hideProgressBarTimer.Interval = 3000; // 设置定时器间隔为 3000ms
            _hideProgressBarTimer.Tick += _timer_hideProgressBar;

            // 更新状态栏为忙碌状态
            UpdateStatus(Status.Busy);
            // 模拟异步加载数据,逐行添加到DataGridView控件中
            for (int i = 0; i < Maximum; i++)
            {
                // 模拟异步加载数据需要一定的时间
                System.Threading.Thread.Sleep(100);

                var rowValue1 = $"第{i}行列1";
                var rowValue2 = $"第{i}行列2";
                Person person = new Person() { 系统 = "王五"+i, 功能 = "" + i, Note = "男" + i };
                // 添加数据到DataGridView控件中
                AddDataGridViewRow(person);                
            }
            // 更新状态栏为就绪状态
            UpdateStatus(Status.Ready);
        }

        private void AddDataGridViewRow(Person person)
        {
            if (this.dataGridView1.InvokeRequired)
            {
                // 如果是异步后台线程触发的,那么需要通过委托回调通知UI线程更新DataGridView控件中的数据
                this.Invoke(new AddDataGridViewRowDelegate(AddDataGridViewRow), new object[] { person });
            }
            else
            {
                // 在UI线程中更新DataGridView控件中的数据
                if (dataGridView1.Rows.Count > 0)
                {
                    DataGridViewRow row = (DataGridViewRow)dataGridView1.Rows[0].Clone();
                }                
                //row.Cells["系统"].Value = arg1;
                //row.Cells["功能"].Value = arg2;
                dataGridView1.Rows.Add(person.系统, person.功能, person.Note);
                toolStripProgressBar1.PerformStep();
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridView_CellClick(sender, e, dataGridView1);
        }
        private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
        {
            DataGridView_MouseClick(sender, e, dataGridView1);
        }
        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {

        }

        
        private void DataGridView_CellClick(object sender, DataGridViewCellEventArgs e, DataGridView dgv)
        {
            // && e.ColumnIndex >= 0)
            // Make sure the clicked cell is valid
            if (e.RowIndex >= 0)
            {
                DataGridViewRow row = dgv.Rows[e.RowIndex];
                if (e.ColumnIndex >= 0)
                {
                    DataGridViewCell cell = row.Cells[e.ColumnIndex];
                }
                string DiagramID = "";
                if (dgv.Columns.Contains("DiagramID") && row.Cells["DiagramID"].Value != null)
                {
                    DiagramID = row.Cells["DiagramID"].Value.ToString();
                }
                try
                {
                    if (DiagramID != "")
                    {
                        EA.Diagram diagram = repository.GetDiagramByID(int.Parse(DiagramID));
                        if (diagram != null)
                        {
                            repository.ShowInProjectView(diagram);
                        }
                    }

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }


            }


        }

        // 单击右键时,在合适的位置弹出contextMenuStrip1
        private void DataGridView_MouseClick(object sender, MouseEventArgs e, DataGridView dgv)
        {
            if (e.Button == MouseButtons.Right)
            {
                // 获取当前鼠标单击的位置
                System.Drawing.Point location = dgv.PointToClient(Cursor.Position);
                // 获取鼠标点击位置
                DataGridView.HitTestInfo hti = dgv.HitTest(e.X, e.Y);
                if (hti.Type == DataGridViewHitTestType.Cell)
                {
                    // 设置当前单元格为选中状态
                    dgv.CurrentCell = dgv.Rows[hti.RowIndex].Cells[hti.ColumnIndex];
                    // 设置当前行为选中状态
                    dgv.Rows[hti.RowIndex].Selected = true;
                    // 弹出右键菜单
                    contextMenuStrip1.Show(dgv, location);
                }
            }
        }

        private EA.Repository repository = null;
        private string title = "";
        private string comboBoxConnector_Type_SelectedItem = null;
        private int Maximum = 120;
        public async void ShowList(EA.Repository repository, string title, DateTime? startTimeVal = null, DateTime? endTimeVal = null)
        {
            this.repository = repository;
            this.title = title;
            DateTime today = DateTime.Now; //获取当前日期
            DateTime lastDay = today.AddDays(-30); //获取当前日期的前一天
            if (startTimeVal == null)
            {
                startTimeVal = lastDay;
            }
            if (endTimeVal == null)
            {
                endTimeVal = today;
            }
            string sql = null;
            PublicClass publicClass1 = new PublicClass();


            // 获取关系类型   comboBoxConnector_Type                      
            if (comboBoxConnector_Type.Items.Count <= 1)
            {
                List<Dictionary<string, string>> dataListElementType = await System.Threading.Tasks.Task.Run(() =>
                {
                    string sql1 = "SELECT DISTINCT Connector_Type FROM `t_connector`";
                    return publicClass1.Sql2Xml(repository, sql1);
                });
                comboBoxConnector_Type.Items.Clear();
                comboBoxConnector_Type.Items.Add("关系类型");
                foreach (var item in dataListElementType)
                {
                    comboBoxConnector_Type.Items.Add(item["Connector_Type"]);
                }
                comboBoxConnector_Type.SelectedItem = "关系类型";
            }
            if (comboBoxConnector_Type.SelectedItem != null || comboBoxConnector_Type.SelectedItem != "关系类型")
            {
                this.comboBoxConnector_Type_SelectedItem = comboBoxConnector_Type.SelectedItem.ToString();
            }
            switch (title)
            {
                case "功能列表":
                    //List> DataFlowList = await GetFeatureList(repository, startTimeVal, endTimeVal);
                    //publicClass1.LoadDataElements(dataGridView1, DataFlowList);
                    pictureBox1.Visible = false;
                    dataGridView1.Visible = true;

                    break;

                default:
                    break;

            }


        }

        private async Task<List<Dictionary<string, string>>> getDiagramList(EA.Repository repository)
        {
            List<Dictionary<string, string>> dataList = new List<Dictionary<string, string>>();
            try
            {
                string sql = null;
                PublicClass publicClass1 = new PublicClass();
                // 异步执行耗时操作
                dataList = await System.Threading.Tasks.Task.Run(() =>
                {
                    string Package_ID_str = publicClass1.GetChindPackages(repository);
                    sql = "SELECT 'diagram' as BelongsType,t.Package_ID,p.Parent_ID,p.`Name` as Package_Name,t.CreatedDate, t.ModifiedDate, t.Diagram_ID, t.Name AS Diagram_Name, t.Diagram_Type,t.Author as author,t.Stereotype FROM t_diagram t left join t_package p on t.Package_ID=p.Package_ID WHERE 1 ";
                    if (Package_ID_str != "")
                    {
                        sql = sql + " and t.Package_ID in(" + Package_ID_str + ") ";
                    }
                    sql = sql + " order by t.Diagram_ID desc";
                    Console.WriteLine(sql);
                    // 耗时操作代码,例如访问网络、读写文件等
                    return publicClass1.Sql2Xml(repository, sql);
                });
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return dataList;
        }

        private async Task<List<Dictionary<string, string>>> getConnectorList(EA.Repository repository, List<Dictionary<string, string>> DiagramList)
        {
            List<Dictionary<string, string>> connectorList = new List<Dictionary<string, string>>();
            foreach (var dataDict in DiagramList)
            {
                EA.Diagram currentDiagram = repository.GetDiagramByID(int.Parse(dataDict["Diagram_ID"]));
                if (currentDiagram == null)
                {
                    continue;
                }
                // Iterate through the diagram links in the current diagram
                foreach (EA.DiagramLink diagramLink in currentDiagram.DiagramLinks)
                {
                    Dictionary<string, string> rowDict = new Dictionary<string, string>(); // 新建一个字典,保存每个数据行的属性值
                    rowDict["DiagramID"] = currentDiagram.DiagramID.ToString();
                    rowDict["DiagramObjects"] = currentDiagram.ObjectType.ToString();
                    rowDict["CreatedDate"] = currentDiagram.CreatedDate.ToString();
                    rowDict["ModifiedDate"] = currentDiagram.ModifiedDate.ToString();
                    rowDict["ConnectorID"] = "";
                    rowDict["Direction"] = "";
                    rowDict["fangxiang"] = "";
                    rowDict["Type"] = "";
                    rowDict["MetaType"] = "";
                    rowDict["ConveyedItems"] = "";
                    rowDict["sourceElementName"] = "";
                    rowDict["ParentSourceElementName"] = "";
                    rowDict["targetElementName"] = "";
                    rowDict["ParentTargetElementName"] = "";
                    // 如果它的源 ID 和目标 ID 与element 的ID匹配,则将其打印出来
                    if (diagramLink != null && diagramLink.ConnectorID > 0)
                    {
                        EA.Connector connector = null;
                        try
                        {
                            connector = repository.GetConnectorByID(diagramLink.ConnectorID);
                        }
                        catch
                        {
                        }
                        if (connector == null)
                        {
                            continue;
                        }

                        if (connector != null)
                        {
                            if (comboBoxConnector_Type_SelectedItem != null|| comboBoxConnector_Type_SelectedItem != "关系类型")
                            {
                                if (comboBoxConnector_Type_SelectedItem != connector.Type.ToString())
                                {
                                    continue;
                                }
                            }
                            rowDict["ConnectorID"] = connector.ConnectorID.ToString();
                            rowDict["Direction"] = connector.Direction.ToString();
                            rowDict["MetaType"] = connector.MetaType.ToString();
                            rowDict["Type"] = connector.Type.ToString();
                            if (rowDict["Direction"].Contains("->"))
                            {
                                rowDict["fangxiang"] = "->";
                            }
                            List<string> arr1 = new List<string>();
                            foreach (dynamic item in connector.ConveyedItems)
                            {
                                if (item != null && item.Name != null)
                                {
                                    arr1.Add(item.Name.ToString());
                                }
                            }
                            rowDict["ConveyedItems"] = string.Join(",", arr1);
                            //rowDict["ConveyedItems"] = string.Join(",", connector.ConveyedItems.Select(item => item.Name).Aggregate((current, next) => current + "," + next));
                            // 获取 Source 和 Target 对象的 Element 对象
                            EA.Element sourceElement = repository.GetElementByID(connector.ClientID);
                            if (sourceElement != null)
                            {
                                rowDict["sourceElementName"] = sourceElement.Name;
                                if (sourceElement.ParentID > 0)
                                {
                                    EA.Element ParentSourceElement = repository.GetElementByID(sourceElement.ParentID);
                                    if (ParentSourceElement != null)
                                    {
                                        rowDict["ParentSourceElementName"] = ParentSourceElement.Name;
                                    }
                                }
                            }
                            EA.Element targetElement = repository.GetElementByID(connector.SupplierID);
                            if (targetElement != null)
                            {
                                rowDict["targetElementName"] = targetElement.Name;
                                if (targetElement.ParentID > 0)
                                {
                                    EA.Element ParentTargetElement = repository.GetElementByID(targetElement.ParentID);
                                    if (ParentTargetElement != null)
                                    {
                                        rowDict["ParentTargetElementName"] = ParentTargetElement.Name;
                                    }
                                }
                            }
                        }
                        connectorList.Add(rowDict);



                        //    // 获取该连接线的目标元素(Target)
                        //    EA.Element targetElement = repository.GetElementByGuid(diagramLink.TargetInstanceUID);
                        //    if (targetElement != null)
                        //    {
                        //        // 获取连接线的Geometry信息,包括箭头方向信息
                        //        string geometry = diagramLink.Geometry;
                        //        // 此处根据geometry信息获取箭头属性等其他信息
                        //        Console.WriteLine($"连接线从 {targetElement.Name} 到 {targetElement.Name},箭头方向为 {geometry}。");

                        //    }

                    }
                }
            }
            return connectorList;
        }

        private async Task<List<Dictionary<string, string>>> GetFeatureList(EA.Repository repository, DateTime? startTimeVal = null, DateTime? endTimeVal = null)
        {
            List<Dictionary<string, string>> diagramList = await getDiagramList(repository);
            Console.WriteLine(diagramList);
            List<Dictionary<string, string>> connectorList = await getConnectorList(repository, diagramList);
            Console.WriteLine(connectorList);
            return connectorList;
        }
        private void exportExcel_Click(object sender, EventArgs e)
        {
            MessageBox.Show("导出数据");
            PublicClass publicClass1 = new PublicClass();
            publicClass1.doExportExcel(dataGridView1);
        }

        private void comboBoxConnector_Type_SelectedIndexChanged(object sender, EventArgs e)
        {
            pictureBox1.Visible = true;
            dataGridView1.Visible = false;
            // 获取当前标签页的title
            ShowList(repository, title);
        }

        private void findInBrowserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EA.Element element = repository.GetTreeSelectedObject() as EA.Element; // 获取当前选中的元素
            EA.Package selectedPackage = repository.GetTreeSelectedPackage() as EA.Package;
            bool isDiagram = false;
            EA.Diagram currentDiagram = null;
            if (element != null)
            {
                // 选择tree中的元素
                this.repository.ShowInProjectView(element);
            }
        }

        private void findInDiagramToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EA.Element element = repository.GetTreeSelectedObject() as EA.Element; // 获取当前选中的元素
            EA.Package selectedPackage = repository.GetTreeSelectedPackage() as EA.Package;
            bool isDiagram = false;
            EA.Diagram currentDiagram = null;
            if (element != null)
            {
                // 选择tree中的元素
                this.repository.ShowInProjectView(element);
                foreach (EA.Diagram dia in element.Diagrams)
                {
                    Console.WriteLine("dia.Name=====" + dia.Name);
                }
                EA.Diagram dia0 = repository.GetContextObject() as EA.Diagram;
                if (dia0 != null && dia0.DiagramObjects.Cast<EA.DiagramObject>().Any(dobj => dobj.ElementID == element.ElementID))
                {
                    // 当前 diagram 包含当前元素
                    Console.WriteLine("dia0=====" + dia0.Name);
                    isDiagram = true;
                    currentDiagram = dia0;

                }
                EA.Diagram dia1 = this.repository.GetCurrentDiagram();
                if (dia1 != null && !isDiagram)
                {
                    isDiagram = true;
                    currentDiagram = dia1;
                }
            }
            if (selectedPackage != null && !isDiagram)
            {
                // 获取 Package 中的所有图表
                foreach (EA.Diagram dia2 in selectedPackage.Diagrams)
                {
                    if (dia2 != null)
                    {
                        isDiagram = true;
                        currentDiagram = dia2;
                        break;
                    }
                }
            }
            if (isDiagram)
            {
                repository.OpenDiagram(currentDiagram.DiagramID);
                if (element != null)
                {
                    // 选中元素在项目浏览器中的位置
                    string location = string.Format("EAID={0}", element.ElementID);
                    // 将元素在 diagram 上的位置设置为当前选中元素
                    currentDiagram.FindElementInDiagram(element.ElementID);
                }

                //EA.DiagramObject diaObject = currentDiagram.GetDiagramObjectByID(element.ElementID, "");
                //diaObject.ElementID = element.ElementID;
                //diaObject.ShowNotes = true;
                //diaObject.ShowTags = true;
                //diaObject.Update();
                //currentDiagram.Update();
                 切换到该 diagram 并刷新界面
                //repository.OpenDiagram(currentDiagram.DiagramID);
                //repository.RefreshOpenDiagrams(true);

            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            comboBoxConnector_Type.SelectedItem = null;
            comboBoxConnector_Type_SelectedItem = null;
            DateTime startTimeVal = DateTime.Now.AddDays(-30);
            DateTime endTimeVal = DateTime.Now;
            ShowList(repository, title, startTimeVal, endTimeVal);
        }

        
    }
}

using EA;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using static UmlDemo1.FormUnnamedElements;

namespace UmlDemo1
{

    public class XmlElementData
    {
        public string Name { get; set; }             // 元素名 
        public Dictionary<string, string> Values
        {   // 属性名和对应的值
            get; set;
        }

        public XmlElementData()
        {
            Values = new Dictionary<string, string>();
        }
    }

    public class PublicClass
    {  
        public List<Dictionary<string, string>> Sql2Xml(EA.Repository repository, string sql)
        {
            //List dataList = new List(); // 存储所有解析得到的元素
            List<Dictionary<string, string>> dataList = new List<Dictionary<string, string>>(); // 初始化保存结果的列表
            if (sql == "" || sql == null|| repository == null)
            {
                return dataList;
            }
            sql = sql.Replace("\r\n", " ");
            sql = string.Format(sql);
            if (sql!="")
            {
                try
                {
                    string xmlResult = repository.SQLQuery(sql);
                    XDocument doc = XDocument.Parse(xmlResult);    // 将查询结果解析为 XDocument 对象
                                                                   // 对解析得到的 XML 数据进行遍历和处理            
                    if (doc.Root.Element("Dataset_0") == null)
                    {
                        return dataList;
                    }
                    if (doc.Root.Element("Dataset_0").Element("Data") == null)
                    {
                        return dataList;
                    }
                    if (doc.Root.Element("Dataset_0").Element("Data").Elements("Row") == null)
                    {
                        return dataList;
                    }
                    // 遍历每个数据行(Row 元素)
                    foreach (XElement rowElement in doc.Root.Element("Dataset_0").Element("Data").Elements("Row"))
                    {
                        Dictionary<string, string> rowDict = new Dictionary<string, string>(); // 新建一个字典,保存每个数据行的属性值

                        // 遍历数据行中的每个属性,将属性名和属性值保存到字典中
                        foreach (XElement attrElement in rowElement.Elements())
                        {
                            rowDict[attrElement.Name.LocalName] = attrElement.Value;
                        }

                        dataList.Add(rowDict); // 将保存了该数据行属性值的字典添加到列表中
                    }
                }
                catch(Exception e)
                {
                    MessageBox.Show(e.Message);
                }
                
            }
            Console.Write(sql);
            return dataList;

        }

        private List<EA.Package> GetAllSubPackages(EA.Package package)
        {
            List<EA.Package> subPackages = new List<EA.Package>();
            foreach (EA.Package subPackage in package.Packages)
            {
                subPackages.Add(subPackage);
                subPackages.AddRange(GetAllSubPackages(subPackage));
            }
            return subPackages;
        }

        public string GetChindPackages(EA.Repository repository)
        {
            int Package_ID = 0;
            string Package_ID_arr2str = "";
            List<int> Package_ID_arr = new List<int>();
            EA.Package selectedPackage = repository.GetTreeSelectedPackage() as EA.Package;
            if (selectedPackage != null && selectedPackage.PackageID > 1)
            {
                Package_ID = selectedPackage.PackageID;
                if (Package_ID > 1)
                {
                    Package_ID_arr.Add(Package_ID);
                    List<EA.Package> allSubPackages = GetAllSubPackages(selectedPackage);
                    foreach (var item in allSubPackages)
                    {
                        Package_ID_arr.Add(item.PackageID);
                    }
                }
            }
            Package_ID_arr2str = string.Join(",", Package_ID_arr.Select(x => x.ToString()).ToArray());
            return Package_ID_arr2str;
        }
        public void LoadDataElements(DataGridView dgv, List<Dictionary<string, string>> dataList)
        {
            dgv.Rows.Clear();

            // 遍历数据源中的每个项,并向 DataGridView 中添加新行
            foreach (var dataDict in dataList)
            {
                DataGridViewRow row = new DataGridViewRow();
                row.CreateCells(dgv);

                // 针对每个属性,在DataGridView中查找匹配的列,并将属性值分配给该列
                foreach (KeyValuePair<string, string> keyValue in dataDict)
                {
                    string attrName = keyValue.Key;
                    string attrValue = keyValue.Value;

                    // 在 DataGridView 中查找具有匹配名称的列
                    DataGridViewColumn col = dgv.Columns[attrName];

                    // 如果找到了匹配的列,则将属性值分配给它
                    if (col != null)
                    {
                        DataGridViewCell cell = row.Cells[col.Index];

                        if (cell.ValueType == typeof(DateTime))
                        {
                            DateTime dt;
                            if (DateTime.TryParse(attrValue, out dt))
                            {
                                cell.Value = dt;
                            }
                        }
                        else if (cell is DataGridViewCheckBoxCell)
                        {
                            bool isChecked = false;
                            if (bool.TryParse(attrValue, out isChecked))
                            {
                                cell.Value = isChecked;
                            }
                        }
                        else
                        {
                            cell.Value = attrValue;
                        }
                    }
                }

                // 将新行添加到 DataGridView 中
                dgv.Rows.Add(row);
            }
        }
        public void LoadDataElements1(DataGridView dgv, List<Dictionary<string, string>> dataList)
        {
            var rowsToDelete = new List<DataGridViewRow>();

            dgv.Rows.Clear();
            foreach (DataGridViewRow row in dgv.Rows)
            {
                if (!row.IsNewRow)
                {
                    bool foundRow = false;

                    // 遍历每个属性,将属性名和属性值添加到对应的 DataGridView 单元格中
                    foreach (KeyValuePair<string, string> keyValue in dataList[0])
                    {
                        string attrName = keyValue.Key;
                        string attrValue = string.Empty;

                        // Check if current row data has the attribute name
                        if (dataList[0].ContainsKey(attrName))
                        {
                            attrValue = dataList.First(k => k.ContainsKey(attrName))[attrName];

                            // Define the cell object
                            DataGridViewCell cell = row.Cells[attrName];

                            // 判断DataGridView中是否存在当前属性值
                            if (dgv.Columns.Contains(attrName) && cell != null)
                            {
                                // 判断当前属性类型,并针对类型进行单元格值的转换
                                if (cell.ValueType == typeof(DateTime))
                                {
                                    DateTime dt;
                                    if (DateTime.TryParse(attrValue, out dt))
                                    {
                                        cell.Value = dt;
                                    }
                                }
                                else if (cell is DataGridViewCheckBoxCell)
                                {
                                    bool isChecked = false;
                                    if (bool.TryParse(attrValue, out isChecked))
                                    {
                                        cell.Value = isChecked;
                                    }
                                }
                                else
                                {
                                    cell.Value = attrValue;
                                }

                                foundRow = true;
                            }
                        }
                    }

                    // 如果找不到符合条件的属性,就将当前行删除
                    if (!foundRow)
                    {
                        rowsToDelete.Add(row);
                    }
                }
            }

            // Remove rows doesn't exist in the data list
            rowsToDelete.ForEach(row => dgv.Rows.Remove(row));

            // 如果有未显示的属性,将它们添加到DataGridView中
            foreach (var dataDict in dataList)
            {
                bool foundRow = false;

                DataGridViewRow row = new DataGridViewRow();
                row.CreateCells(dgv);

                // 遍历每个属性,将属性名和属性值添加到对应的 DataGridView 单元格中
                foreach (KeyValuePair<string, string> keyValue in dataDict)
                {
                    string attrName = keyValue.Key;
                    string attrValue = keyValue.Value;
                    foreach (DataGridViewColumn col in dgv.Columns)
                    {
                        if (col.Name == attrName)
                        {
                            DataGridViewCell cell = row.Cells[col.Index];
                            // 判断当前属性类型,并针对类型进行单元格值的转换
                            if (cell.ValueType == typeof(DateTime))
                            {
                                DateTime dt;
                                if (DateTime.TryParse(attrValue, out dt))
                                {
                                    cell.Value = dt;
                                }
                            }else if (cell is DataGridViewCheckBoxCell)
                            {
                                bool isChecked = false;
                                if (bool.TryParse(attrValue, out isChecked))
                                {
                                    cell.Value = isChecked;
                                }
                            }
                            else
                            {
                                cell.Value = attrValue;
                            }
                            foundRow = true;
                            break;
                        }
                    } 
                }

                if (foundRow)
                {
                    dgv.Rows.Add(row);
                }
            }
        }

        public void doExportExcel(DataGridView dgv)
        {
            // 创建一个Excel对象
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

            // 创建工作簿
            Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add();

            // 创建工作表
            Microsoft.Office.Interop.Excel.Worksheet worksheet = workbook.ActiveSheet;

            // 将DataGridView导出到Excel
            for (int i = 0; i < dgv.ColumnCount; i++)
            {
                worksheet.Cells[1, i + 1] = dgv.Columns[i].HeaderText;
            }
            for (int i = 0; i < dgv.Rows.Count; i++)
            {
                for (int j = 0; j < dgv.Columns.Count; j++)
                {
                    if (dgv.Rows[i].Cells[j].Value != null)
                    {
                        worksheet.Cells[i + 2, j + 1] = dgv.Rows[i].Cells[j].Value.ToString();
                    }
                    else
                    {
                        worksheet.Cells[i + 2, j + 1] = "";
                    }
                }
            }

            // 打开Excel并显示数据
            excel.Visible = true;
        }


        private async Task<List<Dictionary<string, string>>> getDataList(EA.Repository repository,string sql)
        {
            List<Dictionary<string, string>> dataList = new List<Dictionary<string, string>>();
            try
            {
                if (sql != null && sql != "")
                {
                    // 异步执行耗时操作
                    dataList = await System.Threading.Tasks.Task.Run(() =>
                    {
                        //sql = "SELECT 'diagram' as BelongsType,t.Package_ID,p.Parent_ID,p.`Name` as Package_Name,t.CreatedDate, t.ModifiedDate, t.Diagram_ID, t.Name AS Diagram_Name, t.Diagram_Type,t.Author as author,t.Stereotype FROM t_diagram t left join t_package p on t.Package_ID=p.Package_ID WHERE 1 ";
                        Console.WriteLine(sql);
                        // 耗时操作代码,例如访问网络、读写文件等
                        return Sql2Xml(repository, sql);
                    });
                }
                
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            return dataList;
        }













    }


}

你可能感兴趣的:(c#,c#,winform,EA)