通过代码获取在sharepoint designer 2010中从SQL数据表生成大型Excel的错误

时间:2015-12-14 11:01:16

标签: c# sharepoint-2010 sharepoint-designer epplus

问题:想要从数据表中生成Excel。           使用OfficeOpenXml.ExcelPackage创建Workbook.Worksheet并使用GetAsByteArray将其写入Excel。

相同的代码适用于较少的行Eg。当我在实时服务器上应用它作为从表中选择前6000 *然后它正在工作,但如果我把它作为select * from table然后它抛出下面提到的异常。

    protected void FillExcel(DataTable table)
    {
        try
        {

            if (table.Rows.Count > 0 && table != null)
            {
                using (OfficeOpenXml.ExcelPackage pck = new OfficeOpenXml.ExcelPackage())
                {
                    OfficeOpenXml.ExcelWorksheet ws;
                    ws = pck.Workbook.Worksheets.Add("excelname_XYZ");

                    //worksheet name
                    int ColumnIndex = 0;                            //FillExcelData
                    foreach (DataColumn col in table.Columns)       //FillExcelData column
                    {
                        ColumnIndex++;
                        ws.Cells[1, ColumnIndex].Value = col.ColumnName;
                    }
                    int rowIndex = 0;
                    foreach (DataRow row in table.Rows)             //FillExcelData rows
                    {
                        rowIndex++;
                        ColumnIndex = 0;
                        foreach (DataColumn col in table.Columns)
                        {
                            ColumnIndex++;
                            ws.Cells[rowIndex + 1, ColumnIndex].Value = row[col.ColumnName].ToString();
                        }
                    }

                    ColumnIndex = 0;
                    foreach (DataColumn col in table.Columns)
                    {
                        ColumnIndex++;
                        ws.Cells[1, ColumnIndex].Style.Font.Bold = true;
                        ws.Cells[1, ColumnIndex].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                        ws.Cells[1, ColumnIndex].Style.Font.Color.SetColor(System.Drawing.Color.White);
                        ws.Cells[1, ColumnIndex].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(31, 73, 124));
                    }

                    using (OfficeOpenXml.ExcelRange x = ws.Cells["A:AH"])
                    {
                        x.AutoFitColumns();
                    }


                    Byte[] fileBytes = pck.GetAsByteArray();
                    //Clear the response
                    Response.Clear();
                    Response.ClearContent();
                    Response.ClearHeaders();
                    Response.Cookies.Clear();
                    //Add the header & other information                 
                    Response.Cache.SetCacheability(HttpCacheability.Private);
                    Response.CacheControl = "private";
                    Response.Charset = System.Text.UTF8Encoding.UTF8.WebName;
                    Response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
                    Response.AppendHeader("Content-Length", fileBytes.Length.ToString());
                    Response.AppendHeader("Pragma", "cache");
                    Response.AppendHeader("Expires", "60");

                   string strFilename = "fileName_" + DateTime.Now.ToString("MMM").Trim() + ".xlsx";
                   Response.AppendHeader("Content-Disposition",
                    "attachment; " +
                    "filename=\"" + strFilename + ".xlsx\"; " +   //filename of excel
                    "size=" + fileBytes.Length.ToString()); 
                   Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    //Write it back to the client                
                    Response.BinaryWrite(fileBytes);
                }
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, typeof(Page), UniqueID, "alert('No Data Found for a specified date range.');", true);
            }

        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }

    }

异常发生在GetAsByteArray()方法://

    System.Security.SecurityException: Request for the permission of type 
    'System.Security.Permissions.IsolatedStorageFilePermission, mscorlib,     
    Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
    at System.Security.CodeAccessSecurityEngine.Check(Object demand,
    StackCrawlMark& stackMark, Boolean isPermSet) at
    System.Security.CodeAccessPermission.Demand()    
    atSystem.IO.IsolatedStorage.IsolatedStorage.DemandPermission   
    (IsolatedStorageScope scope) at  
    System.IO.IsolatedStorage.IsolatedStorage._InitStore(IsolatedStorageScope
    scope, Evidence domainEv, Type domainEvidenceType, Evidence assemEv, Type
    assemblyEvidenceType, Evidence appEv, Type appEvidenceType) at
    System.IO.IsolatedStorage.IsolatedStorage.InitStore(IsolatedStorageScope
    scope, Type domainEvidenceType, Type assemblyEvidenceType) at
    System.IO.IsolatedStorage.IsolatedStorageFile.GetStore(IsolatedStorageScope
    scope, Type domainEvidenceType, Type assemblyEvidenceType) at
    MS.Internal.IO.Packaging.PackagingUtilities.ReliableIsolatedStorageFileFolder.
    .ctor() at    
    MS.Internal.IO.Packaging.PackagingUtilities.GetDefaultIsolatedStorageFile()
    at          
    MS.Internal.IO.Packaging.PackagingUtilities.
    CreateUserScopedIsolatedStorageFileStreamWithRandomName(Int32 retryCount,
    String& fileName) at
    MS.Internal.IO.Packaging.SparseMemoryStream.EnsureIsolatedStoreStream() at
    MS.Internal.IO.Packaging.SparseMemoryStream.SwitchModeIfNecessary() at
    MS.Internal.IO.Packaging.CompressEmulationStream.Write(Byte[] buffer, Int32
    offset, Int32 count) at MS.Internal.IO.Packaging.CompressStream.Write 
    (Byte [] buffer, Int32 offset, Int32 count) at
    MS.Internal.IO.Zip.ProgressiveCrcCalculatingStream.Write(Byte[] buffer,
    Int32 offset, Int32 count) at 
    MS.Internal.IO.Zip.ZipIOModeEnforcingStream.Write(Byte[] buffer, Int32    
    offset, Int32 count) at System.IO.StreamWriter.Flush(Boolean flushStream,
    Boolean flushEncoder) at System.IO.StreamWriter.Write(String value) at
    OfficeOpenXml.ExcelWorksheet.UpdateRowCellData(StreamWriter sw) at
    OfficeOpenXml.ExcelWorksheet.SaveXml() at OfficeOpenXml.ExcelWorksheet.
    Save() at OfficeOpenXml.ExcelWorkbook.Save() at
    OfficeOpenXml.ExcelPackage.GetAsByteArray(Boolean save) at
    ASP._3709a01c_9c4c_425e_a710_10d1095ce4ca_1735241207.FillExcel(DataTable
    table) in http://server/sitename/Report_Testing.aspx:line 125
    The action that failed was: Demand The type of the first permission that
    failed was: System.Security.Permissions.IsolatedStorageFilePermission The
    first permission that failed was: The demand was for: The granted set of
    the failing assembly was: The assembly or AppDomain that failed was:
    EPPlus, Version=2.9.0.1, Culture=neutral, PublicKeyToken=ea159fdaa78159a1
    The method that caused the failure was: Void UpdateRowCellData  
    (System.IO.StreamWriter) The Zone of the assembly that failed was:
    MyComputer The Url of the assembly that failed was:
    file:///C:/inetpub/wwwroot/wss/VirtualDirectories/2236/bin/EPPlus.DLL

0 个答案:

没有答案