从单元格值openxml中获取列号

时间:2015-01-02 06:04:42

标签: c# excel openxml openxml-sdk

我有一个Excel,其中我想获取列号,例如下图: Sample Image

在上图中,我知道记录将出现在第1行,但我不确定列号。在上面的示例中,列值:“Quantity”出现在“D1”上。我知道行号如何使用OPEN XML找到列号(在上例中为“D”),因为列名称数量可能出现在excel中的任何位置,我需要找到仅相应数量的相应值。

1 个答案:

答案 0 :(得分:3)

不幸的是,没有一种方法可以调用来找到正确的单元格。相反,您需要遍历单元格以查找匹配的文本。为了使事情略微复杂化,单元格中的值并不总是实际文本。相反,字符串可以存储在SharedStringTablePart中,而单元格的值是该表内容的索引。

以下内容应该做你想要的事情:

private static string GetCellReference(string filename, string sheetName, int rowIndex, string textToFind)
{
    using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, false))
    {
        WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
        //get the correct sheet
        Sheet sheet = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName).First();
        if (sheet != null)
        {
            WorksheetPart worksheetPart = workbookPart.GetPartById(sheet.Id) as WorksheetPart;

            SharedStringTablePart stringTable = workbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();

            SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();

            Row row = sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).First();

            if (row != null)
            {
                foreach (Cell c in row.Elements<Cell>())
                {
                    string cellText;

                    if (c.DataType == CellValues.SharedString)
                    {
                        //the value will be a number which is an index into the shared strings table
                        int index = int.Parse(c.CellValue.InnerText);
                        cellText = stringTable.SharedStringTable.ElementAt(index).InnerText;
                    }
                    else
                    {
                        //just take the value from the cell (note this won't work for dates and other types)
                        cellText = c.CellValue.InnerText;
                    }

                    if (cellText == textToFind)
                    {
                        return c.CellReference;
                    }
                }
            }
        }
    }

    return null;
}

然后可以这样调用:

string cellReference = GetCellReference(@"c:\temp\test.xlsx", "Sheet1", 1, "Quantity");
Console.WriteLine(cellReference); //prints D1 for your example

如果您只想D而不是D1,可以使用简单的regex删除数字:

private static string GetColumnName(string cellReference)
{
    if (cellReference == null)
        return null;

    return Regex.Replace(cellReference, "[0-9]", "");
}

然后像这样使用它:

string cellReference = GetCellReference(@"c:\temp\test.xlsx", "Sheet1", 1, "Quantity");
Console.WriteLine(GetColumnName(cellReference)); //prints D for your example
相关问题