Skip to main content

Spreadsheet xls

  • March 24, 2016
  • 2 replies
  • 0 views

Bom dia, estou precisando criar uma planilha xls em um servidor web. Quando o usuário clicar na opção o sistema gera esta planilha, só que não posso utilizar interoperabilidade do Office. Estava tentando o EPPPlus uma dll que gera a planilha sem a necessidade do Office instalado, mas a rotina esta em c# tem como traduzir.


Good morning , I need to create an xls spreadsheet on a web server . When the user clicks the option the system generates this worksheet , I just can not use Office interoperability . Was trying EPPPlus a dll that generates the spreadsheet without the need of Office installed , but the routine is in C # is to translate.


/*******************************************************************************
 *
 * See http://epplus.codeplex.com/ for details
 *
 * Jan Källman  Added  23-MAR-2010
 *******************************************************************************/
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OfficeOpenXml;
using System.IO;
using OfficeOpenXml.Style;
using System.Drawing;
using System.Text;
namespace EPPlusWebSample
{
    public partial class GetSample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            switch (Request.QueryString["Sample"])
            {
                case "1":
                    Sample1();
                    break;
                case "2":
                    Sample2();
                    break;
                case "3":
                    Sample3();
                    break;
                case "4":
                    Sample4();
                    break;
                default:
                    Response.Write("<script>javascript:alert('Invalid querystring');</script>");
                    break;

            }
        }

        /// <summary>
        /// Sample 1
        /// Demonstrates the SaveAs method
        /// </summary>
        private void Sample1()
        {
            ExcelPackage pck = new ExcelPackage();
            var ws = pck.Workbook.Worksheets.Add("Sample1");

            ws.Cells["A1"].Value = "Sample 1";
            ws.Cells["A1"].Style.Font.Bold = true;
            var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect);
            shape.SetPosition(50, 200);
            shape.SetSize(200, 100);
            shape.Text = "Sample 1 saves to the Response.OutputStream";

            pck.SaveAs(Response.OutputStream);
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;  filename=Sample1.xlsx");
        }
        /// <summary>
        /// Sample 2
        /// Demonstrates the GetAsByteArray method
        /// </summary>
        private void Sample2()
        {
            ExcelPackage pck = new ExcelPackage();
            var ws = pck.Workbook.Worksheets.Add("Sample2");

            ws.Cells["A1"].Value = "Sample 2";
            ws.Cells["A1"].Style.Font.Bold = true;
            var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect);
            shape.SetPosition(50, 200);
            shape.SetSize(200, 100);
            shape.Text = "Sample 2 outputs the sheet using the Response.BinaryWrite method";

            Response.BinaryWrite(pck.GetAsByteArray());
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;  filename=Sample2.xlsx");
        }
        /// <summary>
        /// Sample 3
        /// Uses a cached template
        /// </summary>
        private void Sample3()
        {
            if (Application["Sample3Template"] == null) //Check if the template is loaded
            {
                //Here we create the template.
                //As an alternative the template could be loaded from disk or from a resource.
                ExcelPackage pckTemplate = new ExcelPackage();
                var wsTemplate = pckTemplate.Workbook.Worksheets.Add("Sample3");

                wsTemplate.Cells["A1"].Value = "Sample 3";
                wsTemplate.Cells["A1"].Style.Font.Bold = true;
                var shape = wsTemplate.Drawings.AddShape("Shape1", eShapeStyle.Rect);
                shape.SetPosition(50, 200);
                shape.SetSize(200, 100);
                shape.Text = "Sample 3 uses a template that is stored in the application cashe.";
                pckTemplate.Save();

                Application["Sample3Template"] = pckTemplate.Stream;
            }

            //Open the new package with the template stream.
            //The template stream is copied to the new stream in the constructor
            ExcelPackage pck = new ExcelPackage(new MemoryStream(), Application["Sample3Template"] as Stream);
            var ws = pck.Workbook.Worksheets[1];
            int row = new Random().Next(10) 10;   //Pick a random row to print the text
            ws.Cells[row,1].Value = "We make a small change here, after the template has been loaded...";
            ws.Cells[row, 1, row, 5].Style.Fill.PatternType = ExcelFillStyle.Solid;
            ws.Cells[row, 1, row, 5].Style.Fill.BackgroundColor.SetColor(Color.LightGoldenrodYellow);

            Response.BinaryWrite(pck.GetAsByteArray());
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;  filename=Sample3.xlsx");
        }
        private void Sample4()
        {
             ExcelPackage pck = new ExcelPackage();

            //Add a worksheet.
            var ws=pck.Workbook.Worksheets.Add("VBA Sample");
            ws.Drawings.AddShape("VBASampleRect", eShapeStyle.RoundRect);
           
            //Create a vba project            
            pck.Workbook.CreateVBAProject();

            //Now add some code that creates a bubble chart...
            var sb = new StringBuilder();

            sb.AppendLine("Private Sub Workbook_Open()");
            sb.AppendLine("    [VBA Sample].Shapes(\\"VBASampleRect\\").TextEffect.Text = \\"This text is set from VBA!\\"");
            sb.AppendLine("End Sub");
            pck.Workbook.CodeModule.Code = sb.ToString();

            Response.BinaryWrite(pck.GetAsByteArray());
            Response.ContentType = "application/vnd.ms-excel.sheet.macroEnabled.12";            //.xlsm files uses a different contenttype than .xlsx
            Response.AddHeader("content-disposition", "attachment;  filename=Sample4.xlsm");

        }

    }
}

