Discuz!NT官方社区

首页 » Web开发 » ASP.net技术讨论 » 将gridview的内容导出到excel的问题??
wuguoming2004 - 2007-5-27 0:38:00
我按网上的一些代码写了一个将gridview的内容导出到excel的页面,运行后一按导出就出现错误:Retrieving the COM class factory for component with CLSID {00020819-0000-0000-C000-000000000046} failed due to the following error: 80040154.  问题究竟出在那里??
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
            DataSourceID="AccessDataSource1" EmptyDataText="There are no data records to display.">
            <Columns>
                <asp:BoundField DataField="id" HeaderText="id" ReadOnly="True" SortExpression="id" />
                <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
                <asp:BoundField DataField="sex" HeaderText="sex" SortExpression="sex" />
                <asp:BoundField DataField="course" HeaderText="course" SortExpression="course" />
                <asp:BoundField DataField="grade" HeaderText="grade" SortExpression="grade" />
                <asp:BoundField DataField="prize" HeaderText="prize" SortExpression="prize" />
                <asp:BoundField DataField="description" HeaderText="description" SortExpression="description" />
                <asp:BoundField DataField="department" HeaderText="department" SortExpression="department" />
            </Columns>
        </asp:GridView>
        <asp:Button ID="btnExportToExcel" runat="server" Text="导出到Excel"  />
        <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="App_Data\student.mdb"
            DeleteCommand="DELETE FROM `grade` WHERE `id` = ?" InsertCommand="INSERT INTO `grade` (`id`, `name`, `sex`, `course`, `grade`, `prize`, `description`, `department`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
            SelectCommand="SELECT `id`, `name`, `sex`, `course`, `grade`, `prize`, `description`, `department` FROM `grade`"
            UpdateCommand="UPDATE `grade` SET `name` = ?, `sex` = ?, `course` = ?, `grade` = ?, `prize` = ?, `description` = ?, `department` = ? WHERE `id` = ?">
            <InsertParameters>
                <asp:Parameter Name="id" Type="Int32" />
                <asp:Parameter Name="name" Type="String" />
                <asp:Parameter Name="sex" Type="String" />
                <asp:Parameter Name="course" Type="String" />
                <asp:Parameter Name="grade" Type="String" />
                <asp:Parameter Name="prize" Type="String" />
                <asp:Parameter Name="description" Type="String" />
                <asp:Parameter Name="department" Type="String" />
            </InsertParameters>
            <DeleteParameters>
                <asp:Parameter Name="id" Type="Int32" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="name" Type="String" />
                <asp:Parameter Name="sex" Type="String" />
                <asp:Parameter Name="course" Type="String" />
                <asp:Parameter Name="grade" Type="String" />
                <asp:Parameter Name="prize" Type="String" />
                <asp:Parameter Name="description" Type="String" />
                <asp:Parameter Name="department" Type="String" />
                <asp:Parameter Name="id" Type="Int32" />
            </UpdateParameters>
        </asp:AccessDataSource>
   
    </div>
    </form>
</body>
</html>

Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;//引入该空间才能用DataGrid类
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Reflection;//引入该空间才能用Missing类
using System.IO;//引入该空间才能用FileStream类



