0
我編寫了一個方法,用於在傳遞文件名,工作表名稱和單元格地址時返回Excel工作表單元格值。遞歸調用方法來獲取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'和哪裏有什麼錯誤使用它? –
我只想從excel中獲取所有的值,而不是獲取一行。我不知道該怎麼做。 – devan