使用ClosedXML读取Excel

时间:2016-11-28 23:33:31

标签: excel c#-4.0 closedxml

使用ClosedXML读取整个Excel文件并返回List<List<object>>的最有效方法是什么?

这不知何故给我数据。我得到空列表。

        var wb = new XLWorkbook(finalFilePath);
        var ws = wb.Worksheets.First();
        var range = ws.RangeUsed();
        var colCount = range.ColumnCount();
        var rowCount = range.RowCount();

        var i = 1;
        var j = 1;
        List<List<object>> data = new List<List<object>>();
        while (i < rowCount + 1)
        {
            List<object> row = new List<object>();
            while (j < colCount + 1)
            {
                row.Add(ws.Cell(i, j).Value);
                j++;
            }
            data.Add(row);
            i++;
        }

1 个答案:

答案 0 :(得分:1)

这可以完成工作:

Dictionary<Tuple<int, int>, object> data = new Dictionary<Tuple<int, int>, object>();
using (XLWorkbook wb = new XLWorkbook(filePath))
{
    var ws = wb.Worksheets.First();
    var range = ws.RangeUsed();

    for (int i = 1; i < range.RowCount() + 1; i++)
    {
        for (int j = 1; j < range.ColumnCount() + 1; j++)
        {
            data.Add(new Tuple<int, int>(i,j), ws.Cell(i,j).Value);
        }
    }
}