asp.net生成excel

20 篇文章 0 订阅

http://msdn.microsoft.com/zh-cn/library/vstudio/af2ak5yz.aspx


在项目中添加“Microsoft Excel 12.0 Object Library”引用


Microsoft.Office.Interop.Excel.Application app = null;
        Microsoft.Office.Interop.Excel.Workbook workbook = null;
        Microsoft.Office.Interop.Excel.Worksheet sheet = null;
        object missing = System.Reflection.Missing.Value;
        string strPath = string.Empty;
        string strFileName = string.Empty;
        try
        {
            app = new Microsoft.Office.Interop.Excel.Application();
            app.Visible = false;        // 不显示,仅后台生成
            workbook = app.Workbooks.Add(true); // 如果打开已存在文件,这里用Open,保存使用Save
            // 添加sheet的方法
            workbook.Worksheets.Add(missing, missing, missing, missing);
            // 修改sheet名的方法,注意sheet的下标从1开始
            sheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
            sheet.Name = "new sheet name";

            // 设置字体和大小
            //range = sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[rowCount, columnCount]);
            //range.Font.Name = “Arial”;
            //range.Font.Size = 10;
            
            // 设置单元格的wrap text属性
            sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[10001, 8]).WrapText = true;
            // 设置单元格的数据格式
            sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[10001, 8]).NumberFormat = "@";
            // 设置自动调整列宽
            sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[10001, 8]).EntireColumn.AutoFit();


            Microsoft.Office.Interop.Excel.Range range;
            Array arr = Array.CreateInstance(typeof(object), intDataCount+1, 8);
            // 不断的调用下面的的函数填充array中的内容
            // 行,列均从0开始
            
            
            arr.SetValue("序号", 0, 0);
            arr.SetValue("审核表编号", 0, 1);
            arr.SetValue("姓名", 0, 2);
            arr.SetValue("补贴月份", 0, 3);
            arr.SetValue("补贴金额", 0, 4);
            arr.SetValue("银行帐号", 0, 6);
            arr.SetValue("错误信息", 0, 5);
            arr.SetValue("部门编码", 0, 7);
            int i = 1;
            foreach (DataRow row in myData.Tables[LY_BT_ALLOWNCEINFO_DETAILS_TABLE.LY_BT_ALLOWNCEINFO_DETAILS_TABLENAME].Rows)
            {
                arr.SetValue(row["RN"], i, 0);    
                arr.SetValue(row["REGISTER_NUM"], i, 1);    
                arr.SetValue(row["APPLYER"], i, 2);    
                arr.SetValue(row["YMDATE"], i, 3);    
                arr.SetValue(row["MONEY"], i, 4);
                arr.SetValue(row["BANKACCOUNT"], i, 6);
                arr.SetValue(row["ERRORMSG"], i, 5);
                arr.SetValue(row["DepCode"], i, 7);
                i++;
            }


            // 设置array数据,注意选择的行数和列数要与array行数和列数对应
            sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[10001, 8]).Value2 = arr;


            // 这里给sheet填充内容部分略
            // 如果文件已经存在又不想让“是否替换”的提示窗体显示出来,需要先调用File.Delete来删除文件
            strFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
            strPath = Server.MapPath("~/upload");
            workbook.SaveAs(strPath + "\\" + strFileName, missing, missing, missing, missing, missing,
            Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, missing, missing,
            missing, missing, missing);
            
            workbook.Close(false, missing, missing);
            app.Quit();
            workbook = null;
            app = null;
            GC.Collect();


            FileInfo fi = new FileInfo(strPath + "\\" + strFileName);//excelFile为文件在服务器上的地址 
            HttpResponse contextResponse = HttpContext.Current.Response;
            contextResponse.Clear();
            contextResponse.Buffer = true;
            contextResponse.Charset = "GB2312"; //设置了类型为中文防止乱码的出现 
            contextResponse.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}",fi.Name)); //定义输出文件和文件名 
            contextResponse.AppendHeader("Content-Length", fi.Length.ToString());
            contextResponse.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            contextResponse.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 


            contextResponse.WriteFile(fi.FullName);
            contextResponse.Flush();
            fi.Delete();
        }
        catch (Exception ex)
        {
            if (app != null)
            {
                app.Quit();
                app = null;
                GC.Collect();
            }
            webTools.InsertAlert(this.Page, ex.Message.ToString());
        }