2 replies

Chris Glazier
Forum|alt.badge.img+2

Bom dia, estou precisando criar uma planilha xls em um servidor web. Quando o usuário clicar na opção o sistema gera esta planilha, só que não posso utilizar interoperabilidade do Office. Estava tentando o EPPPlus uma dll que gera a planilha sem a necessidade do Office instalado, mas a rotina esta em c# tem como traduzir.


Good morning , I need to create an xls spreadsheet on a web server . When the user clicks the option the system generates this worksheet , I just can not use Office interoperability . Was trying EPPPlus a dll that generates the spreadsheet without the need of Office installed , but the routine is in C # is to translate.


/*******************************************************************************
 *
 * See http://epplus.codeplex.com/ for details
 *
 * Jan Källman  Added  23-MAR-2010
 *******************************************************************************/
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OfficeOpenXml;
using System.IO;
using OfficeOpenXml.Style;
using System.Drawing;
using System.Text;
namespace EPPlusWebSample
{
    public partial class GetSample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            switch (Request.QueryString["Sample"])
            {
                case "1":
                    Sample1();
                    break;
                case "2":
                    Sample2();
                    break;
                case "3":
                    Sample3();
                    break;
                case "4":
                    Sample4();
                    break;
                default:
                    Response.Write("<script>javascript:alert('Invalid querystring');</script>");
                    break;

            }
        }

        /// <summary>
        /// Sample 1
        /// Demonstrates the SaveAs method
        /// </summary>
        private void Sample1()
        {
            ExcelPackage pck = new ExcelPackage();
            var ws = pck.Workbook.Worksheets.Add("Sample1");

            ws.Cells["A1"].Value = "Sample 1";
            ws.Cells["A1"].Style.Font.Bold = true;
            var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect);
            shape.SetPosition(50, 200);
            shape.SetSize(200, 100);
            shape.Text = "Sample 1 saves to the Response.OutputStream";

            pck.SaveAs(Response.OutputStream);
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;  filename=Sample1.xlsx");
        }
        /// <summary>
        /// Sample 2
        /// Demonstrates the GetAsByteArray method
        /// </summary>
        private void Sample2()
        {
            ExcelPackage pck = new ExcelPackage();
            var ws = pck.Workbook.Worksheets.Add("Sample2");

            ws.Cells["A1"].Value = "Sample 2";
            ws.Cells["A1"].Style.Font.Bold = true;
            var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect);
            shape.SetPosition(50, 200);
            shape.SetSize(200, 100);
            shape.Text = "Sample 2 outputs the sheet using the Response.BinaryWrite method";

            Response.BinaryWrite(pck.GetAsByteArray());
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;  filename=Sample2.xlsx");
        }
        /// <summary>
        /// Sample 3
        /// Uses a cached template
        /// </summary>
        private void Sample3()
        {
            if (Application["Sample3Template"] == null) //Check if the template is loaded
            {
                //Here we create the template.
                //As an alternative the template could be loaded from disk or from a resource.
                ExcelPackage pckTemplate = new ExcelPackage();
                var wsTemplate = pckTemplate.Workbook.Worksheets.Add("Sample3");

                wsTemplate.Cells["A1"].Value = "Sample 3";
                wsTemplate.Cells["A1"].Style.Font.Bold = true;
                var shape = wsTemplate.Drawings.AddShape("Shape1", eShapeStyle.Rect);
                shape.SetPosition(50, 200);
                shape.SetSize(200, 100);
                shape.Text = "Sample 3 uses a template that is stored in the application cashe.";
                pckTemplate.Save();

                Application["Sample3Template"] = pckTemplate.Stream;
            }

            //Open the new package with the template stream.
            //The template stream is copied to the new stream in the constructor
            ExcelPackage pck = new ExcelPackage(new MemoryStream(), Application["Sample3Template"] as Stream);
            var ws = pck.Workbook.Worksheets[1];
            int row = new Random().Next(10) 10;   //Pick a random row to print the text
            ws.Cells[row,1].Value = "We make a small change here, after the template has been loaded...";
            ws.Cells[row, 1, row, 5].Style.Fill.PatternType = ExcelFillStyle.Solid;
            ws.Cells[row, 1, row, 5].Style.Fill.BackgroundColor.SetColor(Color.LightGoldenrodYellow);

            Response.BinaryWrite(pck.GetAsByteArray());
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;  filename=Sample3.xlsx");
        }
        private void Sample4()
        {
             ExcelPackage pck = new ExcelPackage();

            //Add a worksheet.
            var ws=pck.Workbook.Worksheets.Add("VBA Sample");
            ws.Drawings.AddShape("VBASampleRect", eShapeStyle.RoundRect);
           
            //Create a vba project            
            pck.Workbook.CreateVBAProject();

            //Now add some code that creates a bubble chart...
            var sb = new StringBuilder();

            sb.AppendLine("Private Sub Workbook_Open()");
            sb.AppendLine("    [VBA Sample].Shapes(\\"VBASampleRect\\").TextEffect.Text = \\"This text is set from VBA!\\"");
            sb.AppendLine("End Sub");
            pck.Workbook.CodeModule.Code = sb.ToString();

            Response.BinaryWrite(pck.GetAsByteArray());
            Response.ContentType = "application/vnd.ms-excel.sheet.macroEnabled.12";            //.xlsm files uses a different contenttype than .xlsx
            Response.AddHeader("content-disposition", "attachment;  filename=Sample4.xlsm");

        }

    }
}

