Quantcast
Channel: Visual Studio and Visual Web Developer Express
Viewing all articles
Browse latest Browse all 3509

The process cannot access the file temp_excelfile_Name.xlsm because it is being used by another process. - For large data (rows)

$
0
0

Excel download using Provider=Microsoft.ACE.OLEDB.12.0; Extended Properties=Excel 12.0; giving error with large group (having more then 100 comapanies).

 

Error: The process cannot access the file temp_excelfile_Name.xlsm' because it is being used by another process. On Response.WriteFile(strPath);

Code goes like this:

protected void Page_Load(object sender, EventArgs e)

    {

if (Request["PeerID"] != null)

            {

                if (Request.QueryString["PeerID"] != null)

                {

                    // Group Id in the session variable 'PeerIDCS1'

                    Session["PeerIDCS1"] = Convert.ToInt32(Request.QueryString["PeerID"]);                

                  

                   

                    summaryFinancialsDownload();         

// similarlly more functions which will dump data into other excel temp sheet.

 

 

                }

            }

}

 

 

private void summaryFinancialsDownload()

    {

 

        try

        {

          

            DataSet oDs = AddPeergroup.ExecuteStoredProcedure("sp_PG_PeerGroupFinancials", new object[] { "@GROUP_ID", "@Custom_TSR", "@Focal_Company_ID", "@DaysBefore", "@DaysAfter", "@StartFrom", "@StartTo", "@EndFrom", "@EndTo" }, new object[] { Convert.ToInt32(Session["PeerIDCS1"]), Session["isTSRfromDate"], Session["FocusCompany"], Convert.ToInt32(Session["DaysBefore"]), Convert.ToInt32(Session["DaysAfter"]), Session["StartFrom"], Session["StartTo"], Session["EndFrom"], Session["EndTo"] });

            if (oDs != null)

            {

                objpeers = new BrowsePlansData();

                strPath = Server.MapPath("../ExcelTemplate/PeerGroupFinancials" + Convert.ToInt32(Session["PeerIDCS1"]) + Session["clientlogin"].ToString() + DateTime.Now.Ticks + ".xlsm");

                DeleteExcelFile(strPath);

               

                // Create the excel file, and refer to that point.

                CreateExcelFile(Server.MapPath("../ExcelTemplate/PeerGroupFinancials.xlsm"), strPath);

 

 

                generateExcelByOledb(strPath, oDs, "TempCompanyInformation", "TempCompanyInformation");

 

                Session["PGTGroupName"] = objpeers.ExecuteScalar("SELECT Group_Name FROM Groups WHERE Group_Id=" + Convert.ToInt32(Session["PeerIDCS1"]) + "");

           

                if (Session["RoleRankID"] == null)

                {

                    if (Session["previlages"] != null)

                    {

                        Session["RoleRankID"] = 1;

                    }

                    else if (Session["RankPrevilages"] != null)

                    {

                        Session["RoleRankID"] = 0;

                    }

                }

 

               // Create the download and the pop dialog.

 

 

                string strDownloadName = ""; // downloadable file name.

                if (Session["PGTGroupName"] != null)

                {

                    if (Session["ClientDateTime"] != null)

                    {

                        strDownloadName = Session["PGTGroupName"].ToString() + "-" + "Peer Group Financials - " + Session["ClientDateTime"].ToString().Trim() + ".xls";

                    }

                    else

                    {

                        strDownloadName = Session["PGTGroupName"].ToString() + "-" + "Peer Group Financials - " + DateTime.Now.ToString("yyyy-MM-dd-hhmm") + ".xls";

                    }

                }

                else

                {

                    strDownloadName = "PeerGroupFinancials.xlsm";

                }

 

 

              Response.AddHeader("Content-Length", new System.IO.FileInfo(strPath).Length.ToString());

                // for dilog pop up of excel sheet.

                Response.AppendHeader("content-disposition", "attachment; filename=\"" + strDownloadName + "\"");

                Response.ContentType = "application/vnd.ms-excel.sheet.macroEnabled.12";

 

               

 

                Response.WriteFile(strPath);           

                Response.Flush();             

                Response.Close();

 

                Response.End();

            }

        }

        catch (Exception ex)

        {

 

            throw ex;

        }

 

    }

 

// for deleting the file.

private void DeleteExcelFile(string DataFile)

    {

        try

        {

            FileInfo fiNewExcel = new FileInfo(DataFile);

            if (fiNewExcel.Exists == true)

            {

                fiNewExcel.Delete();

            }

        }

        catch (Exception exDelete)

        {

            Response.Write(exDelete.ToString());

        }

    }

 

 

 

