简体   繁体   中英

How to Create Dropdownlist in Excel using Openxml in C#

There are some sheets which is created from a XML file.

There are some names in 2nd sheet .excel is created by reading XML file and change it to data-set and later created worksheet and all other rows and columns with the help of OPEN-XML .

So I want to create a list using names from 2nd sheet and show the list in sheet 1 as drop-down.Using OPEN-XML I want to create a drop-downlist with data taken from 2nd page. I browse many time but i did not find any solution Is it possible to create dropdown using openxml.

This is my whole code for creating excel from xml file so if it have solution please help me.

 public void ExportDSToExcel(DataSet ds, string dest)
{
    try
    {
        using (var workbook = SpreadsheetDocument.Create(dest, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
        {
            var workbookPart = workbook.AddWorkbookPart();
            workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
            workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();

            uint sheetId = 1;

            foreach (DataTable table in ds.Tables)
            {
                var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
                var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
                sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);

                DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
                string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);

                if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
                {    
                    sheetId =
                        sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
                }

                DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet()
                {
                    Id = relationshipId, SheetId = sheetId, Name = table.TableName
                };
                sheets.Append(sheet);

               if(sheet.Name=="Customer")
               {                         
                   PageMargins pageM = sheetPart.Worksheet.GetFirstChild<PageMargins>();
                   SheetProtection sheetProtection = new SheetProtection();
                   sheetProtection.Password = "admin";
                   sheetProtection.Sheet = true;
                   sheetProtection.Objects = true;
                   sheetProtection.Scenarios = true;
                   ProtectedRanges pRanges = new ProtectedRanges();
                   ProtectedRange pRange = new ProtectedRange();
                   ListValue<StringValue> lValue = new ListValue<StringValue>();
                   lValue.InnerText = ""; //set cell which you want to make it editable
                   pRange.SequenceOfReferences = lValue;
                   pRange.Name = "not allow editing";
                   pRanges.Append(pRange);
                   sheetPart.Worksheet.InsertBefore(sheetProtection, pageM);
                   sheetPart.Worksheet.InsertBefore(pRanges, pageM);

                   if (cell.CellReference == "B4")
                   {
                       CellFormula cellformula = new CellFormula();
                       cellformula.Text = "=INDEX(Sheet5!B:B,MATCH(A4,Sheet5!B:B,0))";
                       CellValue cellValue = new CellValue();
                       cellValue.Text = "0";
                       cell.Append(cellformula);
                       cell.Append(cellValue);
                   }
               }
                DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();

                if (RadioButtonList1.SelectedItem.Text == "Yes")
                {
                    PageMargins pageM = sheetPart.Worksheet.GetFirstChild<PageMargins>();
                    SheetProtection sheetProtection = new SheetProtection();
                    sheetProtection.Password = "admin";
                    sheetProtection.Sheet = true;
                    sheetProtection.Objects = true;
                    sheetProtection.Scenarios = true;
                    ProtectedRanges pRanges = new ProtectedRanges();
                    ProtectedRange pRange = new ProtectedRange();
                    ListValue<StringValue> lValue = new ListValue<StringValue>();
                    lValue.InnerText = ""; //set cell which you want to make it editable
                    pRange.SequenceOfReferences = lValue;
                    pRange.Name = "not allow editing";
                    pRanges.Append(pRange);
                    sheetPart.Worksheet.InsertBefore(sheetProtection, pageM);
                    sheetPart.Worksheet.InsertBefore(pRanges, pageM);   
                }
                else
                {                    
                }
                List<String> columns = new List<string>();
                foreach (DataColumn column in table.Columns)
                {
                    columns.Add(column.ColumnName);

                    DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                    cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                    cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
                    headerRow.AppendChild(cell);
                }

                sheetData.AppendChild(headerRow);

                foreach (DataRow dsrow in table.Rows)
                {
                    DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
                    foreach (String col in columns)
                    {
                        DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
                        cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
                        cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
                        newRow.AppendChild(cell);                           
                    }

                    sheetData.AppendChild(newRow);
                }
            }
        }
    }
    catch
    {
        lblstatus.Text = "File Upload Not Succesfull ";
    }
    lblstatus.Text = "File Upload Succesfull ";
}
    protected void Button1_Click(object sender, EventArgs e)
    {
        if(txtname.Text != null)
        {
            if (FileUpload1.HasFile == true)
            {
        string myXMLfile = "/uploads/" + FileUpload1.FileName;
        FileUpload1.SaveAs(Server.MapPath(myXMLfile));
        string dest = "D:/uploads/" + txtname.Text+".xlsx";
        DataSet ds = new DataSet();
        try
        {    
            ds.ReadXml(Server.MapPath(myXMLfile));               
        }
        catch (Exception ex)
        {
            lblstatus.Text=(ex.ToString());
        }
            ExportDSToExcel(ds, dest);               
    }
            else
            {
               lblstatus.Text = "Please Upload the file ";
            }
        }
        else {    
            lblstatus.Text = "Please enter the name ";
        }            
    }
}

You need create a Validator

  • First Parameter is a worksheet where create a dropdown
  • Second parameter is worksheet to take data from

A1:A1048576 - is a cells to apply this Validator

public void CreateValidator(Worksheet ws, string dataContainingSheet)
        {
            /***  DATA VALIDATION CODE ***/
            DataValidations dataValidations = new DataValidations();
            DataValidation dataValidation = new DataValidation
            {
                Type = DataValidationValues.List,
                AllowBlank = true,
                SequenceOfReferences = new ListValue<StringValue> { InnerText = "A1:A1048576" }
            };

            dataValidation.Append(
                //new Formula1 { Text = "\"FirstChoice,SecondChoice,ThirdChoice\"" }
                new Formula1(string.Format("'{0}'!$A:$A", dataContainingSheet))
                );
            dataValidations.Append(dataValidation);

            var wsp = ws.WorksheetPart;
            wsp.Worksheet.AppendChild(dataValidations);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM