我编写了以下代码将数据导出到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 :(得分:0)
你应该知道两件事。
首先,您的代码似乎使用Excel Interop Services,因此需要在服务器上安装Excel。
第二件事是Microsoft不支持在服务器端使用Excel Interop Services,for a number of good reasons。
相反,我建议使用替代库,例如EPPlus或Open Office XML SDK,这两个库都可以在服务器端运行。