首页 > 解决方案 > C# 中的 Excel 互操作更快地读取大 Excel 文件?

问题描述

请任何人都可以尝试告诉我应该在我的代码中进行哪些更改以更快地读取 Excel 文件?

我的 Excel 表中有 9 000 行。我将不得不处理更多行数更多的 Excel 文件,我认为我的解决方案非常慢。现在我读取 Excel(9000 行)读取第二个和一个(800 行)然后我比较值(试图在 9000 行中找到 800 条记录。在两个单独的线程上花了我超过 100 秒。

class ExcelParser
{
    private string path;
     _Application excel = new _Excel.Application();
    Workbook wb;
    Worksheet ws;
    private int Sheet;

    public ExcelParser(string path, int Sheet)
    {
        this.Sheet = Sheet;
        this.path = path;
        this.wb = this.excel.Workbooks.Open(path);
        this.ws = wb.Worksheets[Sheet];
    }

    //column code and available are index of excel  column from where read data
    public Dictionary<string, string> ReadCell(int column_code = 0, int column_available = 0)
    {
        int i = 2; // row index in excel
        Dictionary<string, string> data = new Dictionary<string, string>();
        try { 
        while (this.ws.Cells[i, column_code].Value2 != null)
        {
            try
            {
                data.Add(this.ws.Cells[i, column_code].Value2, (this.ws.Cells[i, column_available].Value2).ToString());
                i++;

                }
            catch (Exception e)
            {
                i++;
                //form_obj.UpdateText(i);
            }

        }
        } finally {
            wb.Close();
            excel.Quit();
            Marshal.FinalReleaseComObject(excel);
            Marshal.FinalReleaseComObject(this.ws);
            Marshal.FinalReleaseComObject(this.wb);
            this.ws = null;
            this.wb = null;
        }
        return data;

    }
}

在我释放所有对象或尝试this.wb.Close(). 退出 GUI 后,实例将退出。wb.Close();为什么这个函数通过and结束后 Excel 的实例没有关闭 excel.Quit();

标签: c#excelperformancebigdatainterop

解决方案


推荐阅读