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

New Comment on "Column Width and Styles"

$
0
0
How do you adjust the content to width of a cell?

Reviewed: ClosedXML 0.76.0 (Jun 11, 2015)

$
0
0
Rated 5 Stars (out of 5) - This is great work. I can now honestly say that I have built a spreadsheet using OpenXML - and I will follow that statement with the words, "Never again!". The documentation is clear, and the functionality is great. Thanks.

New Post: XLWorkbook.Save causes spreadsheet to lose data

$
0
0
I have a similar, yet simpler issue.
I have an existing .xlsx file, setup up with a page-break view. When the spreadsheet is opened and saved, the page-break view is stripped.
The problem is, that the value is never loaded into memory from the original document.
Example:
Original document:
<worksheet .....>
<dimension ..../>
<sheetViews>
    <sheetView tabSelected="1" __view="pageBreakPreview"__ zoomScaleNormal="100" zoomScaleSheetLayoutView="100" workbookViewId="0">
...
...

Calling the following, very simple code on the file, will strip the view-attribute of the OpenXml-file:
    public void OpenCloseWorkbook(string fileName, string sheetName)
    {
        var workbook = new XLWorkbook(fileName);
        workbook.Save();
    }
...
<sheetView tabSelected="1" zoomScaleNormal="100" zoomScaleSheetLayoutView="100" workbookViewId="0">
...


Its a bit annoying that a simple open/close operation modifies the file, but the workaround in my case was simple. I always want a specific value, not nessesarily the one defined in the original document. Therefore I just set it before saving, like this:
workbook.Worksheets.First().SheetView.View = XLSheetViewOptions.PageBreakPreview;

New Post: open excel in only read mode

$
0
0
how can i open an excel in only read mode ?
i want to protected so no one can copy it or extract date from it!

thanks

New Post: worksheet to an image

$
0
0
is the away to create a workseet to an image
for view only purposes ?

Created Unassigned: How to delete the default tablestyle and autofilter in Closed XML [9445]

$
0
0
Hii,

I'm creating '.xlsx' file using ClosedXML. The code which i used is given below:
Here dsreport is a Dataset having multiple sheets.



using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dsreport);
wb.Worksheets.Worksheet(i).Row(1).InsertRowsAbove(5);

wb.Worksheets.Worksheet(i).Cell("A1").Value = "ABC Company";
wb.Worksheets.Worksheet(i).Range("A1:J1").Row(1).Merge();
wb.Worksheets.Worksheet(i).FirstRow().Style.Font.Bold = true;
wb.Worksheets.Worksheet(i).FirstRow().Style.Font.SetFontSize(16); wb.Worksheets.Worksheet(i).FirstRow().Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
wb.Worksheets.Worksheet(i).FirstRow().Style.Alignment.WrapText = true;

wb.Worksheets.Worksheet(i).Cell("A2").Value = "Employee Information"
wb.Worksheets.Worksheet(i).Range("A2:J2").Row(1).Merge();
wb.Worksheets.Worksheet(i).Row(2).Style.Font.Bold = true;
wb.Worksheets.Worksheet(i).Row(2).Style.Font.SetFontSize(16); wb.Worksheets.Worksheet(i).Row(2).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
wb.Worksheets.Worksheet(i).Row(2).Style.Alignment.WrapText = true;

wb.Worksheets.Worksheet(i).Cell("A3").Value = "2015-2014";
wb.Worksheets.Worksheet(i).Range("A3:J3").Row(1).Merge();
wb.Worksheets.Worksheet(i).Row(3).Style.Font.Bold = true;
wb.Worksheets.Worksheet(i).Row(3).Style.Font.Italic = true;
wb.Worksheets.Worksheet(i).Row(3).Style.Font.SetFontSize(12); wb.Worksheets.Worksheet(i).Row(3).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);
wb.Worksheets.Worksheet(i).Row(3).Style.Alignment.WrapText = true;

wb.Worksheets.Worksheet(i).Row(6).Delete();
wb.Worksheets.Worksheet(i).Tables.Table(0).AutoFilter.Clear(); wb.Worksheets.Worksheet(i).Tables.Table(0).Style.Fill.SetPatternType(XLFillPatternValues.None);
//wb.Worksheets.Worksheet(i).Range("A4:A5").Column(1).Merge();
wb.Worksheets.Worksheet(i).Row(4).Style.Font.Bold = true;
wb.Worksheets.Worksheet(i).Row(4).Style.Font.SetFontSize(12); wb.Worksheets.Worksheet(i).Row(4).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center); }
wb.SaveAs(FilePath);
}


After Excecuting this code I'm getting a Default Autofilter and Default TableStyles.

How can I eliminate these property

New Post: Cell(1).Value throws exception - cell with formula

$
0
0
When I reading cell(with formula) using .value() , it throws an exception. So i used .valueCached. But when using valueCached it returns null . Below is ma code
var array = new object[colCont];
for (int y = 1; y <= colCont; y++)
{
      try
       {
                if (item.Cell(y).FormulaA1 == "")
                      array[y - 1] = item.Cell(y).Value;
                 else
                       array[y - 1] = item.Cell(y).ValueCached;
        }
        catch
         {
         }
 }        
Please advise.

New Post: Issue with Pivot Tables

