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

时间:2019-02-01 16:25:19

标签: c# excel openxml

我将c#与OpenXml结合使用,试图从Excel工作簿中读取一些单元格值。

我有一些字符串来定义我需要提取的单元格的范围和范围,例如

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

我正在从Workbookpart实例中的DefinedName获取以上字符串。

如何使用OpenXml获取此范围内描述的单元格值?

1 个答案:

答案 0 :(得分:0)

您可以创建海关方法来遍历范围并读取单元格值。我将通过以下方式进行操作:

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

为您获取单元格值的方法:

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

获取行的方法:

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

获取下一列的方法:

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