将 Select Query (SQL Server) 的结果保存到 Excel 的工作表中

Posted

技术标签:

【中文标题】将 Select Query (SQL Server) 的结果保存到 Excel 的工作表中【英文标题】:Save the Result Of Select Query (SQL Server) Into worksheet of Excel 【发布时间】:2021-04-22 10:28:48 【问题描述】:

我目前正在使用 C# 和 Entity Framework 5 开发控制台应用程序,我将数据从 Excel 插入数据库 (SQL Server),然后在数据库中处理它(实际上是在存储过程中),然后再次更新 Excel 文件。 我遇到的问题是插入需要很长时间...但是已经使用SQLBulk解决了。

下一个问题是写入(更新)一列(实际上是 3 列)需要更长的时间。其中列的值来自数据库查询。查询生成的行数为 16000 行。

这是我的代码:

private static void writetoExcel2(T_UploadEvent objParam, DateTime dtstartingTime)
    
        try
        
            M_PriceMapper m_PriceMapper = new M_PriceMapper();

            Application excelApp = new Application();

            if (excelApp == null)
            
                Console.WriteLine("Excel is not installed!!");
                return;
            

            Workbook excelBook = excelApp.Workbooks.Open(@objParam.FilePath);
            _Worksheet excelSheet = excelBook.Sheets[1];
            Range excelRange = excelSheet.UsedRange;
            Range excelRangeRow = excelSheet.UsedRange.Rows;

            int rows = excelRange.Rows.Count;
            int cols = excelRange.Columns.Count;


            List<T_HeaderOrder> t_HeaderOrders = new List<T_HeaderOrder>();

            T_HeaderOrderMapper t_HeaderOrderMapper = new T_HeaderOrderMapper();

            t_HeaderOrderLists = t_HeaderOrderMapper.getListData(objParam, "1");
            T_HeaderOrder objOL = new T_HeaderOrder();

            if (t_HeaderOrderLists != null)
            
                for (int y = 2; y <= rows; y++)
                
                    for (int x = 1; x <= cols; x++)
                    
                        try
                        
                            switch (excelRange.Cells[1, x].value2)
                            
                                case "UNIQCODE":
                                    for (int c = 0; c <= t_HeaderOrderLists.Count - 1; c++)
                                    
                                        T_HeaderOrder obj = t_HeaderOrderLists[c];
                                        if (string.IsNullOrEmpty(obj.ErrorMessage))
                                        
                                            M_Price m_Price = new M_Price();
                                            m_Price = m_PriceMapper.getData(obj.MasterPriceID);
                                            if (m_Price.UniqCode == excelRange.Cells[y, x].value2.ToString())
                                            
                                                objOL = obj;
                                                c = t_HeaderOrderLists.Count;
                                                Range ora1 = excelSheet.Rows.Cells[y, cols + 1];
                                                ora1.Value2 = objOL.NewPrice;

                                                Range ora2 = excelSheet.Rows.Cells[y, cols + 2];
                                                ora2.Value2 = objOL.Manual_VS_MPrise.ToUpper();
                                                if (objOL.Manual_VS_MPrise == "false")
                                                
                                                    Range rowFormat = excelSheet.Rows[y];
                                                    rowFormat.Interior.Color = System.Drawing.Color.Red;
                                                    rowFormat.Font.Color = System.Drawing.Color.White;
                                                

                                                Range ora3 = excelSheet.Rows.Cells[y, 33];
                                                ora3.Value2 = objOL.SourcePrice;
                                            
                                        
                                        else
                                        
                                            Range msgERR = excelSheet.Rows.Cells[y, cols + 4];
                                            msgERR.Value2 = objOL.ErrorMessage.ToUpper();
                                        
                                    
                                    break;
                            
                        
                        catch (Exception eb)
                        
                            Console.WriteLine("Error while write to excel, Row number : " + y);
                            Range msgERR = excelSheet.Rows.Cells[y, cols + 4];
                            msgERR.Value2 = eb.Message;
                        
                    
                    Console.WriteLine("Updateing row : " + y);
                
                Range oraHEADER = excelSheet.Rows.Cells[1, cols + 1];
                oraHEADER.Value2 = "New PRICE";

                Range oravs = excelSheet.Rows.Cells[1, cols + 2];
                oravs.Value2 = "PRICE Comparasion";

                Range orasOURCE = excelSheet.Rows.Cells[1, cols + 3];
                orasOURCE.Value2 = "SOURCE PRICE";

                Range oramsgerr = excelSheet.Rows.Cells[1, cols + 4];
                orasOURCE.Value2 = "Error Message";
            
            excelApp.ActiveWorkbook.Save();
            excelApp.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
        
        catch (Exception ex)
        
            Console.WriteLine("Error While Sending Emails");
        



public List<T_HeaderOrder> getListData(T_UploadEvent objParam, string param)

        try
        
            List<T_HeaderOrder> t_HeaderOrders= new List<T_HeaderOrder>();
            using (Entities entities = new Entities ())
            
                var idParam = new SqlParameter
                
                    ParameterName = "T_UploadEventID",
                    Value = objParam.ID
                ;

                var list = entities.Database.SqlQuery<T_HeaderOrder>
                    ("exec T_HeaderOrder_Comparasion @T_UploadEventID ", idParam).ToList<T_HeaderOrder>();
               
                t_HeaderOrders = list;

            
            return t_HeaderOrders;
        
        catch (DbEntityValidationException e)
        
            foreach (var eve in e.EntityValidationErrors)
            
                Console.WriteLine("Entity of type \"0\" in state \"1\" has the following validation errors:",
                    eve.Entry.Entity.GetType().Name, eve.Entry.State);
                foreach (var ve in eve.ValidationErrors)
                
                    Console.WriteLine("- Property: \"0\", Error: \"1\"",
                        ve.PropertyName, ve.ErrorMessage);
                
            
            throw;
            return new List<T_HeaderOrder>();
        

感谢您的帮助

【问题讨论】:

为什么不使用 EPPlus? EPPlus ..?我不知道它可以更快。你有一些例子吗?谢谢你的回复 使用后台工作者。这是参考***.com/questions/2196204/… 【参考方案1】:

感谢您的所有回复,我已经找到了根本原因并解决了它。 造成的根源是许多验证和嵌套循环。 我已经删除了它..应用程序变得更快了。

【讨论】:

以上是关于将 Select Query (SQL Server) 的结果保存到 Excel 的工作表中的主要内容,如果未能解决你的问题,请参考以下文章

如何将 SQL INSERT INTO SELECT 与 codeigniter 一起使用

SQL 将 COUNT 和 AVG 查询与 SELECT 结合起来

sql serve创建存储过程,查询指定学生的学号、姓名、课程名、成绩

sql serve数据库中对in查询到的数据排序

sql db query db_select条件

SQL SELECT QUERY - 来自两个表