c# - 读取大型 Excel 工作表时的内存优化

标签 c# excel memory recursive-query

我确实有一个 excel 文件,我开发了一种方法来读取工作表 1 中的所有内容并将其填充到 ListView 中,基本上工作表在单元格 A-D 中有数据。但这个数字是120,000。当我运行代码时,它确实读取了这些文件,这需要时间,但在此过程中,对表单的任何操作(如最小化或单击任意位置的表单)都会卡住程序并导致其崩溃。我怎样才能像任何好的程序一样提高性能。下面是我的代码。

   private void button1_Click(object sender, EventArgs e)
    {
        Microsoft.Office.Interop.Excel.Application ExcelObj = new 
        Microsoft.Office.Interop.Excel.Application();
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
         // prepare open file dialog to only search for excel files (had 
        //  trouble setting this in design view)

         openFileDialog1.FileName = "*.xlsx";
         if (openFileDialog1.ShowDialog() == DialogResult.OK)
         {
             // Here is the call to Open a Workbook in Excel 
            // It uses most of the default values (except for the read-only 
           // which we set to true)

                Workbook theWorkbook =   
                ExcelObj.Workbooks.Open(openFileDialog1.FileName, 0, true, 
                5,"", "", true,  XlPlatform.xlWindows, "\t", false, false, 
                0, true);


            // get the collection of sheets in the workbook

               Sheets sheets = theWorkbook.Worksheets;

            // get the first and only worksheet from the collection of 
           //  worksheets

            Worksheet worksheet = (Worksheet)sheets.get_Item(1);

            // loop through 10 rows of the spreadsheet and place each row in 
            // the list view

            for (int i = 1; i <= 10; i++)
            {
                Range range = worksheet.get_Range("A" + i.ToString(), "J" + 
                i.ToString());
                System.Array myvalues = (System.Array)range.Cells.Value;
                string[] strArray = ConvertToStringArray(myvalues);
                listView1.Items.Add(new ListViewItem(strArray));
            }
        }

    }


       string[] ConvertToStringArray(System.Array values)
           {
        // create a new string array

        string[] theArray = new string[values.Length];

         // loop through the 2-D System.Array and populate the 1-D String 
        // Array

        for (int i = 1; i <= values.Length; i++)
        {
            if (values.GetValue(1, i) == null)
                theArray[i - 1] = "";
            else
                theArray[i - 1] = (string)values.GetValue(1, i).ToString();
        }
        return theArray;
    }

最佳答案

关于c# - 读取大型 Excel 工作表时的内存优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46837456/

相关文章:

c++ - 内存映射文件 std::allocator 实现卡住 WM6 设备

c# - LoaderOptimizationAttribute 的作用

c# - "The debugger cannot continue running the process."

c++ - 自动内存分配如何在 C++ 中实际工作?

c++ - malloc() : memory corruption (fast) c++

excel - 条件格式规则拆分和重复

C# 正则表达式获取 4 到 10 个字符之间的单词

c# - 如何将两个 slider XAML 控件值绑定(bind)在一起?

Excel 如果(和/如果(或

excel - 创建具有子级别的类属性