简体   繁体   中英

How can I get the specific column in excel worksheet using DocumentFormat.OpenXml C#?

As the title, I would like to get a specific column in excel worksheet using OpenXML in C# for setting hidden property. Like that:

var columns = worksheet.GetFirstChild<Columns>();
var column = columns.FirstOrDefault(c=>c.ColumnIndex == 4);
column.Hidden = true;

The code above is just a sample for my idea. Is there any way for solving my problem?

per: https://docs.microsoft.com/en-us/office/open-xml/how-to-get-a-column-heading-in-a-spreadsheet ,

workSheetPart.Worksheet.Descendants() in fact gives the columnGroup, not columns in the common sense; here the "column" is a misnomer and it has consequences like questions like this pop out.

Once you get the column group, you can use its "Min" and "Max" attribute to get the columns in it.

Have you tried a similar one (this is for getting a cell)?

Worksheet.Descendants<Cell>().SingleOrDefault(c => c.CellReference.Equals("A1"));

Update: Following code gives the columns in worksheet (select the column you want based on index or the Name)

workSheetPart.Worksheet.Descendants<Column>()

It seems that there is no built-in way to get to a specific column (BTW, this is opposed to the much-used DataTable type, which has a Columns property). As explained here , calling Descendants<Column>() will return null, unless custom column behaviors are specified.

So the way to do it is the documented way , which actually iterates through all of the worksheet's cells.

// Get the cells in the specified column and order them by row.
internal List<Cell> GetColumnCells(Worksheet worksheet, string columnName)
{
    var columnCells = worksheet.Descendants<Cell>()
        .Where(c => string.Compare(GetColumnName(c.CellReference.Value), columnName, true) == 0)
        .OrderBy(r => GetRowIndex(r.CellReference))
        .ToList();
}                            
private string GetColumnName(StringValue cellName)
{
    var regex = new Regex("[a-zA-Z]+");
    var match = regex.Match(cellName);
    return match.Value;
}
private uint GetRowIndex(StringValue cellName)
{
    var regex = new Regex(@"\d+");
    var match = regex.Match(cellName);
    return uint.Parse(match.Value);
}

However, you can improve this a little by iterating the rows, and move to the next row once you get the cell of the required column:

internal List<Cell> GetColumnCells(Worksheet worksheet, string columnName)
{
     var columnCells = worksheet.Descendants<Row>()
          .Where(r => r.Descendants<Cell>().FirstOrDefault(c => 
              string.Compare(GetColumnName(c.CellReference.Value), columnName, true) == 0)
          )
          .OrderBy(r => GetRowIndex(r.CellReference))
          .ToList();
}

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