Spire.XLS is a professional Excel API that enables developers to create, manage, manipulate, convert and print Excel worksheets. Get free and professional technical support for Spire.XLS for .NET, Java, Android, C++, Python.

Thu Oct 21, 2021 5:40 am

Each time I run the program (WPF) I want to open exisiting Excel file to delete and create sheets and pivot tables based on SQL database information.
Everything works fine, I empty the 2 sheets used as datasource and delete the sheet for pivot1 (pivot table 1) and create a new sheet with the same name and create a new pivot table based on
the datasource sheet (2 datasource sheet for 3 pivot tables, 2 of them share one datasource).

Problem
After that I try to do the same process for pivot table 2, deleting pivot2 sheet and recreate. Code executes until the end (delete and create) but after i try to save the file I get The entry pivotCacheDefinition2.xml already exists in the zip and the file becomes corrupted.
After more testing I found out that even if I only remove/delete the sheet pivot2 and save the file (excluding the creation process from the execution) it gives me the same error. So I can only delete and create 1 pivot table. How to solve this?


Main file code
Code: Select all
excel_manager em = new excel_manager();
                    //excel_editor ee = new excel_editor();


                    em.loadExcelFile("C:\\test\\situatie_pivoti_27.07 - 07.00.xlsx");
                    em.setDebugMode(true);

                    em.clearData("date");
                    em.clearData("date2");

                    em.addDateHeaders();

                   
                    em.fillData("date", ds.Tables["dataset1"]);

                   
                    em.fillData("date2", ds.Tables["dataset2"]);
               


                    em.removeSheet("pivot1", "PivotTable1");

                    em.create_pivot_table_one("date", "PivotTable1");

                    //problem here
                    em.removeSheet("pivot2", "PivotTable4");
                    em.close_and_save(); //Exception here



removeSheet Code
Code: Select all
public void removeSheet(String sheetName, String pivotTableName="")
        {
            try
            {
                if (sheetName.Contains("pivot"))
                {
                    sWB.Worksheets[sheetName].Clear();
                    sWB.Worksheets[sheetName].ClearData();
                    sWB.Worksheets[sheetName].PivotTables.Remove(pivotTableName);
                }

                sWB.Worksheets.Remove(sheetName);

            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: ", ex.ToString());
            }
        }


Save the file code
Code: Select all
public void close_and_save()
        {
            sWB.SaveToFile(fileName, ExcelVersion.Version2013);
        }



Create pivot table code
Code: Select all
 public void create_pivot_table_two(String DataSourceSheetName, String pivotTableName)
        {
            try
            {
                //Re-create worksheet pivot2
                Worksheet pivot2 = sWB.CreateEmptySheet();
                pivot2.Name = "pivot2";
                pivot2.AllocatedRange.AutoFitColumns();
                pivot2.AllocatedRange.AutoFitRows();

                changeSheet("pivot2");

                //Get Datasource "data"
                Worksheet datasource1 = sWB.Worksheets[DataSourceSheetName];
                CellRange dataRange = datasource1.Range[datasource1.FirstRow, datasource1.FirstColumn, datasource1.LastRow - 340, datasource1.LastColumn - 1];

                #region Debug_Code
                //var a = dataRange.CellList;
                //List<String> debug = new List<string>();

                //foreach (var index in a)
                //{
                //    debug.Add(index.DisplayedText);
                //}
                #endregion

                //Create Pivot Table 2
                //PivotCache cache = this.cache1;
                PivotCache cache = sWB.PivotCaches.Add(dataRange);
                PivotTable pt2 = pivot2.PivotTables.Add(pivotTableName, dataRange, cache);
               

                #region PivotTable2 Proprieties
                pt2.BuiltInStyle = PivotBuiltInStyles.PivotStyleDark3;
                pt2.ShowRowStripes = true;

                pt2.ShowColumnGrand = false;
                pt2.ShowRowGrand = false;
                pt2.Options.MergeLabels = true;
                #endregion

                #region PivotTable2 Row and Column Field Proprieties
                //creating the rows 
                PivotField r1 = pt2.PivotFields["nume"] as PivotField;
                r1.Axis = AxisTypes.Row;
                pt2.Options.RowHeaderCaption = "Row Labels";

                PivotField r2 = pt2.PivotFields["numar"] as PivotField;
                r2.Axis = AxisTypes.Row;

                PivotField r3 = pt2.PivotFields["dela-panala"] as PivotField;
                r3.Axis = AxisTypes.Row;




                //creating the columns with dates
                PivotField c = pt2.PivotFields["dt"] as PivotField;
                c.Axis = AxisTypes.Column;
                c.NumberFormat = "dd-mmm";
                c.SortType = PivotFieldSortType.Ascending;


                pt2.DataFields.Add(pt2.PivotFields["ocupate"], "efectuate", SubtotalTypes.Sum);
                pt2.DataFields.Add(pt2.PivotFields["total"], "maxim", SubtotalTypes.Sum);

                #endregion


                pivot2.SetRowHeight(1, 20);
                pivot2.SetColumnWidth(1, 60);

                //cache.Dispose();
            }catch (Exception ex)
            {
            }
           
        }


