Quantcast
Channel: ClosedXML - The easy way to OpenXML
Viewing all 1877 articles
Browse latest View live

Updated Wiki: Pivot Table example

$
0
0

Pivot Tables

In this example, we'll create a pivot table of monthly pastry sales. First, we'll need our Pastry class:
    public class Pastry
    {
    	public Pastry(string name, int amount, string month)
	    {
	   		Month = month;
		    Name = name;
		    NumberOfOrders = amount;
	    }
	    
	    public string Name { get; set; }
	    public int NumberOfOrders { get; set; }
	    public string Month { get; set; }
    }

Next, we'll mock up some data:
    var pastries = new List<Pastry>
    {
 	   new Pastry("Croissant", 150, "Apr"),
	    new Pastry("Croissant", 250, "May"),
	    new Pastry("Croissant", 134, "June"),
	    new Pastry("Doughnut", 250, "Apr"),
	    new Pastry("Doughnut", 225, "May"),
	    new Pastry("Doughnut", 210, "June"),
	    new Pastry("Bearclaw", 134, "Apr"),
	    new Pastry("Bearclaw", 184, "May"),
	    new Pastry("Bearclaw", 124, "June"),
	    new Pastry("Danish", 394, "Apr"),
	    new Pastry("Danish", 190, "May"),
	    new Pastry("Danish", 221, "June"),
	    new Pastry("Scone", 135, "Apr"),
	    new Pastry("Scone", 122, "May"),
	    new Pastry("Scone", 243, "June")
    };

And then we'll create a worksheet with this data in a table:
    var workbook = new XLWorkbook();
    var sheet = workbook.Worksheets.Add("PastrySalesData");
    
    // Insert our list of pastry data into the "PastrySalesData" sheet at cell 1,1
    var source = sheet.Cell(1, 1).InsertTable(pastries, "PastrySalesData", true);

Finally, we'll use that table as the source for our pivot table:
    // Create a range that includes our table, including the header row
    var range = source.DataRange;
    var header = sheet.Range(1, 1, 1, 3);
    var dataRange = sheet.Range(header.FirstCell(), range.LastCell());
    
    // Add a new sheet for our pivot table
    var ptSheet = workbook.Worksheets.Add("PivotTable");
    
    // Create the pivot table, using the data from the "PastrySalesData" table
    var pt = ptSheet.PivotTables.AddNew("PivotTable", ptSheet.Cell(1, 1), dataRange);
    
    // The rows in our pivot table will be the names of the pastries
    pt.RowLabels.Add("Name");
    
    // The columns will be the months
    pt.ColumnLabels.Add("Month");
    
    // The values in our table will come from the "NumberOfOrders" field
    // The default calculation setting is a total of each row/column
    pt.Values.Add("NumberOfOrders");

This will create a pivot table with a row for each pastry, a column for each month, and sales numbers in the cells. Each column and row will be totaled.


Commented Issue: replace function [6499]

$
0
0
will there be a function on the workbook or the worksheet to replace a given string?
 
it could look something like that :
 
workbook.replace("what you search", "what you want to replace it with");
 
I could do it but i think my program would lose a lot of time to do it.
Comments: ** Comment from web user: d2020 **

MDeLeaon, (and others)

Would explain to what the var "c" is?
And I am not familiar with the => operator, I'm curious.

I think most important - would you convert this line to VB.

I see the parameter defined as "predicate As System.Func(Of ClosedXML.Excel.IXLCell,Boolean)) As ClosedXML.Excel.IXLCells

I'm just not sure where to go from here.
Any explanation or direction is greatly appreciately.

Thx,
Max

Commented Issue: replace function [6499]

$
0
0
will there be a function on the workbook or the worksheet to replace a given string?
 
it could look something like that :
 
workbook.replace("what you search", "what you want to replace it with");
 
I could do it but i think my program would lose a lot of time to do it.
Comments: ** Comment from web user: MDeLeon **

c is for cell. Lookup c# lambdas to know what '=>' is.

New Post: Exporting gridview to excel with multiple headers

$
0
0
Hello,
I am able to export to excel gridview with one header. But how do I export gridview with two headers? Please any help is greatly appreciated.
Thanks

New Post: Exporting gridview to excel with multiple headers

New Post: Code examples on creating Pivot Table?

$
0
0
Thank you. It's a very good example. I wish I had know that ClosedXML could be used to create Pivot tables, because I ended up using Aspose.Cells to do mine. It's a pretty good product, but I still find the API from ClosedXML simpler and closer to the way I think of Excel files. Thanks again.

New Post: Exporting gridview to excel with multiple headers

$
0
0
I do not understand, are you saying that I can not do with closedxml? What do you mean manually ?

New Post: Exporting gridview to excel with multiple headers


New Post: Memory problem with ClosedXML

