GithubHelp home page GithubHelp logo

closedxml / closedxml.report Goto Github PK

View Code? Open in Web Editor NEW
504.0 504.0 107.0 5.04 MB

ClosedXML.Report is a tool for report generation with which you can easily export any data from your .NET classes to Excel using a XLSX-template.

Home Page: https://closedxml.github.io/ClosedXML.Report/

License: MIT License

C# 100.00%
c-sharp closedxml dotnet excel reporting

closedxml.report's Introduction

ClosedXML

Release NuGet Badge .NET Framework .NET Standard Build status Open Source Helpers

💾 Download unstable CI build

ClosedXML is a .NET library for reading, manipulating and writing Excel 2007+ (.xlsx, .xlsm) files. It aims to provide an intuitive and user-friendly interface to dealing with the underlying OpenXML API.

For more information see the documentation or the wiki.

Release notes & migration guide

The public API is still not stable and it is a very good idea to read release notes and migration guide before each update.

Performance

Performance matters mostly for large files. For small files, few ms here or there doesn't matter. The presented data are from generally develop branch (currently 0.103-beta).

Runtime details ``` BenchmarkDotNet v0.13.8, Windows 11 (10.0.22621.2283/22H2/2022Update/SunValley2) AMD Ryzen 5 5500U with Radeon Graphics, 1 CPU, 12 logical and 6 physical cores .NET SDK 8.0.100-rc.1.23463.5 [Host] : .NET 7.0.11 (7.0.1123.42427), X64 RyuJIT AVX2 ```

Save

Description Rows Columns Time/Memory to insert data Save workbook Total time/memory
Mixed (text/number) workbook.
Gist
250 000 15 1.619 sec / 117 MiB 6.343 sec 7.962 sec / 477 MiB
Text only workbook. Gist 1 000 000 10 6.302 sec / 402 MiB 17.134 sec 23.436 sec / 1880 MiB

Load

Description Rows Columns Time to load data Used memory
Load mixed workbook (10 text/5 number columns). 250 000 15 15.648 sec 236 MiB
Text only workbook. 1 000 000 10 49.046 sec 801 MiB

Load tests used files created during save test.

Frequent answers

  • If you get an exception Unable to find font font name or fallback font fallback font name. Install missing fonts or specify a different fallback font through ‘LoadOptions.DefaultGraphicEngine = new DefaultGraphicEngine(“Fallback font name”)’, see help page about missing fonts.
  • ClosedXML is not thread-safe. There is no guarantee that parallel operations will work. The underlying OpenXML library is also not thread-safe.
  • If you get an exception The type initializer for 'Gdip' threw an exception. on Linux, you have to upgrade to 0.97+.

Install ClosedXML via NuGet

If you want to include ClosedXML in your project, you can install it directly from NuGet

To install ClosedXML, run the following command in the Package Manager Console

PM> Install-Package ClosedXML

What can you do with this?

ClosedXML allows you to create Excel files without the Excel application. The typical example is creating Excel reports on a web server.

Example:

using (var workbook = new XLWorkbook())
{
    var worksheet = workbook.Worksheets.Add("Sample Sheet");
    worksheet.Cell("A1").Value = "Hello World!";
    worksheet.Cell("A2").FormulaA1 = "=MID(A1, 7, 5)";
    workbook.SaveAs("HelloWorld.xlsx");
}

Extensions

Be sure to check out our ClosedXML extension projects

Developer guidelines

The OpenXML specification is a large and complicated beast. In order for ClosedXML, the wrapper around OpenXML, to support all the features, we rely on community contributions. Before opening an issue to request a new feature, we'd like to urge you to try to implement it yourself and log a pull request.

Please read the full developer guidelines.

Credits

closedxml.report's People

Contributors

b0bi79 avatar davija avatar dependabot[bot] avatar erestor avatar gersondias avatar igitur avatar jafin avatar makeprojectgreatagain avatar pallu avatar pankraty avatar reivaj810 avatar smakaiberriesandco avatar srihar avatar tobaloidee avatar vakssonya avatar vbondarev avatar zsu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

closedxml.report's Issues

