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

Created Unassigned: Auto Height for Rows [9432]

$
0
0
Great library but one trouble here - if you like to copy and modify rows often you touch row's height property . Then library sets height as CustomHeight.
So it seems the most simple way looks like to set CustomHeight off

I suppose to to set height as automatically with special function like int other openexcel libraries
SetAutoHeight()

Name actually does not matter

Could you consider ability to add Function to reset Height of Row to allow Excel automatically set it?

Here code working for me:
IXLRows.cs
namespace ClosedXML.Excel
{
public interface IXLRows: IEnumerable<IXLRow>, IDisposable
{
...
/// <summary>
/// Set the height of all rows as auto. Excel should set height automatically then.
/// </summary>
IXLRows SetAutoHeight();
...



XLRows.cs
namespace ClosedXML.Excel
{
using System.Collections;

internal class XLRows : IXLRows, IXLStylized
{
...
public IXLRows SetAutoHeight()
{
_rows.ForEach(r => r.SetAutoHeight());
return this;
}
...


XLRow.cs
namespace ClosedXML.Excel
{
internal class XLRow : XLRangeBase, IXLRow
{
...

internal object SetAutoHeight()
{
int row = RowNumber();
var thisRow = Worksheet.Internals.RowsCollection[row];
//Ensure for now that row height will be auto
thisRow.HeightChanged = false;
HeightChanged = false;
return this;
}

}
}


New Comment on "Adjust Row Height and Column Width to Contents"

$
0
0
Is there any way to set the row height for each row so it fits all the text from a certain column (with word wrap enabled)?

Created Unassigned: Errors in Formulas: improve API for graceful handling [9433]

$
0
0
A customer-provided Excel document contained a Formula referencing a second file using a formula like

```
='C:\Temp\[A.xlsx]Country'!$A$3
```

which results in a `System.Exception`: Identifier expected.
at

```
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.XLWorksheet.Evaluate(String expression)
at ClosedXML.Excel.XLCell.get_Value()
at ClosedXMLRepro.Program.Main(String[] args) in ClosedXMLRepro\Program.cs:line 31
```

As documented in issues like https://closedxml.codeplex.com/workitem/9402 there seems to be an issue with the formula parser if single quotes are involved. It looks like there is currently no (easy?) way to check for formula validity before accessing a cell value. I don't suspect that cross file references are supported at all.
I was hoping for a way to validate a formula or a defined set of distinct Exception types (e.g. like UnsupportedFormulaException, SyntaxException) to be able to better distinguish what is going on.

New Post: Cell metadata?

$
0
0
I'm building an app that reads a data dictionary file and uses ClosedXML to build a fairly complex Excel workbook based on its contents. I need to store some meta-information at the cell level in a number of locations so another tool can later consume the excel file and relate certain cells back to the data dictionary.

I know that OpenXML offers cell level metadata and ExtensionList objects (though I haven't found many concrete examples of how they're used); does ClosedXML offer any kind of metadata mechanism that doesn't involve comments or hidden columns?

Failing that, is there any way to map a ClosedXML cell object directly to its OpenXML equivalent? Otherwise I assume if I have to go the OpenXML-for-metadata route I'll have to save & close the file from ClosedXML and reopen it in OpenXML for a second pass through to apply the metadata.

New Comment on "Documentation"

$
0
0
Hello I need Help with this. In office interop, I use: ((Range)excelWorksheet.Rows[RowIndex + 1]).Select(); ((Range)excelWorksheet.Rows[RowIndex + 1]).Insert(XlInsertShiftDirection.xlShiftToRight, XlInsertFormatOrigin.xlFormatFromLeftOrAbove); But in ClosedXML I do not how to used. I use: excelWorksheet.Row(RowIndex + 1).Select(); excelWorksheet.Row(RowIndex + 1).InsertRowsBelow(1); But in the excel the Data do not respect the position. My excel have a Graph but this superposstion in the data. Anyone can help me Thanks Michel Laos mlaos@dcp.pe

Created Unassigned: Extra empty cells added when inserting comment [9434]

$
0
0
When adding a comment to a cell extra empty cells are added in the excel sheet which are not touched by the code.

With the following code:
```
var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Test");

var cell = worksheet.Cell(1, 1);
cell.Comment.AddText("test comment");

using (var ms = File.Open("Test.xlsx", FileMode.CreateNew))
{
workbook.SaveAs(ms);
}
```

You can find these cells in the Excel application by using the 'Find & Select' option, select 'Go To Special' and select 'Blanks' and press OK (see screenshot).

I think it is strange because these cells are not actually touched, but they are updated when writing the excel data. Normally it is not a problem, but our client complaints about it because they are using it to import data with a script which cannot handle the extra blanks in the sheet.

The problem lies in the surrounding cells which are requested from the XLCellsCollection object. When the comments are added the GenerateShape method is called which calls the GetAnchor method. This method requests the surrounding cells to determine the anchor which updates the the MaxColumnUsed and MaxRowUsed properties of the collection. These properties are updated, but are not actually used.

I want to fix this problem, but I do not know what this anchor means or does. When I remove the anchor from the ClientData on the Shape which is generated it results in the exact same output and the comments are displayed ok.

Can someone help me fixing this problem?

Thnx, Erwin

Created Unassigned: COUNTIF function [9435]

$
0
0
The following code
```
XLWorkbook xw = new XLWorkbook();
IXLWorksheet ws = xw.AddWorksheet("ASheet");

ws.Cell("A1").Value = 2;
ws.Cell("A2").Value = 1;
ws.Cell("A3").Value = 3;
ws.Cell("A4").Value = 1;
ws.Cell("A10").FormulaA1 = @"=COUNTIF(A1:A4;""1""))";
Debug.Print(ws.Cell("A10").Value.ToString());

```
fires an "Identifier expected" issue.


New Post: Save choking on formula in GetA1Column

$
0
0
I have a spreadsheet that was working as a template (using ClosedXML to add data to the template). After opening the template with Excel 2010 and saving it (no other changes), it began to fail on Save() in ClosedXML.

After downloading the ClosedXML source, and running it in debug, the failure is in the XLCell.cs in the "GetA1Column" method when it is passed a columnPart = "C-".

You can duplicate this with a very simple spreadsheet. Enter the formula "=IF(ISERROR(B1-(B2)),0,B1-(B2))" in cell B3. Drag the formula across to E3 (copies the formula into C3, D3, and E3). Save the spreadsheet as "C:\Test.xslx".

Create a Console program (I used the ClosedXML_Sandbox) that opens and tries to save the Text.xlsx spreadsheet, it should fail in the GetA1Column method (on the line "columnToReturn = XLHelper.GetColumnLetterFromNumber(Address.ColumnNumber + Int32.Parse(columnPart.Substring(mIndex)) + columnsToShift);" with the error


"System.FormatException was unhandled
HResult=-2146233033
Message=Input string was not in a correct format.
Source=mscorlib
StackTrace:
   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)
   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
   at System.Int32.Parse(String s)
   at ClosedXML.Excel.XLCell.GetA1Column(String columnPart, Int32 columnsToShift) in c:\Development\ClosedXML\ClosedXML\ClosedXML\Excel\Cells\XLCell.cs:line 1831
   at ClosedXML.Excel.XLCell.GetA1Address(String r1C1Address, Int32 rowsToShift, Int32 columnsToShift) in c:\Development\ClosedXML\ClosedXML\ClosedXML\Excel\Cells\XLCell.cs:line 1807
   at ClosedXML.Excel.XLCell.GetFormula(String strValue, FormulaConversionType conversionType, Int32 rowsToShift, Int32 columnsToShift) in c:\Development\ClosedXML\ClosedXML\ClosedXML\Excel\Cells\XLCell.cs:line 1762
   at ClosedXML.Excel.XLCell.GetFormulaA1(String value) in c:\Development\ClosedXML\ClosedXML\ClosedXML\Excel\Cells\XLCell.cs:line 1738
   at ClosedXML.Excel.XLCell.get_FormulaA1() in c:\Development\ClosedXML\ClosedXML\ClosedXML\Excel\Cells\XLCell.cs:line 937
   at ClosedXML.Excel.XLCell.get_InnerText() in c:\Development\ClosedXML\ClosedXML\ClosedXML\Excel\Cells\XLCell.cs:line 139
   at ClosedXML.Excel.XLWorkbook.<GenerateSharedStringTablePartContent>b__df(IXLCell c) in c:\Development\ClosedXML\ClosedXML\ClosedXML\Excel\XLWorkbook_Save.cs:line 700
   at ClosedXML.Excel.XLCellsCollection.<GetCells>d__1a.MoveNext() in c:\Development\ClosedXML\ClosedXML\ClosedXML\Excel\Cells\XLCellsCollection.cs:line 418
   at System.Linq.Enumerable.<SelectManyIterator>d__14`2.MoveNext()
   at ClosedXML.Excel.XLWorkbook.GenerateSharedStringTablePartContent(SharedStringTablePart sharedStringTablePart, SaveContext context) in c:\Development\ClosedXML\ClosedXML\ClosedXML\Excel\XLWorkbook_Save.cs:line 696
   at ClosedXML.Excel.XLWorkbook.CreateParts(SpreadsheetDocument document) in c:\Development\ClosedXML\ClosedXML\ClosedXML\Excel\XLWorkbook_Save.cs:line 133
   at ClosedXML.Excel.XLWorkbook.CreatePackage(String filePath, SpreadsheetDocumentType spreadsheetDocumentType) in c:\Development\ClosedXML\ClosedXML\ClosedXML\Excel\XLWorkbook_Save.cs:line 91
   at ClosedXML.Excel.XLWorkbook.Save() in c:\Development\ClosedXML\ClosedXML\ClosedXML\Excel\XLWorkbook.cs:line 417
   at ClosedXML_Sandbox.Program.Main(String[] args) in c:\Development\ClosedXML\ClosedXML\ClosedXML_Sandbox\Program.cs:line 18
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
InnerException:

Edited Unassigned: COUNTIF function [9435]

$
0
0
The following code
```
XLWorkbook xw = new XLWorkbook();
IXLWorksheet ws = xw.AddWorksheet("ASheet");

ws.Cell("A1").Value = 2;
ws.Cell("A2").Value = 1;
ws.Cell("A3").Value = 3;
ws.Cell("A4").Value = 1;
ws.Cell("A10").FormulaA1 = @"=COUNTIF(A1:A4;""1"")";
Debug.Print(ws.Cell("A10").Value.ToString());

```
fires an "Identifier expected" issue.


New Post: About EXCEL's chart programming

$
0
0
Dear colleagues !

Do I correctly understand that ClosedXML does not work with charts ?
That is, ClosedXML has not methods to add/delete chart, to manipulate chart's data, etc.
Or I have missed something ?

Thank you !

New Post: Inserting a formula in a TotalsRow

$
0
0
Hi,

I have a simple Excel sales report, with 4 columns: customer, turnover, margin, and margin percentage.
I have added a TotalsRow (awesome functionality by the way), with sums of the turnover and margin columns, and the average of the margin percentage. Sounds straightforward, but this is not correct, because obviously the margin percentages are not weighted by the turnover and margin in the total average.

For example:
Customer Turnover Margin Margin %
Customer A 10,000 5,000 50 %
Customer B 100,000 25,000 25 %
Total: 110,000 30,000 37.5 %

The total margin % is actually 27.3 % (30K / 110K), not 37.5 % (75 / 2)

So in my code, I add the totalsRow, and then I tried to simply replace the content of the total margin percentage cell with a formula (Total margin / total turnover).

The problem is, this always results in Excel claiming that there is unreadable content, after which it empties the cell, and also the cell to the left. So I end up with:
Customer Turnover Margin Margin %
Customer A 10,000 5,000 50 %
Customer B 100,000 25,000 25 %
Total: 110,000

Can I, or how should I write formulas like this to cells in the TotalsRow ?

Regards,
Johan

Commented Unassigned: Unreadable content in Excel file after deleting sheets [9428]

$
0
0
I have a template .xlsx file which I open with ClosedXML, populate with necessary info, and depending on the user options, delete some irrelevant sheets (mostly the empty ones). Then I save the file, but when the user tries to open the file, Excel complains about unreadable content (a common error, I know).

My sheets contain NamedRanges and Tables, and there are also some pivot tables. I try to delete these all explicitly before deleting the actual sheet, but I think some reference somewhere still remains.

I attach a simplified version of the empty template file, some code that shows how I delete the sheets, and the resultant file that has the 'unreadable content'.

We're on Excel 2010, Windows 7 32b, ClosedXML 0.76.0.0

Please advise.

``` C#
private void DeleteIrrelevantSheet(XLWorkbook wb)
{
new string[] {
"YieldCurvePivot",
"GeneratedYieldCurveEntries"
}.ForEach(s => DeleteSheetAndTable(wb, s));
}

private void DeleteSheetAndTable(XLWorkbook wb, string sheetName)
{
var sheet = wb.Worksheet(sheetName);

//Delete named ranges on workbook level pointing to sheet
string[] namedRangesToDelete = wb.NamedRanges.Where(nr => nr.RefersTo.Contains(sheetName)).Select(nr => nr.Name).ToArray();
foreach (var nr in namedRangesToDelete)
{
wb.NamedRanges.Delete(nr);
}

//Delete named ranges on sheet level pointing to sheet
foreach (var sheet2 in wb.Worksheets)
{
namedRangesToDelete = sheet2.NamedRanges.Where(nr => nr.RefersTo.Contains(sheetName)).Select(nr => nr.Name).ToArray();
foreach (var nr in namedRangesToDelete)
{
sheet2.NamedRanges.Delete(nr);
}
}

//Delete tables
var tablesToDelete = sheet.Tables.Select(t => t.Name).ToArray();
foreach (var table in tablesToDelete)
{
sheet.Tables.Remove(table);
}

//Delete pivot tables
sheet.PivotTables.DeleteAll();
sheet.Delete();
}

```
Comments: If someone can help me pinpoint what is going wrong in the XML files in the .xlsx file, I can try to write a patch. But I don't know the schema well enough to find the problem.

Created Unassigned: Traverse merged cells? [9436]

$
0
0
Currently if we use cell.CellRight(), we can traverse the cells as if they were unmerged. This is fine. However, this imposes strict requirements on file structure of my users. If they choose to merge multiple cells then I have to change code so I am jumping over cells to account for merging. ClosedXML provides a way to know if a cell is merged (IsMerged()), however there is no way to find out which merged range current cell belongs to.

I think this would a nice feature to have. Either this, or traverse cells in a way so that it automatically skips remaining cells in merged range.

Created Issue: Loading an XLSX file fails with NullReferenceException [9437]

$
0
0
NullReferenceException occurs in XLWorkbook_Load method when opening attached XLSX file:

```
var xl new XLWorkbook(path);
```


> at ClosedXML.Excel.XLWorkbook.LoadConditionalFormatting(ConditionalFormatting conditionalFormatting, XLWorksheet ws, Dictionary`2 differentialFormats) in c:\work\QualiSystems\Trunk\Tools\API\3rdParty\ClosedXml\Sources\ClosedXML\ClosedXML\ClosedXML\Excel\XLWorkbook_Load.cs:line 1425

Can be fixed by adding null check:
```

if (conditionalFormatting == null || conditionalFormatting.SequenceOfReferences == null ) return;
```


Edited Issue: Loading an XLSX file fails with NullReferenceException [9437]

$
0
0
NullReferenceException occurs in XLWorkbook_Load method when opening attached XLSX file:

```
var xl = new XLWorkbook("Bug_118703_WriteMatrixToExcelNullReferenceException.xlsx");
```


> at ClosedXML.Excel.XLWorkbook.LoadConditionalFormatting(ConditionalFormatting conditionalFormatting, XLWorksheet ws, Dictionary`2 differentialFormats) in c:\work\QualiSystems\Trunk\Tools\API\3rdParty\ClosedXml\Sources\ClosedXML\ClosedXML\ClosedXML\Excel\XLWorkbook_Load.cs:line 1425

Can be fixed by adding null check:
```

if (conditionalFormatting == null || conditionalFormatting.SequenceOfReferences == null ) return;
```



Created Unassigned: Permission problem using ClosedXML with Microsoft NAV [9438]

$
0
0
I use OpenXML to create Excel Workbooks in Microsoft NAV 2013R2. In my development environment everything works without problems. When I try to execute the function in the customer environment I get a security error message (see Attachment).

Any ideas how to solve the problem?

Edited Unassigned: Permission problem using ClosedXML with Microsoft NAV [9438]

$
0
0
I use ClosedXML to create Excel Workbooks in Microsoft NAV 2013R2. In my development environment everything works without problems. When I try to execute the function in the customer environment I get a security error message (see Attachment).

Any ideas how to solve the problem?

Commented Issue: Loading an XLSX file fails with NullReferenceException [9437]

$
0
0
NullReferenceException occurs in XLWorkbook_Load method when opening attached XLSX file:

```
var xl = new XLWorkbook("Bug_118703_WriteMatrixToExcelNullReferenceException.xlsx");
```


> at ClosedXML.Excel.XLWorkbook.LoadConditionalFormatting(ConditionalFormatting conditionalFormatting, XLWorksheet ws, Dictionary`2 differentialFormats) in c:\work\QualiSystems\Trunk\Tools\API\3rdParty\ClosedXml\Sources\ClosedXML\ClosedXML\ClosedXML\Excel\XLWorkbook_Load.cs:line 1425

Can be fixed by adding null check:
```

if (conditionalFormatting == null || conditionalFormatting.SequenceOfReferences == null ) return;
```


Comments: The bug is reproduced only when file name is "MoBC_1111_MoCBC_PD11______.1T__DUStr.xlsx"

Created Unassigned: ClosedXML doc can't be open using Spire.Xls [9439]

$
0
0

I want to open a file created by ClosedXML.Excel and then user Spire.XLS to save it as a PDF.

The following code creates a simple Excel file using ClosedXML.Excel.
If I try to open the file using Spire.XLS I get a "Root element is missing" error.

If I open the file using Microsoft Excel and then save it, I can then open it using Spiral.

Any ideas why I can't open it in Spire without first saving it using Microsoft.Excel?



__var FilePath = @"c:\output.xlsx";
File.Delete(FilePath);


var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Data");
worksheet.Cell("A1").Value = "Hello World!";
workbook.SaveAs(FilePath);

// IF YOU OPEN AND SAVE THE FILE IN EXCEL THEN ALL WILL BE WELL, OTHERWISE YOUR'RE FUCKED
Spire.Xls.Workbook spWorkbook = new Spire.Xls.Workbook();
spWorkbook.LoadFromFile(FilePath);


var settings = new Spire.Xls.Converter.PdfConverterSettings() { FitSheetToOnePage = Spire.Xls.Converter.FitToPageType.ScaleWithSameFactor };
var pdf = Spire.Xls.PdfConvertionHelper.SaveExcelToPdf(spWorkbook, settings);

pdf.SaveToFile(Path.ChangeExtension(FilePath,"pdf"));__

Created Unassigned: Style.Border.InsideBorder always work at 1st worksheet [9440]

$
0
0
```
ws.Range(row1, col1, row2, col2).Style.Border.InsideBorder = XLBorderStyleValues.Thin;
```
always work at 1st worksheet.

```
ws.Cell(row1, col1).Style.Border.InsideBorder = XLBorderStyleValues.Thin;
```
is same(always work at 1st worksheet).

Now I'm coding
```
ws.Range(row1, col1, row1, col1).Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
```
for each cell.

Thank you.
Viewing all 1877 articles
Browse latest View live


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