$
0
0
I am doing a test where I create a workbook, then add two spreadsheets on it and 500,000 rows with one test value in the first cell. Every object is initialised with the using keyword.

Memory consumption shoots up to 1GB and stays there, even after I have saved the workbook and exited the using bracket (but not the application).

I have profiled the app using ANTS. It looks as if the bulk of the memory is held in Generation 2 and consists of XLAddress, XLRow, XLCell and string objects (these must be the values)

I am not sure if this is standard behaviour? Ideally I would like ClosedXML to release those resources when it's finished because the service on which I am using it runs many such reports.

Is there any way of marshalling back that memory, other than using GC.Collect() ?

New Post: Creating Hyperlinks in "large" (greater than 41967 links) - corrups xlsx file

$
0
0
1) per http://office.microsoft.com/en-us/excel-help/excel-specifications-and-limits-HP010342495.aspx?CTT=1 the max HYPERLINK limit per workbook is 66530.

2) However, if I generate, using Closed XML, any more than 41967 hyperlinks I get errors opening the spreadsheet:
a) "Excel Found unreadable content in <filename>. Do you want to recover the contents of this workbook? If you trust the source of this workbook, click Yes."
b) I click yes, then get a pop up - titled: "Repairs to <filename> with a message:
"Removed Feature: hyperlnks from xl/worksheets/sheet.xml part"
"Click to veiw log files listing repairs: C:\users\<account>\appdata\local\temp\error......xml"

which just shows me the same information above.
(see attachments.)

Any workarounds or positive direction would be greatly appreciated.

Regards,
https://www.sugarsync.com/pf/D7819871_76810965_702952
https://www.sugarsync.com/pf/D7819871_76810965_702968
https://www.sugarsync.com/pf/D7819871_76810965_702976

Commented Issue: Error when using SaveAs [8078]

$
0
0
First, let me thank you for this library, it is really awsome and probably saved me a lot of coding time.
 
I have a problems with the SaveAs function.
I have an application that is using version 0.63.0 (Jan 2012). It was working fine until the file template that is used was changed.
I am now receiving the following error when using the SaveAs function: {"The 'br' start tag on line 18 position 87 does not match the end tag of 'font'. Line 19, position 9."}
 
I tried updating to the latest release of the library but now I have an error with the old file that worked before as well as with the newer file: "The given key was not present in the dictionary".
 
I cannot attach my file to the incident since it is over the 4MB limit but I could send it by email.
 
Thanks,
-Dan-
Comments: ** Comment from web user: jasjodi **

Has this been fixed yet? I see there are other people experiencing this error. it occurs on any sheet containing conditional formating.

Created Issue: Open ClosedXML Doc on Android Device [8736]

$
0
0
Last year, I converted a program-generated Excel file from the old Microsoft document API to Open XML. It was clunky and time consuming, until I discovered ClosedXML. Wow! What a difference. It has been deployed for a year how, and is working great.

The documents are sent to users as attachments in emails. Recently, users have begun reading their email on their personal Android and iPad tablet PC's and phones. Most of the documents open with no issue, but one or two of the Excel files (created using Closed XML) give an error. The users quickly learned that if the opened the file on their Windows PC and then saved it and forwarded it to themselves via email, that then they could open the file on their mobile device. Obviously, they would like to not have to perform this extra step.

I have confirmed the scenario by copying a file and then opening it and saving it, then sending both to my Android phone. Sure enough, the latter works, but the original does not. I did a compare of both files using the Open XML 2.0 Productivity Tool, and the differences are very minor.

Has anyone encountered this problem, and is there any advice on how I can correct the problem? I am attaching both files for review and assessment.

Thanks.

Commented Issue: Open ClosedXML Doc on Android Device [8736]

$
0
0
Last year, I converted a program-generated Excel file from the old Microsoft document API to Open XML. It was clunky and time consuming, until I discovered ClosedXML. Wow! What a difference. It has been deployed for a year how, and is working great.

The documents are sent to users as attachments in emails. Recently, users have begun reading their email on their personal Android and iPad tablet PC's and phones. Most of the documents open with no issue, but one or two of the Excel files (created using Closed XML) give an error. The users quickly learned that if the opened the file on their Windows PC and then saved it and forwarded it to themselves via email, that then they could open the file on their mobile device. Obviously, they would like to not have to perform this extra step.

I have confirmed the scenario by copying a file and then opening it and saving it, then sending both to my Android phone. Sure enough, the latter works, but the original does not. I did a compare of both files using the Open XML 2.0 Productivity Tool, and the differences are very minor.

Has anyone encountered this problem, and is there any advice on how I can correct the problem? I am attaching both files for review and assessment.

Thanks.
Comments: ** Comment from web user: caums **

Adding second attachment

New Post: Memory problem with ClosedXML