Refer to <<sum>> cell in formula

I've been trying to create a table that takes the totals of each column from another table (the <> cell) to perform other calculation starting from there.

Pointing to the cell using an excel formula (like "=Sheet1!A5") keeps pointing at the same cell in the final file, no matter how many rows have been added above. Escaping the formula ("&=Sheet1!A5") ends in the same result.
Trying to calculate the ending position of the cell using the knowledge of the number of rows that will be added ends up moving the cell down by about (but not exactly) double the amount of rows.

Either I have failed to find in the wiki the way to accomplish this, or it is not possible to implement in the current version so I'd love to have something to accomplish this as a feature.

No overload for method 'Relative' takes 2 parameters

The 2 extension methods called Relative (in XlExtensions.cs), one for IXLRangeAddress (line 132)which takes one parameter IXLRangeAddress; and the other one is for IXLCell (line 147) that takes one parameter IXLAddress.

On line 216 the Intersection Method returns a IXLRangeAddress and tries to call a Range method that takes two parameters! Both of which are IXLRangeBase, not IXLRangeAddress.

How are you getting this to compile? I'm trying to compile with Visual Studio 4 Mac.

Screen Shot 2019-07-30 at 14 14 30

Big report file causes IsolatedStorageException {"Unable to determine the identity of domain."}

This is a known issue for ClosedXML library when working with big files - ClosedXML/ClosedXML#264
And looks like for ClosedXML it was solved in version 0.93.1. ClosedXML.report library was installing ClosedXML 0.92.1.0. I have tried to update it and got a message "The type 'IXLWorkbook' is defined in an assembly that is not referenced. You must add a reference to assembly 'ClosedXML, Version=0.92.1.0, Culture=neutral, PublicKeyToken=fd1eb21b62ae805b'".

Is there a way to avoid domain issue in ClosedXML.report?

Current release 0.1.2 has screwed up references

The release that is out on nuget (0.1.2) currently claims it has a dependency on ClosedXML >=0.92.1.

However, I am using 0.94.2 (due to some bugfixes that I need) and I am getting reference errors due to how the references are defined in the project (says it must reference version 0.92.1.0).

This is a show-stopper for me as I need the bugfixes in later versions of ClosedXML and would still like to be able to use ClosedXML.Reports (I cannot use a beta version at this point either).

Pivot table's number of fields limit

Did the pivot table have the limit of column count will not able work? as i try it and i get a error when the number of columns more than 11.

Is there a way to display rows horizontal rather then vertically.

I was unable to find in documentation if there is a way to display items in one next to the other rather one under the other. Range horizontal displays everything horizontally. What I need is items to be displayed inline like so:
Row1 | Row2 | Row3 |
Col1 | Col1 | Col1 |
Col2 | Col2 | Col2 |
Rather then
Row1 | Col1 | Col2|
Row2 | Col1 | Col2|
Row3 | Col1 | Col2|
I am not sure if there is a pivot function for this,the docs are in Russian.

{{items.Count()}} in my template gives Unknown identifier 'items' error in excel output

Hi Team,

Thanks for this wonderful Package. I'm using the latest beta. As per the docs, the following link says,

Expressions are enclosed in double braces {{ }} and utilize the syntax similar to C#. Lambda expressions are supported.

{{items.Where(i => i.Currency == "RUB").Count()}}

So I tried just to get count from items using {{items.Count()}} in my excel template but I'm getting the following error,

Unknown identifier 'items'

Please assist on where I'm wrong.

Template:
image

Output:
image

Thanks,
Abdul

Help Wanted. Can we create a nested range with 6 levels.

Hello Team,
I need your valuable help. Actually I am creating a report based on employee attendance. I am able to get the 3 levels of the nested range and I am able to see the report.
But on the 4th level, I need to use the list object to populate the data. But I am unable to do that.
I have attached the report template that I have created.
EmployeeReport_Data_1.xlsx
EmployeeReport.xlsx

could you please help in this regard?

Thanks & Regards,
Seshu Kumar.

Problem with NuGet after update 0.92.1 is in the ClosedXML.Report