excel_manager Full Class
Code: Select all
class excel_manager
    {
        Workbook sWB;
        Worksheet active_sheet;
        PivotCache cache1;

        String filePath;
        String fileName;
        String[] date_headers = new string[] {"nume","numar", "total",
                                 "ocupate", "dt", "dela-panala"};

        String[] date2_headers = new string[] { "nume", "dt", "libere", "total" };

        int sheetNumber;

        public excel_manager()
        {
            sWB = new Workbook();
            filePath = "";
            fileName = "";
            sheetNumber = 0;
            cache1 = null;
        }

        public void loadExcelFile(String path)
        {

            if (File.Exists(path))
            {
                try
                {
                    this.filePath = path;
                    sWB.LoadFromFile(filePath);
                    sWB.IsHideWindow = true;

                    fileName = sWB.FileName;
                    sheetNumber = sWB.Worksheets.Count;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception: ", ex.ToString());
                }
               
            }
            else
            {
                Console.WriteLine("File does not exist");
            }
        }

        public void setDebugMode(bool status)
        {
            sWB.IsHideWindow = !(status);
        }

        public void changeSheet(int index)
        {
            if (index > 0 && index <= sheetNumber)
            {
                try
                {
                    active_sheet = sWB.Worksheets[index];
                    active_sheet.Activate();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception: ", ex.ToString());
                }
            }
            else
            {
                Console.WriteLine("Invalid Inex for Sheet!");
            }
           
           
        }

        public void changeSheet(String sheetName)
        {
            try
            {
                active_sheet = sWB.Worksheets[sheetName];
                active_sheet.Activate();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: ", ex.ToString());
            }

        }

        internal void clearData(string sheetName)
        {
            CellRange cr = sWB.Worksheets[sheetName].AllocatedRange;
           
            //Clear all objects
            cr.ClearAll();
        }

        public void removeSheet(String sheetName, String pivotTableName="")
        {
            try
            {
                if (sheetName.Contains("pivot"))
                {
                    sWB.Worksheets[sheetName].Clear();
                    sWB.Worksheets[sheetName].ClearData();
                    sWB.Worksheets[sheetName].PivotTables.Remove(pivotTableName);
                }

                sWB.Worksheets.Remove(sheetName);

            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: ", ex.ToString());
            }
        }

        public void removeSheet(int index)
        {
            if (index > 0 && index <= sheetNumber)
            {
                try
                {
                    sWB.Worksheets.Remove(index);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception: ", ex.ToString());
                }
            }
            else
            {
                Console.WriteLine("Invalid Inex for Sheet!");
            }
        }

        public void addSheet(String sheetName)
        {
            sWB.Worksheets.Add(sheetName);
        }

        public void close_and_save()
        {
            sWB.SaveToFile(fileName, ExcelVersion.Version2013);
        }

        internal void addDateHeaders()
        {
            changeSheet("date");

            CellRange range1 = active_sheet.Range[active_sheet.FirstRow, active_sheet.FirstColumn, active_sheet.FirstRow, date_headers.Length];

            int c1 = 0;
            foreach (var i in range1)
            {
                i.Text = date_headers[c1];
                i.Style.Font.IsBold = true;
                c1++;
            }


            changeSheet("date2");

            CellRange range2 = active_sheet.Range[active_sheet.FirstRow, active_sheet.FirstColumn, active_sheet.FirstRow, date2_headers.Length];

            int c2 = 0;
            foreach (var i in range2)
            {
                i.Text = date2_headers[c2];
                i.Style.Font.IsBold = true;
                c2++;
            }
        }

        public void fillData(String sheetName, DataTable Data)
        {
            changeSheet(sheetName);
            active_sheet.InsertDataTable(Data, true, 1, 1);
        }

        public void create_pivot_table_one(String DataSourceSheetName, String pivotTableName)
        {
            try
            {
                //Re-create worksheet pivot1
                Worksheet pivot1 = sWB.CreateEmptySheet();
                pivot1.Name = "pivot1";
                pivot1.AllocatedRange.AutoFitColumns();
                pivot1.AllocatedRange.AutoFitRows();

                //Get Datasource "data"
                Worksheet datasource1 = sWB.Worksheets[DataSourceSheetName];
                CellRange dataRange = datasource1.Range[datasource1.FirstRow, datasource1.FirstColumn, datasource1.LastRow - 340, datasource1.LastColumn - 1];

                #region Debug_Code
                //var a = dataRange.CellList;
                //List<String> debug = new List<string>();

                //foreach (var index in a)
                //{
                //    debug.Add(index.DisplayedText);
                //}
                #endregion

                //Create Pivot Table 1
                PivotCache cache = sWB.PivotCaches.Add(dataRange);

                cache1 = cache;
                PivotTable pt1 = pivot1.PivotTables.Add(pivotTableName, dataRange, cache);

                #region PivotTable1 Proprieties
                pt1.BuiltInStyle = PivotBuiltInStyles.PivotStyleDark4;
                pt1.ShowColumnGrand = false;
                pt1.ShowRowGrand = false;
                pt1.ShowRowStripes = true;
                pt1.Options.MergeLabels = true;
                #endregion

                #region PivotTable1 Row and Column Field Proprieties
                //creating the rows 
                PivotField r1 = pt1.PivotFields["nume"] as PivotField;
                r1.Axis = AxisTypes.Row;
                pt1.Options.RowHeaderCaption = "Row Labels";




                //creating the columns with dates
                PivotField c = pt1.PivotFields["dt"] as PivotField;
                c.Axis = AxisTypes.Column;
                c.NumberFormat = "dd-mmm";
                c.SortType = PivotFieldSortType.Ascending;


                pt1.DataFields.Add(pt1.PivotFields["numar"], "numar_gh", SubtotalTypes.Count); //this won't work
                pt1.DataFields.Add(pt1.PivotFields["total"], "maxim", SubtotalTypes.Sum);
                pt1.DataFields.Add(pt1.PivotFields["ocupate"], "efectuate", SubtotalTypes.Sum);
                #endregion


                pivot1.SetRowHeight(1, 20);
                pivot1.SetColumnWidth(1, 60);

                //cache.Dispose();
            }
            catch (Exception ex)
            {

            }
        }

        public void create_pivot_table_two(String DataSourceSheetName, String pivotTableName)
        {
            try
            {
                //Re-create worksheet pivot2
                Worksheet pivot2 = sWB.CreateEmptySheet();
                pivot2.Name = "pivot2";
                pivot2.AllocatedRange.AutoFitColumns();
                pivot2.AllocatedRange.AutoFitRows();

                changeSheet("pivot2");

                //Get Datasource "data"
                Worksheet datasource1 = sWB.Worksheets[DataSourceSheetName];
                CellRange dataRange = datasource1.Range[datasource1.FirstRow, datasource1.FirstColumn, datasource1.LastRow - 340, datasource1.LastColumn - 1];

                #region Debug_Code
                //var a = dataRange.CellList;
                //List<String> debug = new List<string>();

                //foreach (var index in a)
                //{
                //    debug.Add(index.DisplayedText);
                //}
                #endregion

                //Create Pivot Table 2
                //PivotCache cache = this.cache1;
                PivotCache cache = sWB.PivotCaches.Add(dataRange);
                PivotTable pt2 = pivot2.PivotTables.Add(pivotTableName, dataRange, cache);
               

                #region PivotTable2 Proprieties
                pt2.BuiltInStyle = PivotBuiltInStyles.PivotStyleDark3;
                pt2.ShowRowStripes = true;

                pt2.ShowColumnGrand = false;
                pt2.ShowRowGrand = false;
                pt2.Options.MergeLabels = true;
                #endregion

                #region PivotTable2 Row and Column Field Proprieties
                //creating the rows 
                PivotField r1 = pt2.PivotFields["nume"] as PivotField;
                r1.Axis = AxisTypes.Row;
                pt2.Options.RowHeaderCaption = "Row Labels";

                PivotField r2 = pt2.PivotFields["numar"] as PivotField;
                r2.Axis = AxisTypes.Row;

                PivotField r3 = pt2.PivotFields["dela-panala"] as PivotField;
                r3.Axis = AxisTypes.Row;




                //creating the columns with dates
                PivotField c = pt2.PivotFields["dt"] as PivotField;
                c.Axis = AxisTypes.Column;
                c.NumberFormat = "dd-mmm";
                c.SortType = PivotFieldSortType.Ascending;


                pt2.DataFields.Add(pt2.PivotFields["ocupate"], "efectuate", SubtotalTypes.Sum);
                pt2.DataFields.Add(pt2.PivotFields["total"], "maxim", SubtotalTypes.Sum);

                #endregion


                pivot2.SetRowHeight(1, 20);
                pivot2.SetColumnWidth(1, 60);

                //cache.Dispose();
            }catch (Exception ex)
            {
            }
           
        }

        public void update_pivot_table_one()
        {
            XlsPivotTable pt = sWB.Worksheets["pivot1"].PivotTables[0] as XlsPivotTable;
            pt.Cache.IsRefreshOnLoad = true;
        }
    }