$
0
0
I was having a similar problem.
The quick version is that I was doing a loop in the loop.
My spreadsheet have about 250,000 rows.
The first pass of the 2nd loop took my 8g machine into an out of memory crash.

I solved by doing a .select to "find" the row for which I was looking.

If you want to post the most relevant code,. I will take a look at.

Mitch

Patch Uploaded: #14484

$
0
0

hartez has uploaded a patch.

Description:
This addresses two possible sources of NullReferenceExceptions when opening a file:

1. A Null WorkbookStylesPart - this is the problem when opening the example file provided by FirebirdUK in issue #8631.

2. Null WorkbookProperties object when looking for the Date1904 setting - I encountered this in Excel files output by ActiveReports (which is what led me to look at this issue in the first place).


Updated Wiki: Documentation

$
0
0

Some Updates, 

Hi All, well i am the new care taker, i have been going through the code and i will be starting on some new features, the most requested of which are pivot table. Stay tuned. 

-Amir 



Please don't ask questions on the comments section of the documentation pages because Codeplex doesn't send notifications for them. Please use the discussion tab instead. Thanks.

Requirements:

To use ClosedXML you must reference the following DLL: DocumentFormat.OpenXml.dll (part of MS Open XML SDK 2.0)

FAQ

How do I deliver an Excel file in ASP.NET?
Does it support Excel 2003 and prior formats (.xls)?
How can I insert an image?
Text with numbers are getting converted to numbers, what's up with that?
How do I get the result of a formula?

Examples

Showcase - No nonsense example of how to use this API
Basic Table
Hello World - Proverbial hello world program

Real world scenarios

Finding and extracting the data

Time Savers

Simplifying your life...

Performance and Memory

Turning off events
Better lambdas
Where to use the using keyword
Other performance improvements

Misc

Data Types - How to handle and convert cell's data types (Text, Boolean, DateTime, Numeric)
Creating Multiple Worksheets
Organizing Sheets
Loading and Modifying Files
Using Lambda Expressions
Cell Values
Workbook Properties
Using Formulas
Evaluating Formulas- New
Creating Rows/Columns Outlines
Hide Unhide Row(s)/Column(s)
Freeze Panes
Copying Worksheets
Using Hyperlinks
Data Validation
Hide Worksheets
Sheet Protection
Tab Colors
Conditional Formatting
Pivot Table example

Inserting Data/Tables

Copying IEnumerable Collections - Using "cell.Value = collection"
Inserting Data - Using "cell.InsertData(collection)"
Inserting Tables - Using "cell.InsertTable(collection)"
Adding DataTable as Worksheet
Adding DataSet

Styles

Styles - Alignment
Styles - Border
Styles - Fill
Styles - Font
Styles - NumberFormat
NumberFormatId Lookup Table
Style Worksheet
Style Rows and Columns
Using Default Styles
Using Colors
ClosedXML Predefined Colors
Excel Indexed Colors
Using Rich Text
Using Phonetics

Ranges

Defining Ranges
Merging Cells
Clearing Ranges
Deleting Ranges
Multiple Ranges
Shifting Ranges
Transpose Ranges
Named Ranges
Accessing Named Ranges- New
Copying Ranges
Using Tables
Sorting Data
Selecting Cells and Ranges

Rows

Row Height and Styles
Selecting Rows
Inserting Rows
Inserting and Deleting Rows
Adjust Row Height and Column Width to Contents
Row Cells

Columns

Column Width and Styles
Selecting Columns
Inserting Columns
Inserting and Deleting Columns
Adjust Row Height and Column Width to Contents
Column Cells

Page Setup (Print Options)

Pages Tab
Paper Size Lookup Table
Margins Tab
Headers and Footers Tab
Sheet Tab
Print Areas and Page Breaks

AutoFilters

Adding an AutoFilter to a Range
Filter Values
Custom Filters

Comments

Visibility
Position
Signatures
Style - Alignment
Style - Colors and Lines
Style - Size
Style - Protection
Style - Properties
Style - Margins
Style - Web

New Post: Identifier Expected

$
0
0
Hello,

I am trying to copy information from one area of a ClosedXML sheet to another. I have the following setup:

Sheet1 is just data - as extracted from sql server (using ClosedXML - getting this happening was awesome; thank you MDeLeon).


On Sheet2 are a number of "='Sheet1'!<CellRef>" formulas (where <CellRef> is the A1 style reference for the cell).


I am trying to copy the information in those cells Sheet2 cells to a different range on Sheet2 using the following:
double sourceValue = ws.Cell("B12").GetDouble();
ws.Cell("B32").Value = sourceValue;
According to my understanding of the 'Evaluating a Formula' functionality, this should work, and give me the value of the cell (as a double). Please correct me if I have got this wrong.