$
0
0
I am unable to create a Pivot table with ReportFilters. Once I add a report filter, I get an error trying to open the excel file. To reproduce, I used the Pivot example from the site. The only change I made was changing "Month" from a column to a report filter. The code is below:
Can you tell me if I am doing anything wrong?
      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")
        };


        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);

        // 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.ReportFilters.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");


        workbook.SaveAs("c:\\temp\\PastrySample.xlsx");

Reviewed: ClosedXML 0.76.0 (Jun 24, 2015)

$
0
0
Rated 5 Stars (out of 5) - If I could give 6 stars I would, this is fantrastic.

New Comment on "Adding an AutoFilter to a Range"

$
0
0
I'm getting the same NullReferenceException, any solution for this?

New Post: Disable AutoFilter in Table

$
0
0
st21chris wrote:
Option 1 did get rid of the autofilter, but it also removed the theme, which I would like to keep. Option 2 didn't do anything. Immediately after inserting the table, I evaluated the ws.AutoFilterRange property and it was already null.   So, I started poking around a little and found the solution that worked for me: var table = sheet.Cell(1, 1).InsertTable(dataTable); table.ShowAutoFilter = false;   Next time, I'll stop being lazy and look around a bit more before posting a question. :)  
Thanks for this, it worked great for me, I've been hours trying to get rid of the AutoFilter

Commented Unassigned: Using SUMIF results in a "Syntax error." exception [9442]

$
0
0
Using

```
SUMIF(A1:A10,">0")
```

results in a "Syntax error." exception.


Code ends up in the ParseAtom() method with the _token.Type of TKTYPE.COMPARE, which is unsupported at that moment.
Comments: This only happens if the cell in A1:A10 range is an empty string ValueSatisfiesCriteria tries to evaluate the expression of value > 0, value being empty it builds an unsupported expression and the whole thing fails with Syntax error.

Commented Unassigned: Using SUMIF results in a "Syntax error." exception [9442]

$
0
0
Using

```
SUMIF(A1:A10,">0")
```

results in a "Syntax error." exception.


Code ends up in the ParseAtom() method with the _token.Type of TKTYPE.COMPARE, which is unsupported at that moment.
Comments: The fix is to just replace the value with 0 if it's blank in the built expression. MathTrig.cs line 258

New Post: Disable AutoFilter in Table

New Post: ASMBA


Reviewed: ClosedXML 0.76.0 (Jun 30, 2015)

$
0
0
Rated 5 Stars (out of 5) - This is a truly fantastic product! It capitalizes on all the extensions from OpenXML and provides simple but powerful methods to build and consume all types of Excel products. Also this is a remarkably fast product reading and writing a very detail oriented Excel workbook. Thanks for developing this!

Reviewed: ClosedXML 0.76.0 (Jul 02, 2015)

$
0
0
Rated 5 Stars (out of 5) - This is a miracle. We needed to allow clients to upload Excel Workbooks to SharePoint Document Libraries. From there, we used SharePoint Event Receivers to upload the Workbook to SQL Server Database. We could not use the Excel Object Model because Office was not installed on the Server. OpenXML 2.0 and the ClosedXML source code saved the day.

Created 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:

```
string sheetName, sheetArea;
ParseReference(text, out sheetName, out sheetArea);
if (Worksheet(sheetName) != null &&
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.

Edited 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.

Created Unassigned: .SaveAs(MemoryStream ms) does not progress when saving two .xlsm files (each about 7MB) at the same time [9447]

$
0
0
Hi, I wonder if anyone has any idea about the issue stated in the title.
To reproduce the issue, I created a console project and below is the code in my Program.cs file:
```
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ClosedXML.Excel;

namespace TestSavingTwoBigFiles
{
public class Program
{
private static string folderPath = @"C:\FOLDERPATH\";
private static string fileName1 = folderPath + "FILENAME1.xlsm";
private static string fileName2 = folderPath + "FILENAME2.xlsm";

public static void StartThread1()
{
Console.WriteLine("Creating first file...");
var wb = new XLWorkbook(fileName1, XLEventTracking.Disabled);
try
{
using (wb)
{
using (var ms = new MemoryStream())
{
Console.WriteLine("Saving first file...");
wb.SaveAs(ms);
}
}
Console.WriteLine("First file saved successfully");
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadLine();
}
}

public static void StartThread2()
{
Console.WriteLine("Creating second file...");
var wb = new XLWorkbook(fileName2, XLEventTracking.Disabled);
try
{
using (wb)
{
using (var ms = new MemoryStream())
{
Console.WriteLine("Saving second file...");
wb.SaveAs(ms);
}
}
Console.WriteLine("Second file saved successfully");
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadLine();
}
}

public static void Main(string[] args)
{
var thread1Start = new ThreadStart(StartThread1);
var thread1 = new Thread(thread1Start);
Console.WriteLine("Starting first thread");
thread1.Start();

var thread2Start = new ThreadStart(StartThread2);
var thread2 = new Thread(thread2Start);
Console.WriteLine("Starting second thread");
thread2.Start();
}
}
}
```
When I run the above program with two .xlsm files, one is ~2MB and the other one is ~7MB, the program completes successfully. However, when I run it with two ~7MB files, the program will be stuck at the saving statements and does not progress without throwing an exception. The console will stay as the attached image shows and does not change.

One workaround we used was placing a lock on the SaveAs method. Is there a better way?

Thanks!
Viewing all 1877 articles
Browse latest View live


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