我正在尝试使用Visual Studio 2013在C#中使用Open XML SDK读取excel。 我按照以下链接 http://msdn.microsoft.com/en-us/library/office/hh298534(v=office.15).aspx http://msdn.microsoft.com/en-us/library/office/gg575571.aspx
代码是
using (SpreadsheetDocument document = SpreadsheetDocument.Open(excelPath, true))
{
WorkbookPart workbookPart = document.WorkbookPart;
foreach (WorksheetPart workSheetPart in workbookPart.WorksheetParts)
{
SheetData sheetData = workSheetPart.Worksheet.Elements<SheetData>().First();
IEnumerable<Row> rows = sheetData.Elements<Row>().Where(x => x.RowIndex > 1);
foreach (Row r in rows)
{
IEnumerable<string> textValues = from cell in r.Descendants<Cell>() where cell.CellValue != null select cell.CellValue.Text;
foreach (var cell in textValues)
{
string str = cell.ToString();
}
}
}
}
我也试过以下代码
using (SpreadsheetDocument document = SpreadsheetDocument.Open(excelPath, true))
{
WorkbookPart workbookPart = document.WorkbookPart;
foreach (WorksheetPart workSheetPart in workbookPart.WorksheetParts)
{
SheetData sheetData = workSheetPart.Worksheet.Elements<SheetData>().First();
IEnumerable<Row> rows = sheetData.Elements<Row>().Where(x => x.RowIndex > 1);
foreach (Row r in rows)
{
List<Cell> cells = r.Descendants<Cell>().ToList();
foreach (var cell in cells)
{
if (cell != null)
{
string value = cell.CellValue.Text;
if (cell.DataType != null)
{
switch (cell.DataType.Value)
{
case CellValues.SharedString:
var stringTable = workSheetPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
if (stringTable != null)
{
value = stringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText;
}
break;
}
}
}
}
}
}
}
但两者都只返回数值,而不是文本。任何人都可以请教如何使用C#中的Open XML SDK阅读excel文本。?