如何在C#中使用Open XML打开Excel文档并读取值

时间:2013-09-20 20:17:11

标签: c# excel openxml

我希望能够打开一个excel文档,并使用C#中的Open XML循环遍历单元格中的值。

尝试使用以下代码,但它永远不会超过Foreach(Row ...)。另外注释表明这是数值而非Alpha数值。

    using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(Filedirectory, false))
    {
        WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
        WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
        SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
        string text;
        foreach (Row r in sheetData.Elements<Row>())
        {
            foreach (Cell c in r.Elements<Cell>())
            {
                text = c.CellValue.Text;
            }
        }
    }

1 个答案:

答案 0 :(得分:-1)

一位同事想出了以下解决方案。

            FileInfo uploadedFile = new FileInfo(FileDirectory);
            using (ASC.ExcelPackage.ExcelPackage xlPackage = new ASC.ExcelPackage.ExcelPackage(uploadedFile))
            {
                ASC.ExcelPackage.ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[1];
                Int32 currentRow = 1;
                while (worksheet.Cell(currentRow, 1) != null && !string.IsNullOrEmpty(worksheet.Cell(currentRow, 1).Value))
                {
                    string value = worksheet.Cell(currentRow, 1).Value;

                    currentRow++;
                }
            }