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

New Post: Am I using NamedRanges correctly?

$
0
0
Maybe too old but I have the following problem.

When I use AddToNamed i get the folloing =Source!$A$1:$E$1,Source!$A$2:$E$63. This wrecks my pivot table data since it is based on the Source Named Range. How can I do it so that after using ws.Range("$A$2:$E$63).AddToNamed("Source") I actually get Source!$A$1:$E$63 only and not the comma separated name range

New Post: Convert range to table, treat all rows as data rows

$
0
0
Code which exports data from worksheet to datatable (iterative approach):
/// <summary>
/// Exports data and column names from ClosedXML worksheet to DataTable
/// </summary>
public static DataTable ExportWorkSheetToDataTable(IXLWorksheet worksheet)
{
    DataTable dt = new DataTable();
    int ColumnsQty = worksheet.ColumnsUsed().Count();
    int RowsQty = worksheet.RowsUsed().Count();

    // Create column names for DataTable
    for (int i = 1; i <= ColumnsQty; i++)
    {
        dt.Columns.Add(worksheet.Row(1).Cell(i).GetValue<string>());
    }

    // Add data to DataTable
    for (int i = 2; i <= RowsQty; i++)
    {
        DataRow workRow = dt.NewRow();
        for (int j = 1; j <= ColumnsQty; j++)
        {
            var CellValue = worksheet.Row(i).Cell(j).Value;
            workRow[j - 1] = CellValue;
        }
        dt.Rows.Add(workRow);
    }
    return dt;
}

New Post: Problem trying to save a workbook

$
0
0
I am having a strange problem when trying to save a particular workbook - the error is:

"Unable to determine the identity of domain."

...and the stacktrace:

at System.IO.IsolatedStorage.IsolatedStorage._GetAccountingInfo(Evidence evidence, Type evidenceType, IsolatedStorageScope fAssmDomApp, Object& oNormalized)
at System.IO.IsolatedStorage.IsolatedStorage.GetAccountingInfo(Evidence evidence, Type evidenceType, IsolatedStorageScope fAssmDomApp, String& typeName, String& instanceName)
at System.IO.IsolatedStorage.IsolatedStorage._InitStore(IsolatedStorageScope scope, Evidence domainEv, Type domainEvidenceType, Evidence assemEv, Type assemblyEvidenceType, Evidence appEv, Type appEvidenceType)
at System.IO.IsolatedStorage.IsolatedStorage.InitStore(IsolatedStorageScope scope, Type domainEvidenceType, Type assemblyEvidenceType)
at System.IO.IsolatedStorage.IsolatedStorageFile.GetStore(IsolatedStorageScope scope, Type domainEvidenceType, Type assemblyEvidenceType)
at MS.Internal.IO.Packaging.PackagingUtilities.ReliableIsolatedStorageFileFolder.GetCurrentStore()
at MS.Internal.IO.Packaging.PackagingUtilities.ReliableIsolatedStorageFileFolder..ctor()
at MS.Internal.IO.Packaging.PackagingUtilities.GetDefaultIsolatedStorageFile()
at MS.Internal.IO.Packaging.PackagingUtilities.CreateUserScopedIsolatedStorageFileStreamWithRandomName(Int32 retryCount, String& fileName)
at MS.Internal.IO.Packaging.SparseMemoryStream.EnsureIsolatedStoreStream()
at MS.Internal.IO.Packaging.SparseMemoryStream.SwitchModeIfNecessary()
at MS.Internal.IO.Packaging.SparseMemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at MS.Internal.IO.Packaging.CompressEmulationStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at MS.Internal.IO.Packaging.CompressStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at MS.Internal.IO.Zip.ProgressiveCrcCalculatingStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at MS.Internal.IO.Zip.ZipIOModeEnforcingStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.Xml.XmlUtf8RawTextWriter.FlushBuffer()
at System.Xml.XmlUtf8RawTextWriter.RawText(Char* pSrcBegin, Char* pSrcEnd)
at System.Xml.XmlUtf8RawTextWriter.RawText(String s)
at System.Xml.XmlUtf8RawTextWriter.WriteStartElement(String prefix, String localName, String ns)
at System.Xml.XmlWellFormedWriter.WriteStartElement(String prefix, String localName, String ns)
at DocumentFormat.OpenXml.OpenXmlElement.WriteTo(XmlWriter xmlWriter)
at DocumentFormat.OpenXml.OpenXmlCompositeElement.WriteContentTo(XmlWriter w)
at DocumentFormat.OpenXml.OpenXmlElement.WriteTo(XmlWriter xmlWriter)
at DocumentFormat.OpenXml.OpenXmlCompositeElement.WriteContentTo(XmlWriter w)
at DocumentFormat.OpenXml.OpenXmlElement.WriteTo(XmlWriter xmlWriter)
at DocumentFormat.OpenXml.OpenXmlCompositeElement.WriteContentTo(XmlWriter w)
at DocumentFormat.OpenXml.OpenXmlPartRootElement.WriteTo(XmlWriter xmlWriter)
at DocumentFormat.OpenXml.OpenXmlPartRootElement.SaveToPart(OpenXmlPart openXmlPart)
at DocumentFormat.OpenXml.OpenXmlPartRootElement.Save()
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.SavePartContent(OpenXmlPart part)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.TrySavePartContent(OpenXmlPart part)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.SavePartContents()
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.Dispose(Boolean disposing)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.Dispose()
at ClosedXML.Excel.XLWorkbook.CreatePackage(String filePath, SpreadsheetDocumentType spreadsheetDocumentType) in c:\Source\Sainsburys\SainsburysStoreSpace.64bit\CSharp\SainsburysStoreSpace_CSharp\ClosedXML\Excel\XLWorkbook_Save.cs:line 107
at ClosedXML.Excel.XLWorkbook.Save() in c:\Source\Sainsburys\SainsburysStoreSpace.64bit\CSharp\SainsburysStoreSpace_CSharp\ClosedXML\Excel\XLWorkbook.cs:line 417
at SainsburysStoreSpace_CSharp.GondolaExtractNew.SADHelper.SaveSADWorkBook() in c:\Source\Sainsburys\SainsburysStoreSpace.64bit\CSharp\SainsburysStoreSpace_CSharp\GondolaExtractNew\SADHelper.cs:line 75


...also, the resulting excel file is corrupted - I am prompted to repair it on opening.

I have edited/saved other workbooks with ClosedXML, but I cannot fathom what is going on with this.

Any help greatly appreciated

Commented Unassigned: Use of AddConditionalFormat > Unreadable XLS [9460]

$
0
0
Hi,

I'm opening/modifying/saving an existing Excel 2010 file. When I don't use conditional formatting > no pb to read it with MS Excel 2010 once I made the modifications. When I use conditional formatting (for instance with the following code :

xlWorksheet.Range( 4, 8, 4 + (dateTimeCount - 1), 8).AddConditionalFormat().ColorScale().Minimum(XLCFContentType.Percentile, 5.0, XLColor.LightCarminePink).Midpoint(XLCFContentType.Number, 0.0, XLColor.White).Maximum(XLCFContentType.Percentile, 95.0, XLColor.LightGreen );

The C# code executes without notice but the resulting XLS file can't be opened with MS Excel 2010 anymore. What's quite strange is that I use C# code which worked last year with an older version of ClosedXML (don't ask me which one, I lost the info) but which doesn't work anymore with the latest one (0.76.0).

Any help is welcome.

Eric
Comments: 0.75.0 works correctly. Problem seems to be the ordering of the elements underneath the ColorScale: Expected: ConditionalFormatValueObject ConditionalFormatValueObject ConditionalFormatValueObject Color Color Color Actual in 0.76.0: ConditionalFormatValueObject Color ConditionalFormatValueObject Color ConditionalFormatValueObject Color

New Post: Is a .Net Framework 4.5 or 4.5.1 release of ClosedXml coming for VS 2012?

$
0
0
Is there any update yet? I'm looking for compatibility with .NetFramework 4.5.1 and Visual Studio 2013.

Or, has anyone got experience they can share regarding using the .Net 4.0 version of ClosedXML in an application targeting 4.5.1?

Thanks,
Richard

New Post: Formula support - IRR & NPV

$
0
0
Hello,

Is there any plan to support additional advanced formulas as NPV and IRR in a future version of ClosedXML?

Thanks

New Post: Best practice for using ClosedXML in an Excel AddIn?

$
0
0
I am sure you folks are aware of the ambiguity between the assemblies:

Microsoft.Office.Interop.Excel

and

Microsoft.Office.Tools.Excel

My applications (AddIns) are becoming more and more complex. After winging it for years, I am afraid I need to take a more formal approach in order to stay away from this source of potential trouble.

I have casting all over and have code like this:
    Microsoft.Office.Interop.Excel.Range dstRange = worksheet.get_Range("B3");
    dstRange.Value2 = text;
which can be done in a nicer way with ClosedXML.

New Post: Best practice for using ClosedXML in an Excel AddIn?

$
0
0
I just discovered that my AddIns do not even use ClosedXML.

So the question becomes: How to use OpenXML inside AddIns?

TIA

New Comment on "Adding an AutoFilter to a Range"

$
0
0
Hi! I have a same problem too. is there any solition for this error?

Commented Unassigned: Use of AddConditionalFormat > Unreadable XLS [9460]

$
0
0
Hi,

I'm opening/modifying/saving an existing Excel 2010 file. When I don't use conditional formatting > no pb to read it with MS Excel 2010 once I made the modifications. When I use conditional formatting (for instance with the following code :

xlWorksheet.Range( 4, 8, 4 + (dateTimeCount - 1), 8).AddConditionalFormat().ColorScale().Minimum(XLCFContentType.Percentile, 5.0, XLColor.LightCarminePink).Midpoint(XLCFContentType.Number, 0.0, XLColor.White).Maximum(XLCFContentType.Percentile, 95.0, XLColor.LightGreen );

The C# code executes without notice but the resulting XLS file can't be opened with MS Excel 2010 anymore. What's quite strange is that I use C# code which worked last year with an older version of ClosedXML (don't ask me which one, I lost the info) but which doesn't work anymore with the latest one (0.76.0).

Any help is welcome.

Eric
Comments: I'm not sure to understand what you means. I thought it could have to do with the number format as I read on a forum that ClosedXML has a problem when the Windows version not an english one is (and mine is a french one). There was a workaround but it was so cumbersome that I didn't give it a try...

New Comment on "Adding DataSet"

$
0
0
Regarding dataSet, How can I add some rows before the dataSet info, such as header or something like that?

New Post: system out of memory exception at Saveas

$
0
0
I have the system out of memory exception at try to save my document, how can i save my workBook?

Is a .xlsx with 20 sheets and per sheet have like a 10000 rows and i have groups

I used the using keyword and i put the data by a list,

New Post: system out of memory exception at Saveas

$
0
0
JoseValdez wrote:
I have the system out of memory exception at try to save my document, how can i save my workBook?

Is a .xlsx with 20 sheets and per sheet have like a 10000 rows and i have groups

I used the using keyword and i put the data by a list,
Do you try to fill only one sheet, and then save the document, close and dispose, and after that reopen the document, save another sheet, and so on.
This should be avoid increase the memory size.
Take a look an example in OpenXML http://www.codeproject.com/Tips/659666/Export-very-large-data-to-Excel-file

New Post: Pivot Table creation results in Corrupt Spreadsheet

$
0
0
Hello,

I am using ClosedXML 0.76 in VB with VS2013 and I am trying to generate a pivot table from data that was added to a sheet via a Datatable. The Raw data itself gets inserted fine but if I generate the pivot table and then try to open the file The spreadsheet gets corrupted and in order to fix it Excel has to remove the Pivot Table entirely.

Here is the code I am using
Module Module1
    Sub Main()
        Dim CMD As New SqlCommand("SalesSum")
        Dim StartDate As Date = FormatDateTime("01-01-" & Now.Year, DateFormat.ShortDate)
        Dim EndDate As Date = FormatDateTime(Now(), DateFormat.ShortDate)

        CMD.Parameters.Add("@StartDate", SqlDbType.Date).Value = StartDate
        CMD.Parameters.Add("@EndDate", SqlDbType.Date).Value = EndDate
        Console.WriteLine("Getting Sales Data From " & StartDate & " To " & EndDate)
        Dim DT As DataTable = ExecuteCMD(CMD)

        Dim fileTest As String = "C:\Temp\TestPivot.xlsx"
        If File.Exists(fileTest) Then
            File.Delete(fileTest) ' oh, file is still open
        End If

        Dim oXLwb As New XLWorkbook()

        Console.WriteLine("Writing Data to Spreadsheet")


        Dim xlPtSheet = oXLwb.Worksheets.Add("AllStoreSales")
        Dim xlSheet = oXLwb.Worksheets.Add(DT, "RawData")

        Dim xlRange = xlSheet.RangeUsed()
        Dim xlHeader = xlSheet.Range(1, 1, 1, DT.Columns.Count)
        Dim xlDatarange = xlSheet.Range(xlHeader.FirstCell(), xlRange.LastCell())


        Console.WriteLine("Generating AllStoreSales Pivot Table")

        Dim pt = xlPtSheet.PivotTables.AddNew("AllStoreSales", xlPtSheet.Cell(3, 1), xlDatarange)

        pt.RowLabels.Add("SalesMonth")
        pt.RowLabels.Add("Department")
        pt.RowLabels.Add("Stores")

        pt.Values.Add("TYNetSales")
        pt.Values.Add("LYNetSales")

        Console.WriteLine("Saving Spreadsheet to " & fileTest)
        oXLwb.SaveAs(fileTest)
End Sub
Trying to see if another pair of eyes can spot what I am doing wrong or if this is a bug with the ClosedXML version I am using

Commented Unassigned: ClosedXML does not preserve style [9454]

$
0
0
So this is my code

```
using (var document = new XLWorkbook(root + outFolder + copied))
{
var sheet = document.Worksheets.First();
var allRows = sheet.Rows();
foreach (var currentRow in allRows)
{
var allCells = currentRow.Cells();
foreach (var cell in allCells)
{
var cVal = cell.Value.ToString();
if (dict.ContainsKey(cVal))
{
cell.Value = dict[cVal];
}
}
}
document.SaveAs(root + outFolder + copied);
}
```

This is how the Excel file looked before editing with ClosedXML: http://i.imgur.com/jjBWsUJ.png

This is how it looks after: http://i.imgur.com/qH8DrhO.png

As you can see, there are a bunch of styles it isn't saving. OpenXML does not do this.
Comments: Can you upload both the correct and incorrect versions of the Excel files?

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: So the issue was that the pivot cache wasn't deleted when a sheet was deleted. Fixed in PR: https://closedxml.codeplex.com/SourceControl/network/forks/igitur/ClosedXML/contribution/8516

Commented Unassigned: XLWorkbook_Load does not load NamedRanges in specific sheets [9446]

$
0
0
When loading an existing workbook that contains named ranges, ranges are only applied at the Workbook level even if the range is for a specific Worksheet. The crux of the problem is the "LoadDefinedNames" function in [XLWorkbook_Load.cs](https://closedxml.codeplex.com/SourceControl/latest#ClosedXML/ClosedXML/ClosedXML/Excel/XLWorkbook_Load.cs) only assigns named ranges to a specific worksheet if it's a Print_Area name or has a "[LocalSheetId](https://msdn.microsoft.com/en-us/library/documentformat.openxml.spreadsheet.definedname.localsheetid(v=office.14).aspx)" attribute. However, if it specifies the sheet using the typical reference syntax (e.g., Sheet1!$A$1), it adds it to the Workbook's NamedRanges collection and not the Worksheets' NamedRanges collection.

A possible fix is to add this at line 733:

```csharp
string sheetName, sheetArea;
ParseReference(text, out sheetName, out sheetArea);
if (Worksheet(sheetName) != null)
{
if (!Worksheet(sheetName).NamedRanges.Any(nr => nr.Name == name))
Worksheet(sheetName).NamedRanges.Add(name, text, comment);
}
else
{
if (!NamedRanges.Any(nr => nr.Name == name))
NamedRanges.Add(name, text, comment);
}
```

This uses the same "parsing" logic that the Print_Area reference uses. TBD is whether to add the full "text" of the reference to Worksheet(sheetName).NamedRanges or whether to add the "sheetArea" similar to what is done in "Print_Area".

If this is a reasonable solution, I can submit a PR.
Comments: I think the current implementation is correct. The defined name should be in the Worksheet scope only if LocalSheetId is declared. I'm not 100% sure though. Do you have a sample Excel file to show exactly what you mean?

Commented Unassigned: Date value as text in excel file [9444]

$
0
0
I am trying to set a text value to one of my columns.
Text value is 2015/06/03 15:15

Below is the code, that I use to set this column

excelWorkSheet.Cell(j + 1, k).SetDataType(XLCellValues.Text);
excelWorkSheet.Cell(j + 1, k)
.Style.NumberFormat.SetNumberFormatId(0);
excelWorkSheet.Cell(j + 1, k).Value = cellValue;

This is converting my string as a number.

How could I show this value as a text(Not as date time or a number)
Comments: Just out of curiosity, why not set it as a normal date with a custom date format to suit your needs?

Commented Unassigned: Worksheet.PivotTables is always empty [9378]

$
0
0
My .xlsx file contains a Pivot Table. But I can't get access to it via `Worksheet.PivotTables` property.

This is my sample code:

```
using (var excel = new XLWorkbook(sourceFile, XLEventTracking.Enabled))
{
var pivots = excel.Worksheets.SelectMany(ws => ws.PivotTables).ToList();
// pivots.Count == 0
}

```
The version of the ClosedXML library is 0.75.0 (got from NuGet)

The example of .xml file is attached.


Comments: Also realised this today. There is currently no code to load existing pivot tables. It's also not a simple job to load it, but I'm going to give it a shot sometime.

Created Unassigned: After inserting a row in a table, the files grows very big [9461]

$
0
0
I have an excel file that has a table with range A:K and has few rows say 100. So the cells with A1..K100 has values. But the same sheet has values at some random cells like Q6000. The file was of 47KB. Now I do

```
var excelTable = wb.Worksheets.First().Tables.FirstOrDefault(t => string.Equals("Table", t.Name, StringComparison.Ordinal));
var row = excelTable.DataRange.InsertRowsBelow(1).First();
```
The excel file after the insertion grew to 270KB. When checked, I saw new cells added all through A101..Q6001 in the sheet.xml which is incorrect. Also, when we insert one row, all the cells below the new row gets pushed down by one row. Here only the cell columns that are part of table are considered which is incorrect. It should consider the MaxColumnUsed.

There are two issues
1. XLRangeAddress.InsertRowsAboveInternal() should not add new cells for old cells that are not present in the internal worksheet.
2. XLRangeAddress.InsertRowsAboveInternal() should use MaxColumnUsed when it is pushing the cell values down by number of rows being inserted.

The issue 1 is affecting the performance because saving big files to stream takes lot of time.
The issue 2 causes inconsistency after insertion
Viewing all 1877 articles
Browse latest View live


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