rares.deoanca21
 
Posts: 7
Joined: Wed Oct 20, 2021 11:31 am

Thu Oct 21, 2021 9:15 am

Hello Rares,

Thanks for your inquiry.
In your code, both the create_pivot_table_one and the create_pivot_table_two methods include creating new worksheet named pivot1 or pivot2, so please directly use sWB.Worksheets.Remove(sheetName) to remove any worksheet without judging "pivot".
removeSheet Code
Code: Select all
    public void removeSheet(String sheetName, String pivotTableName="")
            {
                try
                {
                    // if (sheetName.Contains("pivot"))
                    //{
                    //   sWB.Worksheets[sheetName].Clear();
                    //   sWB.Worksheets[sheetName].ClearData();
                    //    sWB.Worksheets[sheetName].PivotTables.Remove(pivotTableName);
                    // }

                    sWB.Worksheets.Remove(sheetName);

                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception: ", ex.ToString());
                }
            }


I used Spire.XLS Pack(Hotfix) Version:11.9.3 to do a test. For pivot table 2, deleting pivot2 sheet and recreate , there is no issue. Here is my full test WPF project, https://www.e-iceblue.com/downloads/attachment/CreateExcel(27238).zip.

Sincerely,
Amy
E-iceblue support team
User avatar

amy.zhao
 
