2014-03-19 36 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

相关问题