从单元格值openxml获取列号

我有一个Excel,其中我想获得例如下面的图像的列号: 示例图像

在上面的图片中,我知道logging将出现在第一行,但我不确定列号。 在上面的例子中,在“D1”上出现列值:“数量”。 我知道行号如何使用OPEN XMLfind列号(在上面的例子中是“D”),因为列名的数量可能出现在Excel的任何地方,我只需要find相应的数值。

不幸的是,没有一种方法可以调用find正确的单元格。 相反,您需要遍历单元格以查找匹配的文本。 稍微复杂一点,单元格中的值并不总是实际的文本。 相反,string可以存储在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