我有一个 Excel,其中我想获取下图的列号:
在上图中,我知道记录将出现在第一行,但我不确定列号。在上面的示例中,列值:“数量”出现在“D1”上。我知道行号如何使用 OPEN XML 找到列号(在上述情况下为“D”),因为列名数量可能出现在 excel 中的任何位置,我只需要找到数量的相应值。
最佳答案
遗憾的是,没有一种方法可以调用来查找正确的单元格。相反,您需要遍历单元格以找到匹配的文本。让事情稍微复杂一点的是,单元格中的值并不总是实际的文本。相反,字符串可以存储在 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
关于c# - 从单元格值中获取列号,openxml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27738041/