However I am getting an 'Identifier Expected' exception on the double sourceValue = ... line with the following stacktrace:
   at ClosedXML.Excel.CalcEngine.CalcEngine.Throw(String msg)
   at ClosedXML.Excel.CalcEngine.CalcEngine.GetToken()
   at ClosedXML.Excel.CalcEngine.CalcEngine.ParseExpression()
   at ClosedXML.Excel.CalcEngine.CalcEngine.Parse(String expression)
   at ClosedXML.Excel.CalcEngine.ExpressionCache.get_Item(String expression)
   at ClosedXML.Excel.CalcEngine.CalcEngine.Evaluate(String expression)
   at ClosedXML.Excel.CalcEngine.CellRangeReference.GetValue(IXLCell cell)
   at ClosedXML.Excel.CalcEngine.CellRangeReference.GetValue()
   at ClosedXML.Excel.CalcEngine.XObjectExpression.Evaluate()
   at ClosedXML.Excel.CalcEngine.Expression.op_Implicit(Expression x)
   at ClosedXML.Excel.CalcEngine.BinaryExpression.Evaluate()
   at ClosedXML.Excel.CalcEngine.CalcEngine.Evaluate(String expression)
   at ClosedXML.Excel.XLWorksheet.Evaluate(String expression)
   at ClosedXML.Excel.XLCell.get_Value()
   at ClosedXML.Excel.XLCell.TryGetValue[T](T& value)
   at ClosedXML.Excel.XLCell.GetValue[T]()
   at ClosedXML.Excel.XLCell.GetDouble()
   at LGFinance.ViewModel.MainViewModel.InsertExpenditureWorkings(IXLWorksheet sheet, Int32 startRow)
What have I done wrong? :-)

Closed Issue: Strange values returned, bad value in cell [8535]

$
0
0
I have an excel file that has a formaula getting its values from other tabs. ClosedXml is returning completely different values. This is very strange behaviour. In cell M1210 there is a value (if opened with excel) of -1634290,7 located in TAB [STAGING]. Codeplex is returning the value -180807,44
Woops. Also other values in this column are having the same problem.
This is no good news.

Closed Issue: Style isnt copied with row.copyto [8493]

$
0
0
im trying to populate an XLS template, and to test the best way im using the following code[code]using System;using ClosedXML.Excel;using System.Linq;using System.Diagnostics;namespace ClosedXML_Examples{ public class Program { static void Main(string[] args) { int innerloop = 100; Stopwatch s = new Stopwatch(); for (int k = 1; k <= 1; k++) // just to test Speed-slowdown when working with Large Data. raise values for testing { XLWorkbook workbook = new XLWorkbook(XLEventTracking.Disabled); s.Reset(); s.Start(); copyDown3(makeSheet(workbook, "copy_loop"), 1, innerloop, k); s.Stop(); Console.WriteLine(string.Format("copy1 : Zeit für {0:D5} durchläufe : {1} = {2:F2} ms/100", k * innerloop, s.Elapsed, (decimal)s.ElapsedMilliseconds / (k * innerloop) * 100)); workbook.SaveAs("test.xlsx"); } Console.Read(); } static IXLWorksheet makeSheet(XLWorkbook workbook,string name) { IXLWorksheet ws = workbook.Worksheets.Add(name); ws.Cell(2, 1).Value = "ende"; // zeile 1 vorbereiten ws.Cell(1, 1).Value = 1.123; for (int x = 1; x <= 21; x++) ws.Cell(1, x).Style.NumberFormat.Format = "#,##0.00"; for (int x = 0; x < 7; x++) { ws.Cell(1, 3 * x + 1).Value = 3 * x + 1; ws.Cell(1, 3 * x + 2).Value = 3 * x + 2; ws.Cell(1, 3 * x + 3).FormulaR1C1 = "=RC[-2]+RC[-1]"; ws.Cell(1, 3 * x + 3).Style.Fill.BackgroundColor = XLColor.Xanadu; } return ws; } static void copyDown3(IXLWorksheet ws, int srcrow, int innerloop, int anz) { for (int i = 0; i < innerloop * anz; i++) { ws.Row(srcrow).CopyTo(ws.Row(srcrow + 1 + i)); // <-- Format isnt copied ! . Why ? } } }}[/code]the formulas are copied, but the styles-Formats are getting lost.am i doing something wrong, or is it bugged ?

Closed Issue: There isn't a worksheet named '#REF' [8465]

$
0
0
I've attached a simple workbook that can't be opened. It works fine with OpenXML library directly (and incidentally with NPOI and EPPlus).The Exceptions is: There isn't a worksheet named '#REF'.Details:This file was fine when first created but I then added, then deleted, sheets from another workbook that was exhibiting this same problem.I found this entry in the forum which is identical:http://closedxml.codeplex.com/discussions/350351
Viewing all 1877 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>