我想要一个包含电子表格中所有单元格的所有值的数组或列表。有一定数量的列,但有任意数量的行。这是我从msdn.com获得的一种方法,我想知道是否可以修改它以返回电子表格中的所有值,或者是否有办法获取所有具有值的单元格,然后使字符串生成器迭代通过每个地址。真的,我正试图了解这个SDK,并希望你们能给我一些见解。这是方法:
public static string GetCellValue(string fileName,
string sheetName,
string addressName)
{ string value = null;
// Open the spreadsheet document for read-only access.
using (SpreadsheetDocument document =
SpreadsheetDocument.Open(fileName, false))
{
// Retrieve a reference to the workbook part.
WorkbookPart wbPart = document.WorkbookPart;
// Find the sheet with the supplied name, and then use that
// Sheet object to retrieve a reference to the first worksheet.
Sheet theSheet = wbPart.Workbook.Descendants<Sheet>().
Where(s => s.Name == sheetName).FirstOrDefault();
// Throw an exception if there is no sheet.
if (theSheet == null)
{
throw new ArgumentException("sheetName");
}
// Retrieve a reference to the worksheet part.
WorksheetPart wsPart =
(WorksheetPart)(wbPart.GetPartById(theSheet.Id));
// Use its Worksheet property to get a reference to the cell
// whose address matches the address you supplied.
Cell theCell = wsPart.Worksheet.Descendants<Cell>().
Where(c => c.CellReference == addressName).FirstOrDefault();
// If the cell does not exist, return an empty string.
if (theCell != null)
{
value = theCell.InnerText;
// If the cell represents an integer number, you are done.
// For dates, this code returns the serialized value that
// represents the date. The code handles strings and
// Booleans individually. For shared strings, the code
// looks up the corresponding value in the shared string
// table. For Booleans, the code converts the value into
// the words TRUE or FALSE.
if (theCell.DataType != null)
{
switch (theCell.DataType.Value)
{
case CellValues.SharedString:
// For shared strings, look up the value in the
// shared strings table.
var stringTable =
wbPart.GetPartsOfType<SharedStringTablePart>()
.FirstOrDefault();
// If the shared string table is missing, something
// is wrong. Return the index that is in
// the cell. Otherwise, look up the correct text in
// the table.
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;
}
我非常感谢任何帮助。
答案 0 :(得分:1)
以下代码块抓取所有单元格并将其过滤到我们想要查找的单元格中...
Cell theCell = wsPart.Worksheet.Descendants<Cell>().
Where(c => c.CellReference == addressName).FirstOrDefault();
如果删除Where(...)
,则应该为您提供所有单元格...
var cells = wsPart.Worksheet.Descendants<Cell>();
现在您已经拥有了这个,您可以在if (theCell != null) { ... }
块中获取代码块,使其成为Cell
的方法(我在这里称之为ProcessCell
,它是'需要是一个返回static
的{{1}}函数,并在string
循环中调用它,如下所示:
foreach
然后只返回结果!
var results = new List<String>();
foreach cell in cells
{
results.Add(ProcessCell(cell));
}
从技术上讲,我没有回答你的问题,因为返回类型是return results;
而不是数组,但我认为如果真的有必要,你可以找出那部分;)