How to set a List for data validations in column/columns of excel file using OpenXml in c#?

时光怂恿深爱的人放手 提交于 2019-12-23 15:03:33

问题


I need to create a dropdown using a particular list as source in column/columns of an excel file using openXml.

I use the following code for the purpose,

     SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open("C:\\Users\\Harun.TV\\Desktop\\OpenXml\\1.xlsx",true);

        WorkbookPart workbookpart = spreadSheetDocument.WorkbookPart;
        Workbook workbook=workbookpart.Workbook;


        WorksheetPart worksheetPart=workbookpart.WorksheetParts.First();            


        DataValidations dataValidations1 = new DataValidations();
        DataValidation dataValidation2 = new DataValidation() { Formula1 = new Formula1("'mySheet'!$A$1:$A$4"), Type = DataValidationValues.List, AllowBlank = true, ShowInputMessage = true, ShowErrorMessage = true, SequenceOfReferences = new ListValue<StringValue>() { InnerText = "A4:B4" } };
        Formula1 formula12 = new Formula1();
        formula12.Text = "$A$1:$A$3";
        dataValidations1.Append(dataValidation2);
        worksheetPart.Worksheet.Append(dataValidations1);

         workbookpart.Workbook.Save();


        spreadSheetDocument.Close();

And it throws throws an error while opening the excel. the log is as follows,

      <?xml version="1.0" encoding="UTF-8" standalone="true"?>
     -<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">     <logFileName>error055840_01.xml</logFileName>
      <summary>Errors were detected in file  'C:\Users\Harun.TV\Desktop\OpenXml\6.xlsx'</summary>
      -<removedParts summary="Following is a  list of removed parts:">     
       <removedPart>Replaced Part: /xl/worksheets/sheet3.xml part with XML error. Load error. Line 1, column 467.</removedPart></removedParts></recoveryLog>

Also how can i assign a list of comma separated values to DataValidations and attain the desired result as we do it manually for an excel column?


回答1:


The problem may be that there is already a "DataValidatoins" node. This works for me:

        DataValidation dataValidation = new DataValidation
        {
            Type = DataValidationValues.List,
            AllowBlank = true,
            SequenceOfReferences = new ListValue<StringValue>() { InnerText = "B1" },
            Formula1 = new Formula1("'SheetName'!$A$1:$A$3")
        };

        DataValidations dvs = worksheet.GetFirstChild<DataValidations>(); //worksheet type => Worksheet
        if (dvs != null)
        {
            dvs.Count = dvs.Count + 1;
            dvs.Append(dataValidation);
        }
        else
        {
            DataValidations newDVs = new DataValidations();
            newDVs.Append(dataValidation);
            newDVs.Count = 1;
            worksheet.Append(newDVs);
        }



回答2:


I know this post date from 2 years ago, BUT I got exactly the same problem and I found a solution.

When I tried to create a DataValidation in my excel file from C#, I got the same issue when opening it in Excel.

If you check your WorkSheet object, you will find several Child inside. When you do "worksheet.Append(...)" you just add another child.

In my case, I just figure out that the order of children is important ! (In fact, I was not create all the excel file, I was using an existing one to modify some stuff)

Here, the order of children

  1. SheetDimension
  2. SheetViews
  3. SheetFormatProperties
  4. Columns
  5. SheetData
  6. DataValidations
  7. PageMargins
  8. PageSetup

And there, how I reorder worksheet children

            //workseet property is a Worksheet object
            var pageMargins = worksheet.GetFirstChild<PageMargins>();
            pageMargins.Remove();

            var pageSetup = worksheet.GetFirstChild<PageSetup>();
            pageSetup.Remove();

            DataValidations newDataValidations = new DataValidations();

            DataValidation dataValidation = new DataValidation()
            {
                Type = DataValidationValues.List,
                AllowBlank = true,
                SequenceOfReferences = new ListValue<StringValue>() { InnerText = "B2:B4" },
                Formula1 = new Formula1("\"test,great test\""),
                ShowErrorMessage = true,
                ShowInputMessage = true,
            };

            newDataValidations.Append(dataValidation);
            newDataValidations.Count = 1;
            worksheet.Append(newDataValidations);
            worksheet.Append(pageMargins);
            worksheet.Append(pageSetup);

So be careful if the addition of your DataValidation it the last thing that you do...



来源:https://stackoverflow.com/questions/22808284/how-to-set-a-list-for-data-validations-in-column-columns-of-excel-file-using-ope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!