The translation for this routine is shown below. I have not tested it so that part is up to you. Please note the literal that says Place the javascipt in here. I had to remove actual javascript as it was causing formatting problems with this post. Add back the original content before using.

      $set ilusing"System"
      $set ilusing"System.Collections.Generic"
      $set ilusing"System.Web"
      $set ilusing"System.Web.UI"
      $set ilusing"System.Web.UI.WebControls"
      $set ilusing"OfficeOpenXml"
      $set ilusing"System.IO"
      $set ilusing"OfficeOpenXml.Style"
      $set ilusing"System.Drawing"
      $set ilusing"System.Text"
       class-id EPPlusWebSample.GetSample is partial 
                inherits type System.Web.UI.Page public.
                 
       working-storage section.

       method-id Page_Load protected.
       local-storage section.
       procedure division using by value param-sender as object
                                         param-e as type System.EventArgs.
            evaluate Request::QueryString["Sample"]
               when "1"
                  invoke Sample1
               when "2"
                  invoke Sample2
               when "3"
                  invoke Sample3
               when "4"
                  invoke Sample4
               when other
                  invoke Response::Write("place the javascript in here")
           end-evaluate
       
           goback.
       end method.
 
       method-id Sample1 private.
       procedure division.
        
            declare pck as type ExcelPackage = new ExcelPackage
            declare ws = pck::Workbook::Worksheets::Add("Sample1")
            set ws::Cells["A1"]::Value to "Sample 1"
            set ws::Cells["A1"]::Style::Font::Bold to true
            declare shape = ws::Drawings::AddShape("Shape1", type eShapeStyle::Rect)
            invoke shape::SetPosition(50, 200)
            invoke shape::SetSize(200, 100)
            set shape::Text to "Sample 1 saves to the Response.OutputStream"

            invoke pck::SaveAs(Response::OutputStream)
            set Response::ContentType to "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            invoke Response::AddHeader("content-disposition", "attachment;  filename=Sample1.xlsx")

           goback.
       end method.
         *>/// 
         *>/// Sample 2
         *>/// Demonstrates the GetAsByteArray method
         *>/// 
       method-id Sample2 private.
       procedure division.
           declare pck as type ExcelPackage = new ExcelPackage
           declare ws = pck::Workbook::Worksheets::Add("Sample2")
           set ws::Cells["A1"]::Value to "Sample 2"
           set ws::Cells["A1"]::Style::Font::Bold to true
           declare shape = ws::Drawings::AddShape("Shape1", type eShapeStyle::Rect)
           invoke shape::SetPosition(50, 200)
           invoke shape::SetSize(200, 100)
           set shape::Text = "Sample 2 outputs the sheet using the Response.BinaryWrite method"
           invoke Response::BinaryWrite(pck::GetAsByteArray())
           set Response::ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
           invoke Response::AddHeader("content-disposition", "attachment;  filename=Sample2.xlsx")
           goback.

       end method.
        *>/// 
        *>/// Sample 3
        *>/// Uses a cached template
        *>/// 
       method-id Sample3 private.
       procedure division.
       
           if Application["Sample3Template"] = null *>Check if the template is loaded
             *>Here we create the template. 
             *>As an alternative the template could be loaded from disk or from a resource.
             declare pckTemplate as type ExcelPackage = new ExcelPackage
             declare wsTemplate = pckTemplate::Workbook::Worksheets::Add("Sample3")
             set wsTemplate::Cells["A1"]::Value = "Sample 3"
             set wsTemplate::Cells["A1"]::Style::Font::Bold = true
             declare shape = wsTemplate::Drawings::AddShape("Shape1", type eShapeStyle::Rect)
             invoke shape::SetPosition(50, 200)
             invoke shape::SetSize(200, 100)
             set shape::Text = "Sample 3 uses a template that is stored in the application cashe."
             invoke pckTemplate::Save
           
             set Application["Sample3Template"] = pckTemplate::Stream
           end-if

           *>Open the new package with the template stream.
           *>The template stream is copied to the new stream in the constructor
           declare pck as type ExcelPackage = new ExcelPackage(new MemoryStream, Application["Sample3Template"] as type Stream)
           declare ws = pck::Workbook::Worksheets[1]
           declare row as binary-long = new type Random()::Next(10)   10   *>Pick a random row to print the text
           set ws::Cells[row, 1]::Value = "We make a small change here, after the template has been loaded..."
           set ws::Cells[row, 1, row, 5]::Style::Fill::PatternType = type ExcelFillStyle::Solid
           invoke ws::Cells[row, 1, row, 5]::Style::Fill::BackgroundColor::SetColor(type Color::LightGoldenrodYellow)

           invoke Response::BinaryWrite(pck::GetAsByteArray())
           set Response::ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
           invoke Response::AddHeader("content-disposition", "attachment;  filename=Sample3.xlsx")
        
           goback.
       end method.
       method-id Sample4 private.
       procedure division.
           declare pck = new type ExcelPackage
           *>Add a worksheet.
           declare ws = pck::Workbook::Worksheets::Add("VBA Sample")
           invoke ws::Drawings::AddShape("VBASampleRect", type eShapeStyle::RoundRect)
            
           *>Create a vba project             
           invoke pck::Workbook::CreateVBAProject()

           *>Now add some code that creates a bubble chart...
           declare sb = new type StringBuilder

           invoke sb::AppendLine("Private Sub Workbook_Open()")
           invoke sb::AppendLine("    [VBA Sample].Shapes(""VBASampleRect"").TextEffect.Text = ""This text is set from VBA!""")
           invoke sb::AppendLine("End Sub")
           set pck::Workbook::CodeModule::Code = sb::ToString

           invoke Response::BinaryWrite(pck::GetAsByteArray())
           set Response::ContentType = "application/vnd.ms-excel.sheet.macroEnabled.12"   *>.xlsm files uses a different contenttype than .xlsx
           invoke Response::AddHeader("content-disposition", "attachment;  filename=Sample4.xlsm")
           goback.
       end method.
       end class.

  • March 31, 2016

