Giter VIP home page Giter VIP logo

Comments (5)

Pankraty avatar Pankraty commented on May 24, 2024 3

Template gives you an access to Workbook property which is the good old ClosedXML workbook which you can operate with.

from closedxml.report.

fingers10 avatar fingers10 commented on May 24, 2024 2

Hey Pankraty,

Here is how I return my excel report from asp.net core razor pages.

Steps:

  1. Button Click in JavaScript:
$('#btnGenerateReport').click(() => {
            window.location.href = '/Index/ExcelReport';
        });
  1. Page Handler in Asp.Net Core Razor Pages:
public async Task<IActionResult> OnGetExcelReportAsync()
        {
           var data = await Task.Run(() => get data from db);
            var variable = new ExcelReportModel<ReportModel>
            {
                CompanyName = "Demo",
                Records = data
            };

            return new ExcelReportFromTemplate<ReportModel>(@"wwwroot\templatepath", variable, "DemoReport");
        }
  1. ExcelReportFromTemplate Action Result:
public class ExcelReportFromTemplate<T> : IActionResult
    {
        public ExcelReportFromTemplate(string templatePath, object templateVariable, string fileName)
        {
            TemplatePath = templatePath;
            TemplateVariable = templateVariable;
            FileName = fileName;
        }

        public string TemplatePath { get; set; }
        public object TemplateVariable { get; set; }
        public string FileName { get; set; }

        public async Task ExecuteResultAsync(ActionContext context)
        {
                byte[] excelBytes;
                var template = new XLTemplate(TemplatePath);

                template.AddVariable(TemplateVariable);
                template.Generate();
                template.Workbook.Worksheets
                    .Worksheet(template.Workbook.Worksheets.First().Name)
                    .ColumnsUsed()
                    .AdjustToContents();

                using (var stream = new MemoryStream())
                {
                    template.Workbook.SaveAs(stream);
                    excelBytes = stream.ToArray();
                }

                context.HttpContext.Response.Headers["content-disposition"] =
                    $"attachment; filename={FileName}.xlsx";

                await context.HttpContext.Response.Body.WriteAsync(excelBytes, 0, excelBytes.Length);
        }
    }

Please correct if I'm wrong on ClosedXML Part. Inside ExecuteResultAsync() method in step 3, I'm using

template.Workbook.Worksheets .Worksheet(template.Workbook.Worksheets.First().Name) .ColumnsUsed() .AdjustToContents();

does this have any performance issues?

Thanks,
Fingers10

from closedxml.report.

Pankraty avatar Pankraty commented on May 24, 2024 1

Sure. SaveAs() method can save data not only to the file on disk but also to the stream, and you can open a MemoryStream which is sent as a response.

You may also find it convenient to use this lib: https://github.com/ClosedXML/ClosedXML.Extensions.WebApi. It adds an extenstion method for you could simply call template.Workbook.Deliver("report.xlsx"); after the report is generated.

from closedxml.report.

fingers10 avatar fingers10 commented on May 24, 2024

Thanks for the reply.

I found a way to generate Excel stream using ClosedXML and return to browser. But the problem is can I achieve the same using ClosedXML.Report? Once I load data and generate the template how can I get the stream from template? template has only SaveAs with a string path to store; as far as I have seen from report docs. Am I missing something?

The example code only has SaveAs() saving to path.

protected void Report()
    {
        const string outputFile = @".\Output\report.xlsx";
        var template = new XLTemplate(@".\Templates\report.xlsx");

        using (var db = new DbDemos())
        {
            var cust = db.customers.LoadWith(c => c.Orders).First();
            template.AddVariable(cust);
            template.Generate();
        }

        template.SaveAs(outputFile);

        //Show report
        Process.Start(new ProcessStartInfo(outputFile) { UseShellExecute = true });
    }

Please assist

from closedxml.report.

fingers10 avatar fingers10 commented on May 24, 2024

Really? I'll give a try and paste the complete working sample code here. Please don't close till that. This would be helpful to someone. Any updates on next stable release? From milestone I see 60% complete. Any tentative dates?

Because if I use the latest beta of ClosedXML.Report it requires latest beta of ClosedXML. So now ClosedXML also becomes a beta so I'm afraid if something might break..

from closedxml.report.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.