简体   繁体   English

如何使用OpenXml和C#获取范围内的所有行/单元格值

[英]How to get all rows/cell values from a range with OpenXml and c#

I'm using c# with OpenXml to try to read some cell values from an Excel workbook. 我将c#与OpenXml结合使用,试图从Excel工作簿中读取一些单元格值。

I have strings that define the sheet and range of cells I need to extract for example, 例如,我有一些字符串定义了我需要提取的单元格的范围和范围,

'Master Products'!$Q$4:$AD$89"

I'm obtaining the above string from a DefinedName in my Workbookpart instance. 我从我的Workbookpart实例中的DefinedName获取以上字符串。

How can I get the cell values described in this range using OpenXml? 如何使用OpenXml获取此范围内描述的单元格值?

You can create your customs methods to iterate through a range and read the cell values. 您可以创建海关方法来遍历范围并读取单元格值。 I would do it the following way: 我将通过以下方式进行操作:

static void Main(string[] args)
{
    int rowStart = 4;
    string colStart = "Q";
    int rowEnd = 89;
    string colEnd = "AD";
    string currentRow = colStart;
    // make sure rowStart < rowEnd && colStart < colEnd

    using (document = SpreadsheetDocument.Open(filePath, true))
    {
        WorkbookPart wbPart = document.WorkbookPart;
        Worksheet sheet = wbPart.WorksheetParts.First().Worksheet;
        while(currentRow != GetNextColumn(colEnd))
        {
            for (int i = rowStart; i <= rowEnd; i++)
            {
                Cell cell = GetCell(sheet, currentRow, i);
            }
            currentRow = GetNextColumn(currentRow);
        }
    }
    Console.Read();
}

Method that gets you the cell value: 获取单元格值的方法:

private static Cell GetCell(Worksheet worksheet,
    string columnName, uint rowIndex)
{
    Row row = GetRow(worksheet, rowIndex);

    if (row == null)
        return null;

    return row.Elements<Cell>().Where(c => string.Compare
                                           (c.CellReference.Value, columnName +
                                                                   rowIndex, true) == 0).First();
}

Method to get the row: 获取行的方法:

// Given a worksheet and a row index, return the row.
private static Row GetRow(Worksheet worksheet, uint rowIndex)
{
    return worksheet.GetFirstChild<SheetData>().
        Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
}

Method to get the next column: 获取下一列的方法:

static string GetNextColumn(string col)
{
    char[] charArr = col.ToCharArray();
    var cur = Convert.ToChar((int) charArr[charArr.Length - 1]);
    if (cur == 'Z')
    {
        if (charArr.Length == 1)
        {
            return "AA";
        }
        else
        {
            char[] newArray = charArr.Take(charArr.Length - 1).ToArray();
            var ret = GetNextColumn(new string(newArray));
            return ret + "A";
        }
    }
    charArr[charArr.Length - 1] = Convert.ToChar((int)charArr[charArr.Length - 1] + 1);
    return new string(charArr);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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