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

泄露秘密 提交于 2021-02-20 02:11:51

问题


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?


回答1:


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.




回答2:


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>()



回答3:


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();
}


来源:https://stackoverflow.com/questions/49532009/how-can-i-get-the-specific-column-in-excel-worksheet-using-documentformat-openxm

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