After updating the DLL via NuGet, we get the message from the compiler. It looks like the reference fix to version 0.92.1 is in the ClosedXML.Report.

Message from the compiler

After Update the main 'ClosedXML', we
Error CS0012 The type 'IXLWorkbook' is defined in an assembly that is not referenced. You must add a reference to assembly 'ClosedXML, Version=0.92.1.0, Culture=neutral, PublicKeyToken=fd1eb21b62ae805b'. SanSoft.DotNet.COM D:\Projekte\SanSoft.DotNet\SanSoft.DotNet.COM\Tools\Excel\RecordsetToExcel.cs 24 Active

Need Help

Hi,
How can I highlight the row based on a condition.
for example I have a value in cell A and based on the cell value I need to highlight the row with a color.
How can I achieve this.
Thanks & Regards,
Seshu Kumar.

How to do grouping inside nested range?

Hi

Grouping works inside nested range? Any sample template for that? Please assist.

I checked grouping works inside nested range. but <<group MergeLabels placetocolumn=n>><<Delete>> not working. Please assist

Thanks,
Abdul

print

After Generate (), can you support direct printing?

Adding custom text into subtotals row

I want to write custom text inside subtotals (and totals) row. How can i do? After generation my cells with custom text become empty. I don't want to add some string by parameter TotalLabel, i want use custom string in any empty sell inside subtotals row.

This is image what i want.

image

Is it possible to group a column based on another field value?

I'm trying to generate report as shown below. Is this possible? Please assist.

Let's say I have List<Product> where Product is,

public class Product
{
    public string Category {get: set;}
    public string Name {get; set;}
}

Now I want to do grouping based on Category but display Name in that column. Can this be done?

image

As you can see I have Name as column header and that should display Name but group by Category and display that as summary.

nullreferenceexception with RowsFit tag when empty data source.

As @BenKmann wrote:

I still get an Exception. Nullref because of the RowsFitTag.

bei ClosedXML.Report.Options.RowsFitTag.Execute(ProcessingContext context)
bei ClosedXML.Report.Options.TagsList.Execute(ProcessingContext context)
bei ClosedXML.Report.RangeTemplate.RangeTagsApply(IXLRange range, Object[] items)
bei ClosedXML.Report.RangeInterpreter.EvaluateValues(IXLRange range, Parameter[] pars)
bei ClosedXML.Report.RangeInterpreter.Evaluate(IXLRange range)
bei ClosedXML.Report.XLTemplate.Generate()

Condition is, Empty Datasource + i use the following Tags in Column A <<summaryabove>><<DisableGrandTotal>><<RowsFit>>

RowsFit than is pretty unhappy about the 0 rows. If i Remove <<RowsFit>> the Exception disappears.

Is there a way to conditional coloring of rows?

Hello!

I'm trying to implement an report with this lib.
And i have a question:

How can i colorize some data rows in report basing on data?
For example: i want to colorize row of subgroup in blue in case of existence of best price,
otherwise, if there two or more equal best prices i want to colorize this two or more rows in yellow.
How to do this? :)
image

RowHeight is not set correctly in added rows

The documentation says "Styles from the template are applied to the inserted cells."
But the rowheight of each row is apparently not taken from my contentarrea, but from the existing row. Apparently it just moves in the next row, instead of adding new rows.

If you look at my Template you see, that the rowheight in Row 7 is pretty small.
template

But if you look at the resulting document, you see in row 11 for example, that he took the rowheight of the row 11 that was in the template.
document

That way he kills the formatting of every row below the defined Area and kills the formatting inside the Area.

I also added the Template if it helps.
buggy.xlsx

I can also submit the code to generate the undesired behaviour if you need it.

I use the newest available Versions
"ClosedXML" version="0.95.0-beta1" targetFramework="net452"
"ClosedXML.Report" version="0.2.0-beta1" targetFramework="net452"

multiple primitive types in a variable array raises System.ArgumentException: 'Object of type 'x' cannot be converted to type 'y'

Great library, however I am having an issue when mixing types in an array when using AddVariable.
For example:


