我编写了一个方法来在传递文件名、工作表名和单元格地址时返回 Excel 工作表单元格值。
public static string GetCellValue(string fileName, string sheetName, string addressName)
{
string value = null;
using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false))
{
WorkbookPart wbPart = document.WorkbookPart;
Where(s => s.Name == sheetName).FirstOrDefault();
if (theSheet == null)
{
throw new ArgumentException("sheetName");
}
WorksheetPart wsPart =
(WorksheetPart)(wbPart.GetPartById(theSheet.Id));
Cell theCell = wsPart.Worksheet.Descendants<Cell>().
Where(c => c.CellReference == addressName).FirstOrDefault();
if (theCell != null)
{
value = theCell.InnerText;
if (theCell.DataType != null)
{
switch (theCell.DataType.Value)
{
case CellValues.SharedString:
.
var stringTable =
wbPart.GetPartsOfType<SharedStringTablePart>()
.FirstOrDefault();
if (stringTable != null)
{
value =
stringTable.SharedStringTable
.ElementAt(int.Parse(value)).InnerText;
}
break;
case CellValues.Boolean:
switch (value)
{
case "0":
value = "FALSE";
break;
default:
value = "TRUE";
break;
}
break;
}
}
}
}
return value;
}
这是调用上述方法的方法。
private void button1_Click(object sender, EventArgs e)
{
const string fileName = @"C:\Users\dkumarage\Desktop\Book1.xlsx";
string value = GetCellValue(fileName, "Sheet1", "A1");
textBox1.Text = value;
}
这样我只能获得 1 个单元格值。如何递归调用此方法以获取所有单元格值。请帮我。(在这里我不能通过范围。因为我不知道范围。相反我必须使用 while(不是行尾))
谢谢你