Click here to Skip to main content
15,889,867 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
C#
private void button6_Click(object sender, EventArgs e) // export to excel
      {

          int exportcount = 0;
          //SaveFileDialog sfd = new SaveFileDialog();
              //sfd.Filter = "Excel Documents (*.xlsx)|*.xlsx";
              //sfd.FileName = "Sheet1.xlsx";
              //if (sfd.ShowDialog() == DialogResult.OK)
              //{
              //    ToCsV(dataGridView1, @"c:\export.xls");
              //    ToCsV(dataGridView1, sfd.FileName); // Here dataGridview1 is your grid view name
              //    MessageBox.Show("Excel Exported!");
              Excel.Application app = new Excel.Application();
              //Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
              Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
              Microsoft.Office.Interop.Excel._Worksheet worksheet1 = null;
              //Microsoft.Office.Interop.Excel._Worksheet worksheet2 = null;
              try
              {
                  app.Visible = true;
                  worksheet1 = workbook.Sheets["Sheet1"];
                  worksheet1 = workbook.ActiveSheet;
                  Marshal.ReleaseComObject(worksheet1);
                  Marshal.ReleaseComObject(workbook);


                  worksheet1.Cells[1, 1] = "รางงานการคำนวน การจัดการโครงการโดยการใช้ Critical Path Method";
                  Excel.Range Chartrange;
                  Chartrange = worksheet1.get_Range("A1", "C1");
                  Chartrange.Font.Bold = true;
                  worksheet1.Cells[3, 1] = "ต้นทุนการทำงานต่อวันเท่ากับ " + Check + " บาท";
                  GC.Collect();
                  Marshal.ReleaseComObject(Chartrange);

                  for (int i = 1; i < 4 + 1; i++)
                  {
                      worksheet1.Cells[5, i] = dataGridView1.Columns[i - 1].HeaderText;
                  }
                  for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
                  {
                      for (int j = 0; j < 4; j++)
                      {
                          int excel_cell = dataGridView1.Rows.Count - 1 + 5;
                          if (dataGridView1.Rows[i].Cells[j].Value != null)
                          {
                              worksheet1.Cells[i + 6, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
                              Excel.Range _range;
                              _range = worksheet1.get_Range("A5", "D" + excel_cell);
                              Excel.Borders borders = _range.Borders;
                              borders.LineStyle = Excel.XlLineStyle.xlContinuous;
                              borders.Weight = 3d;
                              GC.Collect();
                              Marshal.ReleaseComObject(borders);
                              Marshal.ReleaseComObject(_range);
                          }
                          else
                          {
                              worksheet1.Cells[i + 2, j + 1] = "";
                          }
                      }
                      exportcount = dataGridView1.Rows.Count + 2;
                  }
                  int report_count1 = Report.Count;
                  //worksheet1.Cells[exportcount + 3, 1] = "ตารางแสดงกิจกกรรมและค่าใช้จ่าย ที่เร่งรัด ใช้เวลาทั้งหมด " + report_count1 + " สัปดาห์";
                  worksheet1.Cells[exportcount + 4, 1] = "เร่งรัดครั้งที่ ";
                  worksheet1.Cells[exportcount + 4, 2] = "กิจกรรมที่เร่งรัด";
                  worksheet1.Cells[exportcount + 4, 3] = "Crtical Path";
                  worksheet1.Cells[exportcount + 4, 4] = "ต้นทุนเร่งรัด";
                  worksheet1.Cells[exportcount + 4, 5] = "ลดค่าใช้จ่ายไป";
                  Excel.Range range;
                  int DL = exportcount + 4;
                  range = worksheet1.get_Range("A" + DL, "E" + DL);
                  Excel.Borders DK = range.Borders;
                  DK.LineStyle = Excel.XlLineStyle.xlContinuous;
                  DK.Weight = 3d;
                  //Excel.Range kk = worksheet1.get_Range("A" + k, "E" + k);
                  //kk.Cells.VerticalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignGeneral;
                  //Excel.Borders borders = kk.Borders;
                  //borders.LineStyle = Excel.XlLineStyle.xlContinuous;
                  //borders.Weight = 3d;
                  GC.Collect();
                  Marshal.ReleaseComObject(range);
                  Marshal.ReleaseComObject(DK);
                  GC.Collect();
                  GC.WaitForPendingFinalizers();


                  string tempreport;
                  string Proj_NameReport = "";
                  for (int i = 0; i < TCritical_ForReport2.Count; i++)
                  {
                      for (int ii = 0; ii < TCritical_ForReport2[i].Count; ii++)
                      {
                          Proj_NameReport = Proj_NameReport + TCritical_ForReport2[i][ii];

                      }
                      tempreport = Proj_NameReport;
                      namereport.Add(tempreport);
                      Proj_NameReport = "";
                  }
                  for (int i = 0; i < namereport.Count; i++)
                  {
                      //int kk = forlast + 6;
                      namereport[i] = namereport[i].Trim();
                      namereport[i] = namereport[i].Replace("\r\n", "\r\n");
                      namereport[i] = namereport[i].Replace("  ", " ");
                  }

                  int k = 0;
                  if (Report.Count != 0)
                  {
                      int forlast = 0;
                      for (int i = 0; i < Report.Count; i++)
                      {
                          int day = i + 1;
                          int excelrow = i + 1;
                          string excelname = "";
                          int CCost = 0;
                          for (int ii = 0; ii < Report[i].Count; ii++)
                          {
                              excelname = excelname + " " + Report[i][ii].PName;
                              CCost = CCost + Report[i][ii].Cost;
                          }
                          int excel_cell = dataGridView1.Columns.Count - 2;
                          k = exportcount + excelrow + 4;
                          int CostOFProject = Convert.ToInt32(Check);
                          int result = CostOFProject - CCost;
                          worksheet1.Cells[exportcount + excelrow + 4, 1] = day;
                          worksheet1.Cells[exportcount + excelrow + 4, 2] = excelname;
                          worksheet1.Cells[exportcount + excelrow + 4, 3] = namereport[i];
                          worksheet1.Cells[exportcount + excelrow + 4, 4] = CCost;
                          worksheet1.Cells[exportcount + excelrow + 4, 5] = CostOFProject + "-" + CCost + " = " + result + " บาท";
                          Excel.Range kk = worksheet1.get_Range("A" + k, "E" + k);
                          kk.Cells.VerticalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignGeneral;
                          kk.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                          Excel.Borders borders = kk.Borders;
                          borders.LineStyle = Excel.XlLineStyle.xlContinuous;
                          borders.Weight = 3d;
                          excelrow = excelrow + 1;
                          GC.Collect();
                          Marshal.ReleaseComObject(kk);
                          Marshal.ReleaseComObject(borders);
                          GC.Collect();
                          GC.WaitForPendingFinalizers();
                          forlast = exportcount + excelrow + 3;
                      }
                      int show_report_Cost = 0;
                      for (int i = 0; i < Report.Count; i++)
                      {
                          for (int ii = 0; ii < Report[i].Count; ii++)
                          {
                              show_report_Cost = show_report_Cost + Report[i][ii].Cost;
                          }
                      }
                      int remain_report = 0;
                      int Report_ForCost = 0;
                      Report_ForCost = Convert.ToInt32(Check) * report_count1;
                      remain_report = keep_MaxTime - report_count1;
                      int calculateCost_report = 0;
                      calculateCost_report = Report_ForCost - show_report_Cost;
                      worksheet1.Cells[forlast + 2, 1] = "เวลาที่ใช้ก่อนที่่จะเร่งรัดกิจกรรมคือ " + keep_MaxTime + " สัปดาห์ หลังจากเร่งรัดกิจกกรมไปจำนวน " + report_count1 + " สัปดาห์";
                      worksheet1.Cells[forlast + 3, 1] = "จะทำให้โครงการลดระยะเวลาในการทำงานเหลือ " + remain_report + " สัปดาห์";
                      worksheet1.Cells[forlast + 4, 1] = "และสามารถลดค่าใช้จ่ายได้ " + calculateCost_report + " บาท";
                      int forlast2 = forlast + 6;


                  }
                  //Excel.Range kk = worksheet1.get_Range(k, 5);
                  //kk.Cells.VerticalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignGeneral;
                  Excel.Range er = worksheet1.get_Range("A:Z", System.Type.Missing);
                  er.EntireColumn.ColumnWidth = 17.0;
                  //workbook.Close();
                  //app.Quit();
                  //GC.Collect();
                  //GC.WaitForPendingFinalizers();
                  //Marshal.ReleaseComObject(er);
                  //Marshal.ReleaseComObject(workbook);
                  //Marshal.ReleaseComObject(worksheet1);
                  //app = null;
                  //GC.Collect();
                  //GC.WaitForPendingFinalizers();


              }


              catch { }
              finally
              {
                  Marshal.ReleaseComObject(workbook);
                  Marshal.ReleaseComObject(worksheet1);
                  if (app != null)
                  {
                      app.Quit();
                  }
                  Marshal.ReleaseComObject(app);
              }



      }//expoert

i really have no clue to do this i try many of thing i found in google
but the issue ism't solve anyone Help me Please the project need to be send to my teacher on next wednesday
Posted
Comments
[no name] 19-Jun-14 8:12am    
http://www.codeproject.com/Questions/787658/Help-Excel-process-keep-runnung-export-excel-with
ZurdoDev 19-Jun-14 8:36am    
What's the question? Just debug it and see what happens.
PrakashCs.net 19-Jun-14 9:02am    
correct Wes Aday,it is already mention in this link
http://www.codeproject.com/Questions/787658/Help-Excel-process-keep-runnung-export-excel-with

What I understood is you are running the code and you are getting the error saying the excel process is still running. If this is the case then you can see in the task manager your process is still in the background running. so I would suggest that safely dispose the excel objects and for that you can try to use Using block in C# or in finally block destroy all the relative objects.

try to release all the object in first go and then use it and in finally block or in using block destroy your objects.
see this link

One more thing in finally block first release the sheet object and then workbook object. it may solve the issue as i can see that you already releases all the objects
 
Share this answer
 
v2
Comments
Real_Criffer 19-Jun-14 10:03am    
i did
finally
{
marshel.releaseCOMObject(worksheet1);
marshel.releaseCOMObject(workbook);
if(app != null)
{
app.quit();
}

but it still process :( do this have to be in exit button of the program ? the code i post is at the export button do i have to close it at this button or application exit button


}
I had this problem too. The order which I closed and released objects seemed to fix it. Modify this to your variable names and objects. Notice I start with the worksheet release, then workbook, then workbooks collection then finally the app. If you have even one COM object that you don't release, the excel process will stay open. Gotta love interop. For the code below I put a call to the ReleaseObjects() function in every exception handle(in case of error) and when my process is done.

C#
public void ReleaseObjects()
        {
            while (System.Runtime.InteropServices.Marshal.ReleaseComObject(_currentSheet) > 0) { }
            _currentSheet = null;
            while (System.Runtime.InteropServices.Marshal.ReleaseComObject(_excelWorkBook) > 0) { }
            _excelWorkBook = null;
            while (System.Runtime.InteropServices.Marshal.ReleaseComObject(_excelWorkBooks) > 0) { }
            _excelWorkBooks = null;
            GarbageCollect();
            _excelApp.Quit();
            while (System.Runtime.InteropServices.Marshal.ReleaseComObject(_excelApp) > 0) { }
            _excelApp = null;
            GarbageCollect();
        }

        public static void GarbageCollect()
        {
            System.GC.Collect();
            System.GC.WaitForPendingFinalizers();

        }
 
Share this answer
 
v2
Comments
Real_Criffer 20-Jun-14 7:19am    
Thank you Sir

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900