// for creating the file.

 

    private void CreateExcelFile(string TemplateFile, string DataFile)

    {

        try

        {

         

            FileInfo fiExcel = new FileInfo(TemplateFile);

            FileInfo fiNewExcel = new FileInfo(DataFile);

            if (fiNewExcel.Exists == false)

            {

                // Copy the template of the excel file into dynamically created file

                File.Copy(Server.MapPath("../ExcelTemplate/" + fiExcel.Name), Server.MapPath("../ExcelTemplate/" + fiNewExcel.Name));

                fiNewExcel.IsReadOnly = false;

            }

        }

        catch (Exception exFile)

        {

            Response.Write(exFile.ToString());

        }

    }

 

 

 

APP_Code function:

public static bool generateExcelByOledb_TotalReward(string filePath, DataSet ds, string sheetName, string tempSheetName)

    {

        DataSet dsTempData = ds;

        try

        {

            string strConn = @"Data Source=" + filePath + @";Provider=Microsoft.ACE.OLEDB.12.0; Extended Properties=Excel 12.0;";

            // ================= OPEN CONNECTION =================

            using (OleDbConnection oCon = new OleDbConnection())

            {

                OleDbConnection oledbConn = new OleDbConnection();

                oledbConn.ConnectionString = strConn;

                if (oledbConn.State == System.Data.ConnectionState.Closed)

                {

                    oledbConn.Open();

                }

                // ================= OPEN CONNECTION END =================

                // =================  GET DATA FROM EXCEL SHEET =================

                OleDbCommand oledbCmd = new OleDbCommand();

                // Get the table structure of particular worksheet in Excel file

                System.Data.DataTable oledbdatatbl = new System.Data.DataTable();

                oledbCmd.CommandText = "SELECT * FROM [" + sheetName + "$]";//Select excel sheet.

                oledbCmd.CommandType = System.Data.CommandType.Text;

                oledbCmd.Connection = oledbConn;

              

                oledbCmd.CommandTimeout = 300;

                OleDbDataAdapter oledbadap = new OleDbDataAdapter();

                oledbadap.SelectCommand = oledbCmd;

                oledbadap.Fill(oledbdatatbl);

                oledbdatatbl.TableName = "ReportTable";

 

                // ================= GET DATA END =================

                // ================= INSERT COMMAND =================

                string strcolumns = string.Empty; // "(F1, F2)";

                string stranswers = string.Empty;

                int coloumcount = 0;

                int answercount = 0;

                for (int icol = 0; icol < (oledbdatatbl.Columns.Count); icol++)

                {

                    coloumcount = coloumcount + 1;

                    if (strcolumns != string.Empty)

                        strcolumns = strcolumns + ",[" + oledbdatatbl.Columns[icol].ColumnName + "]";

                    else

                        strcolumns = strcolumns + "[" + oledbdatatbl.Columns[icol].ColumnName + "]";

                }

                //}

                // Get the company details in rows

                for (int irow = 0; irow < dsTempData.Tables[0].Rows.Count; irow++)

                {

                    stranswers = string.Empty;

 

                    for (int idatacol = 0; idatacol < dsTempData.Tables[0].Columns.Count; idatacol++)

                    {

                        answercount = answercount + 1;

                        if (stranswers != string.Empty)

                        {

                            if (dsTempData.Tables[0].Rows[irow][idatacol].ToString().Contains("'"))

                            {

                                string strtemp = dsTempData.Tables[0].Rows[irow][idatacol].ToString().Trim();

                                strtemp = strtemp.Replace("'", "''");

                                stranswers = stranswers + ",'" + strtemp + "'"; // +dsTempData.Tables[0].Rows[irow][idatacol].ToString() + "'";

                            }

                            else

                            {

                                stranswers = stranswers + ",'" + dsTempData.Tables[0].Rows[irow][idatacol].ToString().Trim() + "'";

                            }

                        }

                        else

                        {

                            string strtemp = dsTempData.Tables[0].Rows[irow][idatacol].ToString().Trim();

                            strtemp = strtemp.Replace("'", "''");

                            stranswers = stranswers + "'" + strtemp + "'";

                        }

                    }

                    // Code to insert the records into an excel sheet

                    int colcnt = coloumcount;

                    int anscnt = answercount;

                    oledbCmd = new OleDbCommand();

                    oledbCmd.CommandText = "insert into [" + tempSheetName + "$](" + strcolumns + ") values (" + stranswers + ")";

                    oledbCmd.CommandType = System.Data.CommandType.Text;

                    oledbCmd.Connection = oledbConn;

                    oledbCmd.ExecuteNonQuery();

                }

                if (oledbConn.State == System.Data.ConnectionState.Open)

                {

                    oledbConn.Close();

                }

                return true;

            }

        }

        catch (Exception ex)

        {

            //Response.Write(ex.Message);

            return false;

        }

    }

Please help it is too urgent...


Viewing all articles
Browse latest Browse all 3509

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>