读取Excel文件时遇到问题

时间:2020-10-16 09:01:59

标签: c# excel visual-studio office-interop

我的项目是打开的excel文件,并在C#中逐行读取,但是我的excel参考文件存在一些空行

例如第一行和第二行不是空的(没有单元格),但是第三行,第四行和第五行的所有单元格都是

为空,然后下一行的单元格不为空等。现在,当我的代码仅在Reads中运行时

仅文件的前几行已满,并且只要到达第一行就完全为空

它退出循环读取文件时尚未结束。为什么会发生这种情况?如何解决?

    private void button1_Click(object sender, EventArgs e)
        {

           
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            Excel.Range range;

            string str;
            string table = null;
            int rCnt;
            int cCnt;
            int rw = 0;
            int cl = 0;

            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Open(@"C:\Users\mostafaheydarsana\Desktop\mp.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            range = xlWorkSheet.UsedRange;
            rw = range.Rows.Count;
            cl = range.Columns.Count;
           
            string s = "'nbn";
            
            string table_row = null;

            int io = 0;
            
            string new_str = null;
            
            string question_field = null;
            
            int peymaeshrowaforaddquestioha;

            try
            {
                StreamWriter sw = new StreamWriter("C:\\Users\\user1\\Desktop\\Test.txt");

                for (rCnt = 1; rCnt <= rw; rCnt++)
                {
                    
                    if (range.Cells[rCnt, 1].Value != null)
                    {
                        sw.WriteLine("question is ( " + question_field + s[0] + "," + new_str + "');", io++);
                        
                        MessageBox.Show("rCnt is " + rCnt + "quesstion_field is insert in file ***" + question_field + "***");

                        question_field = null;
                       
                        new_str = null;

                        new_str += s[0] + range.Cells[rCnt, 1].Value2.ToString() + s[0] + "," + s[0] + range.Cells[rCnt, 2].Value2.ToString() + s[0] + "," + s[0] + range.Cells[rCnt, 3].Value2.ToString() + s[0];

                        question_field += range.Cells[rCnt, 4].Value2.ToString();

                    }
                    else if(range.Cells[rCnt, 1].Value == null)
                    {

                        question_field += range.Cells[rCnt, 4].Value2.ToString();

                        MessageBox.Show("rCnt is " + rCnt + "quesstion_field is ***" + question_field + "***");

                        peymaeshrowaforaddquestioha = rCnt + 1;

                    }
                }
                
                sw.Close();
            }

            catch (Exception ec)
            {
                Console.WriteLine("Exception: " + ec.Message);
            }
            finally
            {
                Console.WriteLine("Executing finally block.");
            }

            xlWorkBook.Close(true, null, null);
            
            xlApp.Quit();

            Marshal.ReleaseComObject(xlWorkSheet);
            Marshal.ReleaseComObject(xlWorkBook);
            Marshal.ReleaseComObject(xlApp);


        }

2 个答案:

答案 0 :(得分:0)

在使用MS OpenXML库进行大量工作以创建Excel输出之后,我在NuGet中发现了ClosedXML包,结果发现这是一种更好,更轻松的方法。很有可能也可以解决您阅读Excel的问题。

答案 1 :(得分:0)

根据我的测试,问题在于,当您尝试访问空单元格时,将出现异常“无法对空引用执行运行时绑定”。

根据参考文献Cannot perform runtime binding on a null reference - Empty Excel Cells,您可以尝试修改以下代码。

更改

        $jsonDecoded = json_decode(file_get_contents('emails.json', true), true);   

        $list = array(
            array('Email Address', 'First Name')
        );

        $timestamp = time();
        foreach($jsonDecoded as $entry)
        {
            $new = array($entry['email'], $entry['name']);
            $list[$timestamp] = $new;
        }

        //if old file exist delete
        $fp = fopen('emails.csv', 'w');
        foreach ($list as $fields) {
            fputcsv($fp, $fields);
        }
        fclose($fp);

进入:

 question_field += range.Cells[rCnt, 4].Value2.ToString();

对我有用。