Posts: 2766
Joined: Wed Jun 27, 2012 8:50 am

Thu Oct 21, 2021 10:03 am

I modified the removeSheet function as specified and updated the Nuget package to Spire.XLS v11.9.3 Issue is still going after i use remove and/or create_pivot_table2

Pictures (seems I can't post images or url add "h"):
ttps://imgur.com/pGRMrCt - modified function

ttps://imgur.com/9lIb6Jt - debug 1

ttps://imgur.com/0Z7aNNB - debug 2

ttps://imgur.com/CgQQFsX - debug 3


I will download your demo and try to integrate it in mine if it works i will post here, thanks amy.

rares.deoanca21
 
Posts: 7
Joined: Wed Oct 20, 2021 11:31 am

Thu Oct 21, 2021 10:26 am

Update
Ok Amy, i ran your Excel file trough my program and your variant of program and it works. Going to the conclusion that it might just be the excel file that triggers the exception or is something specific to that excel file but I can't figure out exactly what it is. When i open yours with 7zip archive your excel file contains 2 pivotcachedefitions (1 and 2) mine (my excel file) has only pivotcachedefition2.xls (after code execution and corrpution) and the exception says that this entry already exists in the zip archive and it gets corrputed after code execution.

rares.deoanca21
 
Posts: 7
Joined: Wed Oct 20, 2021 11:31 am

Fri Oct 22, 2021 6:22 am

Dear Rares,

Thanks for your feedback.
To help me investigate your issue, please share your input excel file.

Thank you for your assistance in advance.

Sincerely,
Amy
E-iceblue support team
User avatar

amy.zhao
 
Posts: 2766
Joined: Wed Jun 27, 2012 8:50 am

Fri Nov 19, 2021 10:54 am

I solved the issue by replacing the template file that i use with your file. I think it was something wrong with it.
I could not share the file since it contains sensitive information, only if i'm allowed I will.
Thank you for your assistance :) .

rares.deoanca21
 
Posts: 7
Joined: Wed Oct 20, 2021 11:31 am

Mon Nov 22, 2021 2:05 am

Dear Rares,

Thanks for your feedback. Glad to hear that you have managed to solve it.
Feel free to contact us if you have any questions.

Sincerely,
Amy
E-iceblue support team
User avatar

amy.zhao
 
Posts: 2766
Joined: Wed Jun 27, 2012 8:50 am

Return to Spire.XLS

cron