IIS下发布操作Excel程序时遇到{00024500-00***即80070005错误

【问题没描述】英文版

Retrieving the COM class factory forcomponent with CLSID {00024500-0000-0000-C000-000000000046} failed due to thefollowing error: 80070005. 

Description: An unhandled exceptionoccurred during the execution of the current web request. Please review thestack trace for more information about the error and where it originated in thecode. 

Exception Details:System.UnauthorizedAccessException: Retrieving the COM class factory forcomponent with CLSID {00024500-0000-0000-C000-000000000046} failed due to thefollowing error: 80070005. 

ASP.NET is not authorized to access therequested resource. Consider granting access rights to the resource to theASP.NET request identity. ASP.NET has a base process identity (typically{MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6) that is used if theapplication is not impersonating. If the application is impersonating via<identity impersonate="true"/>, the identity will be theanonymous user (typically IUSR_MACHINENAME) or the authenticated request user. 

 

To grant ASP.NET access to a file,right-click the file in Explorer, choose "Properties" and select theSecurity tab. Click "Add" to add the appropriate user or group.Highlight the ASP.NET account, and check the boxes for the desired access.

【问题描述】中文版

检索 COM 类工厂中 CLSID 为 {00024500-0000-0000-C000-000000000046} 的组件时失败,原因是出现以下错误: 80070005。

说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。

异常详细信息: System.UnauthorizedAccessException: 检索 COM 类工厂中 CLSID 为{00024500-0000-0000-C000-000000000046} 的组件时失败,原因是出现以下错误:80070005。

ASP.NET 未被授权访问所请求的资源。请考虑授予ASP.NET 请求标识访问此资源的权限。ASP.NET 有一个在应用程序没有模拟时使用的基进程标识(通常,在 IIS 5 上为 {MACHINE}\ASPNET,在 IIS 6 上为网络服务)。如果应用程序正在通过 <identity impersonate="true"/> 模拟,则标识将为匿名用户(通常为IUSR_MACHINENAME)或经过身份验证的请求用户。

 

要将 ASP.NET 访问权限授予某个文件,请在资源管理器中右击该文件,选择“属性”,然后选择“安全”选项卡。单击“添加”添加适当的用户或组。突出显示 ASP.NET 帐户,选中所需访问权限对应的框。

源错误:

执行当前 Web 请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪信息确定有关异常原因和发生位置的信息。

【解决方案1】

1:在服务器上安装office的Excel软件.

2:在"开始"->"运行"中输入dcomcnfg.exe启动"组件服务"

   x64位操作系统执行 comexp.msc -32

3:依次双击"组件服务"->"计算机"->"我的电脑"->"DCOM配置"

4:在"DCOM配置"中找到"MicrosoftExcel 应用程序",在它上面点击右键,然后点击"属性",弹出"Microsoft Excel 应

用程序属性"对话框

5:点击"标识"标签,选择"交互式用户"

6:点击"安全"标签,在"启动和激活权限"上点击"自定义",然后点击对应的"编辑"按钮,在弹出的"安全性"对话框中填加

一个"NETWORK SERVICE"用户(注意要选择本计算机名),并给它赋予"本地启动"和"本地激活"权限.

 

7:依然是"安全"标签,在"访问权限"上点击"自定义",然后点击"编辑",在弹出的"安全性"对话框中也填加一个"NETWORK

SERVICE"用户,然后赋予"本地访问"权限.

这样,我们便配置好了相应的Excel的DCOM权限.

注意:这是在WIN2003上配置的,在2000,xp上,NETWORK SERVICE用户改为ASP.net用户

win2008、win7把NETWORK SERVICE用户改为IIS_IUSRS




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值