打开XML SDK 2.0,按名称访问excel 2010工作表

本文关键字:访问 excel 2010 工作 SDK XML 打开 | 更新日期: 2023-09-27 18:20:01

我有一个Excel 2010电子表格,其中有三个工作表,分别命名为Sheet1、Sheet2和Sheet3。

我正在尝试按名称引用工作表。

我使用的代码是:

using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(FileName, true))
{
    //Access the main Workbook part, which contains all references 
    WorkbookPart workbookPart = myWorkbook.WorkbookPart;
    WorksheetPart worksheetPart = workbookPart.WorksheetParts.Last(); 
    // this gives me Sheet1
    SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
}

我正试图获得Sheet2的参考资料,但我找不到这样做的方法。

我越来越近了,但我还没有到达:

var x = workbookPart.Workbook.Sheets.Where(s=> s.GetAttribute("name", "").Value == "Sheet2").FirstOrDefault();

这让我参考了表格,但没有参考表格上的数据

感谢

打开XML SDK 2.0,按名称访问excel 2010工作表

您真正想要的是WorksheetPart,它包含您要查找的SheetData。在Workbook下抓取Sheets只会为您提供有关工作表的某些元数据。以下是一个关于如何获取WorksheetPart的示例(请随意添加您认为合适的错误检查,因为我假设通过调用First而不是FirstOrDefaultsheetName已经存在)

public WorksheetPart GetWorksheetPart(WorkbookPart workbookPart, string sheetName)
{
    string relId = workbookPart.Workbook.Descendants<Sheet>().First(s => sheetName.Equals(s.Name)).Id;
    return (WorksheetPart)workbookPart.GetPartById(relId);
}

然后,只需使用上面的代码获取正确的SheetData引用,就可以从中找到所需的数据。

以下是一些代码,用于处理具有特定选项卡或工作表名称的电子表格,并将其转储到类似CSV的文件中。(我选择了竖管而不是逗号)。

我希望能更容易地从单元格中获取值,但我认为这正是我们所坚持的。您可以看到,我引用了MSDN文档,其中包含了大部分代码。这就是微软的建议。

    /// <summary>
    /// Got code from: https://msdn.microsoft.com/en-us/library/office/gg575571.aspx
    /// </summary>
    [Test]
    public void WriteOutExcelFile()
    {
        var fileName = "ExcelFiles''File_With_Many_Tabs.xlsx";
        var sheetName = "Submission Form"; // Existing tab name.
        using (var document = SpreadsheetDocument.Open(fileName, isEditable: false))
        {
            var workbookPart = document.WorkbookPart;
            var sheet = workbookPart.Workbook.Descendants<Sheet>().FirstOrDefault(s => s.Name == sheetName);
            var worksheetPart = (WorksheetPart)(workbookPart.GetPartById(sheet.Id));
            var sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
            foreach (var row in sheetData.Elements<Row>())
            {
                foreach (var cell in row.Elements<Cell>())
                {
                    Console.Write("|" + GetCellValue(cell, workbookPart));
                }
                Console.Write("'n");
            }
        }
    }
    /// <summary>
    /// Got code from: https://msdn.microsoft.com/en-us/library/office/hh298534.aspx
    /// </summary>
    /// <param name="cell"></param>
    /// <param name="workbookPart"></param>
    /// <returns></returns>
    private string GetCellValue(Cell cell, WorkbookPart workbookPart)
    {
        if (cell == null)
        {
            return null;
        }
        var value = cell.CellFormula != null
            ? cell.CellValue.InnerText 
            : cell.InnerText.Trim();
        // 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 (cell.DataType == null)
        {
            return value;
        }
        switch (cell.DataType.Value)
        {
            case CellValues.SharedString:
                // For shared strings, look up the value in the
                // shared strings table.
                var stringTable =
                    workbookPart.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;
    }