2014-03-19 71 views
-1

我已經編寫了以下代碼以將數據導出到excel。 此代碼在本地工作正常,但是當我們在服務器(UAT)上部署此代碼時,它不起作用。 如果我們重新啓動服務器,它會工作一段時間,但過一段時間後會失敗。在服務器上部署代碼時不起作用

代碼:

public void ExportToExcelFunction(string FlName, DataTable mydt, string DispColName, string BindCols) 
    { 
     Excel.Application xlObj = new Excel.Application(); 
     object oMissing = System.Reflection.Missing.Value; 
     xlObj.Visible = false; 
     //vinod 
     string filepath = Server.MapPath("Export"); 
     string strFlName = filepath + "\\Master.xlsx"; 

     Excel.Workbook xlWB = xlObj.Workbooks.Open(strFlName, 0, true, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, true, 0, true); 
     Excel.Worksheet xlSheet = (Excel.Worksheet)xlWB.ActiveSheet; 

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

     //Added for export to excel 
     try 
     { 
      //For Column 
      string[] strCols = DispColName.Split(','); 
      for (int i = 1; i <= strCols.Length; i++) 
      { 
       if (strCols[i - 1].Length > 0 && strCols[i - 1] != null) 
        xlSheet.Cells[1, i] = Convert.ToString(strCols[i - 1]); 
      } 

      // for Row 
      string[] strColBind = BindCols.Split(','); 
      for (int r = 0; r < rows; r++) 
      { 
       for (int c = 0; c < strColBind.Length; c++) 
       { 
        xlSheet.Cells[r + 2, c + 1] = mydt.Rows[r][strColBind[c]]; 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
     } 


     String newFlName = "\\" + DateTime.Now.Ticks.ToString() + "_" + FlName + ".xls"; 
     xlWB.SaveAs(filepath + newFlName, Excel.XlFileFormat.xlWorkbookNormal, "", "", false, false, Excel.XlSaveAsAccessMode.xlExclusive, true, false, "", true); 

     xlWB.Close(true, oMissing, oMissing); 
     xlObj.Quit(); 

     System.IO.FileInfo file = new System.IO.FileInfo(@"" + filepath + newFlName + ""); 
     Response.Clear(); 
     Response.ClearHeaders(); 
     Response.ClearContent(); 
     Response.AppendHeader("Content-Disposition", "attachment; filename = " + FlName + ".xls"); 
     Response.AppendHeader("Content-Length", file.Length.ToString()); 
     Response.ContentType = "application/download"; 
     Response.WriteFile(file.FullName); 
     Response.Flush(); 
     Response.Close(); 
     Response.End(); 

    } 
+0

你得到的錯誤是什麼? – DLeh

+0

它可能是服務器沒有權限寫入文件路徑。 – DLeh

+0

你的服務器上有Excel嗎? – PaulG

回答

0

兩件事情你應該知道。

首先,您的代碼似乎是使用Excel Interop Services,因此需要在服務器上安裝Excel。

第二件事是在服務器端使用Excel Interop Services不被Microsoft支持,for a number of good reasons

相反,我建議使用替代庫,例如EPPlusOpen Office XML SDK,它們都可以在服務器端運行。

+0

謝謝你,我只是檢查這些庫。 – user3437960

+0

我個人發現EPPlus非常簡單而強大。如果你對此熟悉,可以通過NuGet獲得。 – mason

相關問題