如何从每个单元格获取数据?

时间:2015-11-01 17:55:29

标签: c# excel

我为在医院工作的朋友做了一个应用程序。

应用程序基本上只是从excel中获取数据,对其进行排序并显示它。 我坚持抓住所有数据。 excel文件有3列和n行。第一列的单元格并不总是填充。

我尝试了不同的方法来获取数据,但我始终无法使其正常工作。我试图将空单元格包含在搜索中,但现在temp将返回所有空字符串。

如何迭代每一行直到结束,并且每次迭代都会从每列中获取数据,即使它是空的 - 返回""?

            Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
            Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(currentExcelLocation, 0, true, 5, "", "", false, Excel.XlPlatform.xlWindows,
                                                                        "", false, true, 0, false, false, false);
            Excel.Sheets excelSheets = excelWorkbook.Worksheets;
            Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(3);
            int iTotalRows = excelWorksheet.UsedRange.Rows.Count;
            for (int i = 1; i <= iTotalRows; ++i)
            {
                string tempL = (excelWorksheet.Cells[i, 1] as Excel.Range).SpecialCells(Excel.XlCellType.xlCellTypeBlanks).Text.ToString();
                if (tempL != "") { temp = tempL; }
                string tempS = (excelWorksheet.Cells[i, 2] as Excel.Range).Value2.ToString();
                string tempD = (excelWorksheet.Cells[i, 3] as Excel.Range).Value2.ToString();
                DataScheme.Symptoms tempSD = new DataScheme.Symptoms(tempS, tempD);
                if (data.FindIndex(a => a.Location == temp) < 0) { data.Add(new DataScheme(temp)); }
                data.Find(b => b.Location == temp).SympList.Add(tempSD);
                textBox6.Text += temp + Environment.NewLine;
            }
            excelWorkbook.Close(0);
            excelApp.Quit();
            Marshal.FinalReleaseComObject(excelApp);
            Marshal.FinalReleaseComObject(excelWorkbook);
            Marshal.FinalReleaseComObject(excelSheets);
            Marshal.FinalReleaseComObject(excelWorksheet);

1 个答案:

答案 0 :(得分:1)

从Nuget获取closedXML,然后按照此方法将excel数据返回到Datatable,然后就可以从每一行获取数据。

    public static DataTable ImportSheet(string fileName)
    {
        var datatable = new DataTable();
        var workbook = new XLWorkbook(fileName);
        var xlWorksheet = workbook.Worksheet(1);
        var range = xlWorksheet.Range(xlWorksheet.FirstCellUsed(), xlWorksheet.LastCellUsed());

        var col = range.ColumnCount();
        var row = range.RowCount();

        datatable.Clear();
        for (var i = 1; i <= col; i++)
        {
            var column = xlWorksheet.Cell(1, i);
            datatable.Columns.Add(column.Value.ToString());
        }

        var firstHeadRow = 0;
        foreach (var item in range.Rows())
        {
            if (firstHeadRow != 0)
            {
                var array = new object[col];
                for (var y = 1; y <= col; y++)
                {
                    array[y - 1] = item.Cell(y).Value;
                }

                datatable.Rows.Add(array);
            }
            firstHeadRow++;
        }
        return datatable;
    }