1

我正在使用此代码在客户端机器上创建一个 excel 文件,同时按下 asp.net 中的按钮

 protected void excldwnlbtn4_Click(object sender, EventArgs e)
{
    write_on_excel("Vendor.xls");
    lblmsg4.Text = "File Downloaded";
}

并且创建excel文件的代码是:

public void write_on_excel(string filepath)
{
    Excel.ApplicationClass excelApp = new Excel.ApplicationClass();
    try
    {

        Excel.Workbook workbook = (Excel.Workbook)excelApp.Workbooks.Add(Missing.Value);
        Excel.Worksheet worksheet;


        //// Opening excel file
        //workbook = excelApp.Workbooks.Open(filepath, 0, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);



        workbook.SaveAs(filepath,
        Excel.XlFileFormat.xlExcel5, Missing.Value, Missing.Value,
        false, false, Excel.XlSaveAsAccessMode.xlNoChange,
        Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

        // Get first Worksheet
        worksheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);

        // Setting cell values

        ((Excel.Range)worksheet.Cells[1, "A"]).Value2 = "Vendor Code";
        ((Excel.Range)worksheet.Cells[1, "B"]).Value2 = "Vendor Password";
        ((Excel.Range)worksheet.Cells[1, "C"]).Value2 = "Vendor Name";


        workbook.Save();
        workbook.Close(0, 0, 0);
    }
    catch (Exception)
    {
        lblmsg4.Text = "File not Downloaded!!";
    }
    finally
    {
        excelApp.Quit();
    }
}

现在它在我的 IIS localhost 中工作正常..我在硬盘驱动器中获得了一个带有这些列标题的空 excel 文件....但是当我将它托管在服务器中并使其生效时,我无法创建excel文件...我收到一个错误:

Server Error in '/' Application.

The resource cannot be found.  

我该怎么办??我的错在哪里?请帮助我

4

2 回答 2

0

那将永远不会在浏览器客户端的机器上创建文件(除非该机器是破坏 Web 服务器的机器)。

例如,如果要允许浏览器客户端下载文件,则需要将其直接写入响应流。查看此线程上排名最高的答案以获取更多信息

单击按钮时下载 ASP.NET Excel 文件

于 2012-11-15T10:19:44.203 回答
0

我在这里看到了几个问题。

一是,您希望 Excel 出现在服务器上。如果您不确定它是否存在,它可能不存在,您的应用程序应该检查它。基本上,如果您在尝试实例化 Excel 对象时遇到异常,则说明 Excel 不存在或您无权执行它。

其次,您将输出文件(如果可以生成的话)本地保存在服务器上。这不会神奇地将文件发送到客户端。您必须自己发送文件;最好不要在服务器上创建本地副本,而是让您的 ASP.NET 页面将 Excel 文件输出到流中;客户端接收流。有关更多信息,请参见此处:http ://www.gemboxsoftware.com/support/articles/asp-net-excel

最后,还有其他方法可以生成 Excel 文件。您可以使用 OpenXML 之类的库(请参阅http://openxmldeveloper.org/),或者您可以使用内置System.Xml类生成 Excel 可以读取的 XML 文件。还有一些商用库可用于在 .NET 中处理 Excel 文件,例如 Aspose Cells(参见http://www.aspose.com/categories/.net-components/aspose.cells-for-.net/default。 .aspx)。

于 2012-11-15T10:29:11.780 回答