Epplus在Web项目上使用模板

时间:2014-09-24 14:44:30

标签: c# asp.net templates web epplus

我一直在使用.NET桌面项目(C#)上的epplus并使用这样的模板:

var package = new ExcelPackage(new FileInfo("C:\\Templates\\FormatoReporteSamsung.xlsx"))

但是现在我正在使用.NET Web项目(C#)而且我不知道是什么使得引用像Web资源一样存在的模板,其资源的URI如下所示:

http://myownweb:29200/Content/excelTemplates/Formato.xlsx 

1 个答案:

答案 0 :(得分:0)

最后,我使用此代码将excel模板作为流传递。

using (var package = new ExcelPackage(new MemoryStream(GetBytesTemplate(FullyQualifiedApplicationPath + "Content/excelTemplates/Format.xlsx"))))
    {
        //Write data to excel

        //Read file like byte array to return a response
        Response.Clear();
        Response.ContentType = "application/xlsx";
        Response.AddHeader("content-disposition", "attachment; filename=" + "myFileName" + ".xlsx");
        Response.BinaryWrite(package.GetAsByteArray());
        Response.End();
    }

要读取excel文件有字节,我使用它 Error "This stream does not support seek operations" in C#

private byte[] GetBytesTemplate(string url)
        {
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
            WebResponse myResp = myReq.GetResponse();

            byte[] b = null;
            using (Stream stream = myResp.GetResponseStream())
            using (MemoryStream ms = new MemoryStream())
            {
                int count = 0;
                do
                {
                    byte[] buf = new byte[1024];
                    count = stream.Read(buf, 0, 1024);
                    ms.Write(buf, 0, count);
                } while (stream.CanRead && count > 0);
                b = ms.ToArray();
            }

            return b;
        }

并获取我使用的网站的名称 http://devio.wordpress.com/2009/10/19/get-absolut-url-of-asp-net-application/

public string FullyQualifiedApplicationPath
        {
            get
            {
                //Return variable declaration
                string appPath = null;

                //Getting the current context of HTTP request
                HttpContext context = HttpContext.Current;

                //Checking the current context content
                if (context != null)
                {
                    //Formatting the fully qualified website url/name
                    appPath = string.Format("{0}://{1}{2}{3}",
                      context.Request.Url.Scheme,
                      context.Request.Url.Host,
                      context.Request.Url.Port == 80
                        ? string.Empty : ":" + context.Request.Url.Port,
                      context.Request.ApplicationPath);
                }
                if (!appPath.EndsWith("/"))
                    appPath += "/";
                return appPath;
            }
        }