Refresh PivotTable EPPlus - c#

I am editing an existing spreadsheet in C# using EPPlus. I am altering the raw data on the second worksheet which is being used as the data source for a Pivot table on the first worksheet. My edits all work perfectly, the problem I am having is that when I load the spreadsheet output I have to manually update the Pivot table by clicking the Refresh Data button on the Excel toolbar.
Is there anyway to do this with C# EPPlus?
I've tried:
package.Workbook.FullCalcOnLoad = true;
and
package.Workbook.Calculate();
without success.
UPDATE
I couldn't find a mechanism for doing this in EPPlus so would still like to know if there is an answer. However, because I am editing a pre-existing Excel file, I was able to edit the properties of the existing pivot table in Excel and change the setting to automatically update on first load.

I couldn't find a way to achieve this using EPPlus.
However, you can enable the "Refresh the data when opening the file" property on the PivotTable manually before modifying the file, so that when you open the file using Excel, the content of the PivotTable will be calculated based on the modified data. You can find this property under the Data tab in the PivotTable options.

A bit late I know, but thought I'd post in case anybody else is looking for the same solution. You can do this in EPPlus by directly amending the XML for the pivot tables cache definition.
pivotTable.CacheDefinition.CacheDefinitionXml.DocumentElement?.SetAttribute(
"refreshOnLoad", 1.ToString());
Using EPPlus version 4.5.3.3.

Pivot tables have it's own calc context in Excel file. You manipulate calculation of formulas with FullCalcOnLoad property and Calculate() method
I bet this code from here will help you.
foreach (Worksheet sheet in package.Workbook.Sheets)
{
foreach (PivotTable pivotTable in sheet.PivotTables())
{
pivotTable.PivotCache().Refresh(); //could be some other method, but i hope you find right one
}
}

Add this to ExcelPivotCacheDefinition.cs
public bool RefreshOnLoad
{
get
{
return GetXmlNodeString("#refreshOnLoad") == "1";
}
set
{
SetXmlNodeString("#refreshOnLoad", value?"1":"0");
}
}

Go to Pivot Table options and check 'Refresh data when opening the file': https://www.extendoffice.com/documents/excel/1859-excel-refresh-pivot-table-on-open.html.
(Optional) If desired, users can disable 'Protected View' inside of their Excel installation: http://www.corporatefocus.com/support/how-to-disable-protected-view-in-microsoft-excel#:~:text=In%20Excel%20go%20to%20File,Enable%20All%20Macros%20by%20default.

Related

Gembox Spreadsheet - Remove blank pages

I dont know how achieve this, I have to create an informative report with images. For this, I use an excell template (It helps me with the format and with the position of the text where to place the respective information). The images are generated perfectly. I convert this XLS to PDF with the property
DocumentToMemoryStream (excelTemplate, XlsxSaveOptions.XlsxDefault);
This report generate blank pages in the PDF. How can I remove these blank pages, before the excel is generated?
Without checking your spreadsheet it's impossible to tell from where do those empty pages come from, so can you upload your XLS?
Anyway, do you perhaps have some explicitly defined horizontal or vertical page breaks?
If yes, can you remove the ones you don't need?
Or, do you perhaps have empty columns at the end which have some kind of styling or formatting?
If yes, then you could try using something like this to remove those empty columns from exporting to PDF:
var workbook = ExcelFile.Load("input.xls");
var worksheet = workbook.Worksheets.ActiveWorksheet;
worksheet.NamedRanges.SetPrintArea(
worksheet.GetUsedCellRange(true));
var options = new PdfSaveOptions();
options.SelectionType = SelectionType.ActiveSheet;
workbook.Save("output.pdf", options);
I had a counter of the rows of the document I was writing on, thanks to the help of #Mario Z, I use this function, before the save and solve my problem of blank pages
wsimgs.NamedRanges.SetPrintArea(wsimgs.Cells.GetSubrange("A1",CellRange.RowColumnToPosition (countRow, 10)));

C# Excel Add in : Make worksheet read only but editable through code