Bom dia, estou precisando criar uma planilha xls em um servidor web. Quando o usuário clicar na opção o sistema gera esta planilha, só que não posso utilizar interoperabilidade do Office. Estava tentando o EPPPlus uma dll que gera a planilha sem a necessidade do Office instalado, mas a rotina esta em c# tem como traduzir.


Good morning , I need to create an xls spreadsheet on a web server . When the user clicks the option the system generates this worksheet , I just can not use Office interoperability . Was trying EPPPlus a dll that generates the spreadsheet without the need of Office installed , but the routine is in C # is to translate.


/*******************************************************************************
 *
 * See http://epplus.codeplex.com/ for details
 *
 * Jan Källman  Added  23-MAR-2010
 *******************************************************************************/
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OfficeOpenXml;
using System.IO;
using OfficeOpenXml.Style;
using System.Drawing;
using System.Text;
namespace EPPlusWebSample
{
    public partial class GetSample : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            switch (Request.QueryString["Sample"])
            {
                case "1":
                    Sample1();
                    break;
                case "2":
                    Sample2();
                    break;
                case "3":
                    Sample3();
                    break;
                case "4":
                    Sample4();
                    break;
                default:
                    Response.Write("<script>javascript:alert('Invalid querystring');</script>");
                    break;

            }
        }

        /// <summary>
        /// Sample 1
        /// Demonstrates the SaveAs method
        /// </summary>
        private void Sample1()
        {
            ExcelPackage pck = new ExcelPackage();
            var ws = pck.Workbook.Worksheets.Add("Sample1");

            ws.Cells["A1"].Value = "Sample 1";
            ws.Cells["A1"].Style.Font.Bold = true;
            var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect);
            shape.SetPosition(50, 200);
            shape.SetSize(200, 100);
            shape.Text = "Sample 1 saves to the Response.OutputStream";

            pck.SaveAs(Response.OutputStream);
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;  filename=Sample1.xlsx");
        }
        /// <summary>
        /// Sample 2
        /// Demonstrates the GetAsByteArray method
        /// </summary>
        private void Sample2()
        {
            ExcelPackage pck = new ExcelPackage();
            var ws = pck.Workbook.Worksheets.Add("Sample2");

            ws.Cells["A1"].Value = "Sample 2";
            ws.Cells["A1"].Style.Font.Bold = true;
            var shape = ws.Drawings.AddShape("Shape1", eShapeStyle.Rect);
            shape.SetPosition(50, 200);
            shape.SetSize(200, 100);
            shape.Text = "Sample 2 outputs the sheet using the Response.BinaryWrite method";

            Response.BinaryWrite(pck.GetAsByteArray());
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;  filename=Sample2.xlsx");
        }
        /// <summary>
        /// Sample 3
        /// Uses a cached template
        /// </summary>
        private void Sample3()
        {
            if (Application["Sample3Template"] == null) //Check if the template is loaded
            {
                //Here we create the template.
                //As an alternative the template could be loaded from disk or from a resource.
                ExcelPackage pckTemplate = new ExcelPackage();
                var wsTemplate = pckTemplate.Workbook.Worksheets.Add("Sample3");

                wsTemplate.Cells["A1"].Value = "Sample 3";
                wsTemplate.Cells["A1"].Style.Font.Bold = true;
                var shape = wsTemplate.Drawings.AddShape("Shape1", eShapeStyle.Rect);
                shape.SetPosition(50, 200);
                shape.SetSize(200, 100);
                shape.Text = "Sample 3 uses a template that is stored in the application cashe.";
                pckTemplate.Save();

                Application["Sample3Template"] = pckTemplate.Stream;
            }

            //Open the new package with the template stream.
            //The template stream is copied to the new stream in the constructor
            ExcelPackage pck = new ExcelPackage(new MemoryStream(), Application["Sample3Template"] as Stream);
            var ws = pck.Workbook.Worksheets[1];
            int row = new Random().Next(10) 10;   //Pick a random row to print the text
            ws.Cells[row,1].Value = "We make a small change here, after the template has been loaded...";
            ws.Cells[row, 1, row, 5].Style.Fill.PatternType = ExcelFillStyle.Solid;
            ws.Cells[row, 1, row, 5].Style.Fill.BackgroundColor.SetColor(Color.LightGoldenrodYellow);

            Response.BinaryWrite(pck.GetAsByteArray());
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;  filename=Sample3.xlsx");
        }
        private void Sample4()
        {
             ExcelPackage pck = new ExcelPackage();

            //Add a worksheet.
            var ws=pck.Workbook.Worksheets.Add("VBA Sample");
            ws.Drawings.AddShape("VBASampleRect", eShapeStyle.RoundRect);
           
            //Create a vba project            
            pck.Workbook.CreateVBAProject();

            //Now add some code that creates a bubble chart...
            var sb = new StringBuilder();

            sb.AppendLine("Private Sub Workbook_Open()");
            sb.AppendLine("    [VBA Sample].Shapes(\\"VBASampleRect\\").TextEffect.Text = \\"This text is set from VBA!\\"");
            sb.AppendLine("End Sub");
            pck.Workbook.CodeModule.Code = sb.ToString();

            Response.BinaryWrite(pck.GetAsByteArray());
            Response.ContentType = "application/vnd.ms-excel.sheet.macroEnabled.12";            //.xlsm files uses a different contenttype than .xlsx
            Response.AddHeader("content-disposition", "attachment;  filename=Sample4.xlsm");

        }

    }
}

It is perfect

Thank you very much.