public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void ExportToExcel(GridView grid,string fileName)
    {
        string temolateFilePath;
        temolateFilePath = Server.MapPath(".") + @"\Template\";
        object missing = Missing.Value;
        Excel.Application app;
        Excel.Workbook workBook;
        Excel.Worksheet workSheet;
        Excel.Range range;

        //创建一个Application对象并使其不可见
        app = new Excel.Application();
        app.Visible = false;

        //创建一个WorkBook对象
        workBook = new Excel.Workbook();
        //得到workSheet对象
        workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1);

        int rowCount = grid.Rows.Count + 1;//DataTable行数+GridHead
        int colCount = grid.Columns.Count;//DataTable列数

        //利用2维数组批量写入
        string[,] arr = new string[rowCount, colCount];

        for (int i = 0; i < rowCount; i++)
        {
            for (int j = 0; j < colCount; j++)
            {
                if (i == 0)
                {
                    arr[i, j] = grid.Columns[j].HeaderText;
                }
                else
                {
                    arr[i, j] = grid.Rows[i - 1].Cells[j].Text.ToString();
                }
            }
        }

        range =(Excel.Range) workSheet.Cells[1, 1];
        range = range.get_Resize(rowCount, colCount);
        range.Value2 = arr;

        workBook.SaveAs(temolateFilePath + fileName, missing, missing, missing, missing, missing, Excel.XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);

        if (workBook.Saved)
        {
            workBook.Close(null, null, null);
            app.Workbooks.Close();
            app.Quit();
        }

        if (range != null)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
            range = null;
        }
        if (workSheet != null)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
            workSheet = null;
        }
        if (workBook != null)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
            workBook = null;
        }
        if (app != null)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
            app = null;
        }
        GC.Collect();//强制代码垃圾回收

        DownLoadFile(temolateFilePath, fileName);
    }

    private bool DownLoadFile(string _FilePath, string _FileName)
    {
        try
        {
            FileStream fs=File.OpenRead(_FilePath+_FileName);
            byte[] FileData=new byte[fs.Length];
            fs.Read(FileData,0,(int)fs.Length);
            Response.Clear();
            Response.AddHeader("Content-Type","application/ms-excel");
            string FileName=HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(_FileName));
            Response.AddHeader("Content-Disposition","inline:filename="+Convert.ToChar(34)+FileName+Convert.ToChar(34));
            Response.AddHeader("Content-Length",fs.Length.ToString());
            Response.BinaryWrite(FileData);
            fs.Close();
            //删除服务器临时文件
            File.Delete(_FilePath+_FileName);
            Response.Flush();
            Response.End();
            return true;
        }
        catch(Exception ex)
        {
            ex.Message.ToString();
            return false;
        }
    }
    protected void btnExportToExcel_Click(object sender, EventArgs e)
    {
        ExportToExcel(GridView1, "成绩.xls");
    }
}

Web.Config
<?xml version="1.0"?>
<!--
    Note: As an alternative to hand editing this file you can use the
    web admin tool to configure settings for your application. Use
    the Website->Asp.Net Configuration option in Visual Studio.
    A full list of settings and comments can be found in
    machine.config.comments usually located in
    \Windows\Microsoft.Net\Framework\v2.x\Config
-->
<configuration>
    <appSettings/>
    <connectionStrings/>

    <system.web>
        <!--
            Set compilation debug="true" to insert debugging
            symbols into the compiled page. Because this
            affects performance, set this value to true only
            during development.
        -->
        <compilation debug="true"/>
        <!--
            The <authentication> section enables configuration
            of the security authentication mode used by
            ASP.NET to identify an incoming user.
        -->
        <authentication mode="Windows"/>
    <identity impers></identity>
        <!--
            The <customErrors> section enables configuration
            of what to do if/when an unhandled error occurs
            during the execution of a request. Specifically,
            it enables developers to configure html error pages
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->
    </system.web>
</configuration>
stone0824 - 2007-5-27 8:26:00
在网上查了一下,有以下几个解决的方法:
1.你是否建立了ASP.NET 帐户, (2003下为ASPNET, xp,2000下为 Network Service ),且该用户有操作Excel的权限
  (具体操作你可以去网上找一下)
    goto Controlpanel --> Administrative tools-->Component Services -->computers --> myComputer -->DCOM Config --> Microsoft Excel Application.
right click to get properties dialog. Goto Security tab and customize permissions accordingly.
我记得我们做的时候就是改了这个就可以了
2.在Web.Config文件中加入<identity  impersonate="true"></identity>即可
3.看一下服务器上是否有未关闭的Excel文件
lee - 2007-5-27 11:18:00
http://www.51aspx.com/CV/GridViewDemo
vagerent - 2007-5-29 11:13:00
这个是以前写的一篇blog,不知能否对楼主有帮助:
http://www.cnblogs.com/vagerent/archive/2007/03/12/672171.html
1
查看完整版本: 将gridview的内容导出到excel的问题??