I have created an Excel add-in in C#, In my add-in I have a form that retrieves data from web service and writes it to excel, I want to make the excel sheet read only, but I also want to edit it from behind the code.
What i want to do:
Basically I want to block user from accessing the worksheet, he can only make changes through the form that I have created.
I tried:
1- To add cell validation to forbid any changes to the cell but it still allows other operations on sheet such as delete rows columns etc.
2- To protect worksheet using a password like this.
var activeWorksheet = ((Excel.Worksheet)Globals.ThisAddIn.Application.ActiveSheet);
activeWorksheet.Protect("password");
But the above will not let me edit the worksheet through code, I have to unlock the worksheet whenever i want to make changes ie.
activeWorksheet.Unprotect("password");
// Do some changes.
activeWorksheet.Protect("password");
This way worksheet will stay unprotected while my Edit code is running (it may consume some time as there may be thousands or more records in sheet).
I can think of one way is to unlock invidual cells to edit them and lock them again, I tried the below code but its not working:
var cellToEdit = activeWorksheet.Range["A2"];
activeWorksheet.Protection.AllowEditRanges.Add("A1",cellToEdit , "password");
cellToEdit.value = "changed cell";
Please suggest me some solution.
This way worksheet will stay unprotected while my Edit code is running (it may consume some time as there may be thousands or more records in sheet).
If you display a modal form (e.g., progress dialog) during the update processing, the user will not be able to make edits while the sheet is unprotected.
I have tested writing a code than runs longer say 3 to 4 seconds and it seems that by default, excel doesnt allow worksheet to be edited while the code in still running.

OpenXML SDK: Is there a command to "refresh" the spreadsheet that was created?

I write applications that create PDF files and Excel files. While generating PDF files, I noticed that some of the features that were inserted in the file, did not show up visually. I was informed of a statement that "refreshes" the file and now all the features are visible.
I am having the exact same problem with Excel generation. I need one of my columns to self-adjust to the width of the widest entry (in the same fashion as double-click interactively). I was told about this solution:
"In OpenXML you can set the spreadsheet column properties so that it will be auto-sized when the spreadsheet is opened in Excel. Set BestFit=true and CustomWidth=true when creating the column."
How to implement the feature that adjusts an Excel column to the precise width, programmatically??
I added this statement to my source code:
Column column2 = new Column() { Min = (UInt32Value)2U, Max = (UInt32Value)2U, Width=7, BestFit = true, CustomWidth = true };
But the column is too narrow. I tried without the Width=7 but in that case the width is assumed to be zero an the column disappears altogether.
TIA
Short answer is no. Setting the BestFit and CustomWidth properties aren't enough. You still have to manually calculate the column width.
It's best to use a third-party library for this. Suggestions are EPPlus, ClosedXML and SpreadsheetLight. All of these free open source libraries provide the auto-fit feature. Disclosure: I wrote SpreadsheetLight.

Writing content in cells of excel using excel object is viewed in c#.net

I am going to write the content to the cells of an excel template using excel object in c#.net.
I have no problem in writing in the cells of the excel it works fine, but while writing the content in the cells of the excel, i can able to view the content writing in the cells.
But I need to restrict not view this action.
Can any one give me an idea about how to resolve this issue?
Please let me know if this is not clear.
If you are asking to hide screen updating, try:
xlApp.ScreenUpdating = false;
At the end, don't forget to turn it back on:
xlApp.ScreenUpdating = true;
Some of the answers to this question may help as well.

C# Winforms DataGridView with sorting/filtering like Ms Excel

Hi I need a quick solution to do filtering/sorting using the Winforms DataGridView control just as in Excel.
I have reviewed the existing posts on this area but none seems to meet my needs.
I am populating my DataGridView manually - no data binding
The DataGridView columns already support sorting.
I would populate a DataTable with your data and then bind the DataGridView to myDataTable.DefaultView.
You can filter the rows displayed by setting myDataTable.DefaultView.RowFilter.
You could place Textboxes and/or Comboboxes above the DataGridView and update myDataTable.DefaultView.RowFilter as the input/selections change.
If you're looking for a Excel like filtering funcionality, check out this article:
http://msdn.microsoft.com/en-us/library/aa480727.aspx
Why don't use a cheap 3rd-party component? Even if you buy it, eventually it could really save your money. This DataGridView alternative with autofilter works very fast, and unbound mode is its main work mode. Plus it supports Excel-style AutoFilter.
Do you want something like this?
DataGridView-AutoFilter is a ready-made Nuget package, you just need to download it and follow this article, it is an easy and enhanced approach.
Microsoft has created a sample project for VB and C# where they show how to create what they say is an "auto-filter" plugin. I personally do not like it as it allows filter exact only so product and customer will work, open invoice where price > some value is not implemented
Sorting is implemented by using:
foreach (DataGridViewColumn column in MyDataView.Columns)
{
column.SortMode = DataGridViewColumnSortMode.Automatic;
}
You do this when the grid has it's columns, if auto creating the columns… after binding.

Categories