const string outputFile = @"out.xlsx";

			var template = new XLTemplate(@"template.xlsx");
			var strings = new[] {
				"string",
				"1" ,
				"string",
				};

			var mixed = new[] {
				(object) "string",
				(object) 1 ,
				(object) "string",
				};

			
			template.AddVariable("strings", strings);
			template.AddVariable("mixed", mixed);
			template.Generate();

The mixed array will generate a System.ArgumentException: 'Object of type 'System.Int32' cannot be converted to type 'System.String' when the template is generated.

I looked through the source and the issue is in FormulaEvaluator.cs the constructor for the internal Parameter it is setting an expected type: i.e Expression.Parameter(value.GetType(), name)
however by changing it to ParameterExpression = Expression.Parameter(typeof(object), name);
the error no longer occurs.

The reason converting all values to strings is undesirable is, the generated excel file shows a warning: the number in the cell is formatted as text or preceded by a apostrophe.
This also causes a side effect that any number formatting on that cell will be ignored (like currency)

Pivot table could not work

Everything is fine in flat table. After we try to add <> to the same template file and set up column define like below picture. But it not works.
default

When we run in the process.
System had a error in Saveas. And it show "source" parameter could not be null.

default

error message as below
於 System.Linq.Enumerable.Any[TSource](IEnumerable`1 source)
於 ClosedXML.Excel.XLWorkbook.GeneratePivotTableCacheDefinitionPartContent(PivotTableCacheDefinitionPart pivotTableCacheDefinitionPart, IXLPivotTable pt, SaveContext context)
於 ClosedXML.Excel.XLWorkbook.GeneratePivotTables(WorkbookPart workbookPart, WorksheetPart worksheetPart, XLWorksheet xlWorksheet, SaveContext context)
於 ClosedXML.Excel.XLWorkbook.CreateParts(SpreadsheetDocument document, SaveOptions options)
於 ClosedXML.Excel.XLWorkbook.CreatePackage(String filePath, SpreadsheetDocumentType spreadsheetDocumentType, SaveOptions options)
於 ClosedXML.Excel.XLWorkbook.SaveAs(String file, SaveOptions options)
於 ClosedXML.Excel.XLWorkbook.SaveAs(String file, Boolean validate, Boolean evaluateFormulae)
於 ClosedXML.Excel.XLWorkbook.SaveAs(String file)
於 ClosedXML.Report.XLTemplate.SaveAs(String file)

Thanks in advance.

WIP Upgrade ClosedXML to 0.93

Work in progress and most of the features are working already, but I had to pause it for a while.
Put it here for you @b0bi79 were aware and not doing a double work.

Feature Request: Worksheet per item in List

I'd like to create one worksheet per item from a list.

For example in case I pass an IEnumerable to the template
template.AddVariable(customers);
and the name of the template worksheet is something like
{{ item.Name }}
the report generator should iterate through the customers list and create one worksheet for every item in the list.

Another approach:
passing a variable data that contains an IEnumerable<Customer> Customers
template.AddVariable(data);
and worksheet with label
{{ Customers.Name }}
should trigger the generation of a single worksheet per customer.
tab template

Using Template containing certain Excel 2013 conditional formatting selections causes NullReferenceException

  1. Create a template in Excel with a vertical table with a detail cell formatted with the "Color Scales -> Red Yelllow Green Color Scale" selection from the Conditional Formatting menu.
  2. Attempt to apply the template.
  3. Exception occurs:
    System.NullReferenceException
    HResult=0x80004003
    Message=Object reference not set to an instance of an object.
    Source=ClosedXML.Report
    StackTrace:
    at ClosedXML.Report.Excel.XlExtensions.<>c.b__30_0(KeyValuePair2 v) at System.Linq.Enumerable.WhereEnumerableIterator1.MoveNext()
    at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
    at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
    at ClosedXML.Report.Excel.XlExtensions.ReplaceCFFormulaeToR1C1(IXLWorksheet worksheet)
    at ClosedXML.Report.XLTemplate.Generate()
    ...

Error in template while adding employee list

Hi
I am getting error while adding the list of employee in template.
Error:

The range does not meet the requirements of the list ranges. For details, see the documentation.

Please check the code:
`
var people = new List
{
new Employee {Name = "Alice", Address = "dfsasdasdasd",Phone="312312312"},
new Employee {Name = "Alice1", Address = "dfsasdasdasd1",Phone="2131232"},
new Employee {Name = "Alice3", Address = "dfsasdasdasd3",Phone="5645"}
};
template.AddVariable("employee", people);
template.Generate();
template.SaveAs(outputFile);
public class Employee
{
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}

`
Please check the error screen shot.
Template:

screenshot_2

Output:

screenshot_1

Note : for string and integer values it's working fine. but issue with list

Adding support for comment templating.

First thank you guys, this is a great repo!

I added a comment to a cell, and inside the comment I wrote an expression like {{item.Comment}},
but in the generated file, the comment is missing.

I looked the code, and it seems that comment templating is not supported.
Will you consider supporting this feature?

New Logo

@Tobaloidee, can I ask you to redesign the green version of the ClosedXML logo? Our library is based on ClosedXML and is designed to generate reports in Excel using templates. If you find a little time, you could add ClosedXML.Report specific attributes to the original ClosedXML logo, for example {{}} or << >>. But it's not a matter of principle, I'm hope for your professional opinion.

Sorry for my English.

NuGet package

Please create a NuGet package and add installation instructions in the README.

Dictionary as data source

Hi,

Is it possible to pass dictionary to template as a variable for usecase when data structure is being specified only in runtime?
so not to create class:
`
class Person {
string FirstName { get; set; }
string LastName { get; set; }
}

...

template.AddVariable(personObj)
but
var data = SomeDataRetrievingMethod();
template.AddVariable(data);
`

Thank you

System.NullReferenceException

There is an exception - here is full stack:

ClosedXML.Report.dll!ClosedXML.Report.Parameter.Parameter(string name, object value) Line 72 C#
ClosedXML.Report.dll!ClosedXML.Report.RangeTemplate.RenderCell(object[] items, int i, ClosedXML.Report.FormulaEvaluator evaluator, ClosedXML.Report.TemplateCell cell) Line 276 C#
ClosedXML.Report.dll!ClosedXML.Report.RangeTemplate.HorizontalTable(object[] items, ClosedXML.Report.FormulaEvaluator evaluator) Line 334 C#
ClosedXML.Report.dll!ClosedXML.Report.RangeTemplate.Generate(object[] items) Line 149 C#
ClosedXML.Report.dll!ClosedXML.Report.RangeTemplate.RenderSubrange(object item, ClosedXML.Report.FormulaEvaluator evaluator, ClosedXML.Report.TemplateCell cell, ClosedXML.Report.Options.TagsList tags, ref int iCell, ref int row) Line 291 C#
ClosedXML.Report.dll!ClosedXML.Report.RangeTemplate.VerticalTable(object[] items, ClosedXML.Report.FormulaEvaluator evaluator) Line 182 C#
ClosedXML.Report.dll!ClosedXML.Report.RangeTemplate.Generate(object[] items) Line 153 C#
ClosedXML.Report.dll!ClosedXML.Report.RangeInterpreter.EvaluateValues(ClosedXML.Excel.IXLRange range, ClosedXML.Report.Parameter[] pars) Line 146 C#
ClosedXML.Report.dll!ClosedXML.Report.RangeInterpreter.Evaluate(ClosedXML.Excel.IXLRange range) Line 36 C#
ClosedXML.Report.dll!ClosedXML.Report.XLTemplate.Generate() Line 83 C#

Exception is caused by null item in object array passed to RenderCell method. There are two ways to fix it - first allow null values in array if array type is specified (other than object[]), second - just guard it to not to throw it as internal null reference but add some explanation in exception details.

I leave solution to author but IMHO null values (like string) are pretty common and should be supported in same way as empty strings.

Error loading report generated on ReoGrid

Good morning, I am creating a report which is generated successfully, but when loading it into the ReoGrid control (https://github.com/unvell/ReoGrid) I get an error and it does not open it.

But if I generate an excel with ClosedXML (not ClosedXML.Report) it opens without problems
There is a difference in the generation of the two

If I open and save the file (Report) with excel, ReoGrid opens it without problems

The code to generate the Report is as follows
image
If anyone has had this problem and has solved it, help me, thanks

Pivot table error based on size of table

I have a simple application that creates a Excel file, a table, and a pivot table based on the table. The table columns are static at 10, and rows vary but a generally between 35,000 and 40,000. In this case, if the row count exceeds 32,895 then the pivot table isn't created correctly and I get the old error saying "We found a problem with some content in [file name]. Do you want to recover..." and the repairs log:

Removed Feature: PivotTable report from /pivotCache/pivotCacheDefinition1.xml part (PivotTable cache)
Removed Feature: PivotTable report from /xl/pivotTables/pivotTable.xml part (PivotTable view)
Removed Records: Workbook properties from /xl/workbook.xml part (Workbook).

If I manually keep the rows to 32,895 in the PivotTables.Add definition, it creates the files correctly without the error.

CSharp code below and created file attached.
Test2.xlsx

{
static void Main(string[] args)
{
String fileName = "DeliveryCompliace " + DateTime.Today.ToString("MMddyyyy") + ".xlsx";
String runTime = DateTime.Now.ToString("MM/dd/yyyy HH:mm");
String reportDate = DateTime.Today.ToLongDateString();

        // Create Workbook
        XLWorkbook wb = new XLWorkbook();
        // Create Worksheet
        IXLWorksheet ws = wb.Worksheets.Add("Data");

        
        // Fill table from stored procedure
        SqlConnection sqlConnection = new SqlConnection(Properties.Settings.Default.conString);
        SqlCommand sqlCommand = new SqlCommand("dbo.cex_DScanCompData", sqlConnection);
        sqlCommand.CommandType = CommandType.StoredProcedure;
        sqlCommand.Parameters.Add("@dDate", SqlDbType.DateTime).Value = reportDate;
        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
        DataTable dataTable = new DataTable();
        sqlDataAdapter.Fill(dataTable);

        // Insert Datatable data
        IXLTable table = ws.Cell(1, 1).InsertTable(dataTable, "Data", true);

        // Fix OrderTrackingID format in ws
        ws.Column(5).CellsUsed().Style.NumberFormat.Format = "#.000000";
        // Adjust column widths in ws
        ws.Columns().AdjustToContents();

        // Pivot Table
        // Add new worksheet
        IXLWorksheet ps = wb.Worksheets.Add("Report");

        // Create pivot table
        var totalRows = ws.LastRowUsed().RowNumber() - 5;
        var totalColumns = ws.LastColumnUsed().ColumnNumber();
        IXLPivotTable pt = ps.PivotTables.Add("PivotTable", ps.Cell(3, 1), ws.Range(1,1,totalRows,totalColumns)); // Max rows 32,895!!

        pt.RowLabels.Add("TerminalName").SetCollapsed();
        pt.RowLabels.Add("Driver").SetCollapsed();
        pt.RowLabels.Add("ConsCompany", "Client").SetCollapsed();

        pt.Values.Add("PkgCount").SetSummaryFormula(XLPivotSummary.Sum);
        pt.Values.Add("DScan").SetSummaryFormula(XLPivotSummary.Sum);
        pt.Values.Add("MScan").SetSummaryFormula(XLPivotSummary.Sum);
        pt.Values.Add("NScan").SetSummaryFormula(XLPivotSummary.Sum);

        //For testing purposes
        IXLWorksheet ws3 = wb.Worksheets.Add("Test");
        ws3.Cell("A1").Value = totalRows;
        ws3.Cell("A2").Value = totalColumns;

        // Save workbook
        wb.SaveAs(@"C:\Users\CEsolutions\Documents\Test2.xlsx");
    }

}

No property or field in type

Hi

I am getting an error in the excel file "No property or field '' exists in type 'List`1'" .
Is there any option to pass a data table to the excel template. if yes then it will be of a great help.

Unknown Identifier error while accessing variables inside nested ranges

Hi,

I have the below class,

public class ExcelReportModel<T>
    {
        public ExcelReportHeader Header { get; set; }
        public IEnumerable<T> Records { get; set; }
        public int DataYear { get; } = Globals.DataYear;
    }

Now if I use DataYear inside my excel like this {{DataYear}} it works. But If I use the same inside any range like Records range its not working. Please assist

Thanks

Clarification needed to populate table

I have read the doc on Flat Tables, but can't understand the connection between the Orders & the template's item element.

What I was trying to achieve:
I have the following template:
image

I have to print data from the following class:

class SoldItemsReport
    {
        public string Company { get; set; }
        public string Branch { get; set; }
        public string Phone { get; set; }
        public string FromDate { get; set; }
        public string ToDate { get; set; }

        public List<SoldItem> SoldItems { get; set; }

        public SoldItemsReport(string company, string branch, string phone, string fromDate, string toDate, object items)
        {
            Company= company;
            Branch = branch;
            Phone = phone;
            FromDate = fromDate;
            ToDate = toDate;
            SoldItems = items as List<SoldItem>;
        }
    }

The data setup code is copied from the above mentioned doc & now like the following:

string outputFile = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/report.xlsx";
            try
            {
                using (var template = new XLTemplate(@".\report_template_sold_items.xlsx"))
                {
                    // NOTE: The following variables are also working perfectly, besides the grouped model data
                    // template.AddVariable("Company", Pref.GetRestaurantName());
                    // template.AddVariable("Branch", Pref.GetBranchName());
                    // template.AddVariable("Phone", Pref.GetBranchPhone());
                    // template.AddVariable("FromDate", fromDateStr);
                    // template.AddVariable("ToDate", DateTime.Now.ToString("yyyy-MM-dd"));

                    var items = ListViewSoldItems.Items;
                    template.AddVariable(new SoldItemsReport("My Company",
                        "Main Branch",
                        "+182374870",
                        fromDateStr,
                        DateTime.Now.ToString("yyyy-MM-dd"),
                        items));

                    template.Generate();
                    template.SaveAs(outputFile);
                }
                ShowSuccess("Path: " + outputFile);
                //Show report
                Process.Start(new ProcessStartInfo(outputFile) { UseShellExecute = true });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                ShowError("Sorry! Cannot generate XLSX now.");
            }

Both the commented AddVariable & model-packaged AddVariable methods are working for the plain fields, but range-variables (range is named as SoldItems) are not setting data rather printing the tags as it is (like: {{item.OrderCount}}, <<sum>> etc.).

Am I missing any very basic point? I have gone through all the basic docs of this library with my naive knowledge of spreadsheet processing, but with no luck. Please give me any kind of hint/clarification about which I may have missed.

Comma in Worksheet Name on Template causes InvalidOperationException

  1. Create a template
  2. Add a second worksheet
  3. Rename the sheet to a name containing a comma
  4. Add a valid vertical table definition to the sheet
  5. Attempt to apply the template
  6. Exception occurs:
    System.InvalidOperationException
    HResult=0x80131509
    Message=Sequence contains no matching element
    Source=System.Core
    StackTrace:
    at System.Linq.Enumerable.Single[TSource](IEnumerable1 source, Func2 predicate)
    at ClosedXML.Excel.XLNamedRange.<get_Ranges>b__9_3(<>f__AnonymousType32 <>h__TransparentIdentifier0) at System.Linq.Enumerable.<>c__DisplayClass7_03.b__0(TSource x)
    at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext() at ClosedXML.Excel.XLNamedRange.get_Ranges() at ClosedXML.Report.Excel.XlExtensions.<>c__DisplayClass7_0.<GetContainingNames>b__0(IXLNamedRange x) at System.Linq.Enumerable.<>c__DisplayClass6_01.b__0(TSource x)
    at System.Linq.Enumerable.WhereEnumerableIterator1.MoveNext() at System.Linq.Buffer1..ctor(IEnumerable1 source) at System.Linq.Enumerable.ToArray[TSource](IEnumerable1 source)
    at ClosedXML.Report.RangeInterpreter.ParseTags(IXLRange range, String rangeName)
    at ClosedXML.Report.RangeInterpreter.Evaluate(IXLRange range)
    at ClosedXML.Report.XLTemplate.Generate()
    ...

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.