我正在尝试在C#中打开并加载Excel文件

时间:2019-08-29 09:41:45

标签: c# excel

打开现有的Excel文件时,调试中不会发生错误。但是Excel无法打开并获取单元格的值。

我正在使用c#。我更改了打开格式,但是结果是相同的。

检查的格式是一一检查所有Excel值并返回结果。

例如,如果总共有100行,则while语句将从1旋转到100,将程序的结果插入两列并保存。

public void RunTask()
    {

        Excel.Application application = null;
        Excel.Workbook wb = null;
        Excel.Worksheet ws = null;

        try
        {

            if(filePath==null)
            {
                MessageBox.Show("파일이 선택되지않았습니다.");
                throw new Exception("file is not exist");
            }
            application = new Excel.Application();
            wb = application.Workbooks.Open(filePath, 0, true, 5, "", "", 
                 true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, 
                 false, 0, true, 1, 0);
            //wb = application.Workbooks.Open(Filename: filePath);
            ws = wb.Worksheets.Item[1];
            int textColum = Int32.Parse(text_colum.Text);
            Range range = null;
            int cellcnt = 1;
            String temp = null;

            if (goToURL(getURL))
            {
                Thread.Sleep(3000);
                while (true)                 
                {
                    temp = null;
                    cellcnt++;

                    range = ws.Cells[cellcnt, 1];
                    temp = range.Value.ToString();     
                    if (temp == null) break;

                    IWebElement q = driver.FindElement(By.Id("top_search"));
                    q.Clear();
                    q.SendKeys(temp);
                    driver.FindElement(By.ClassName("search_m")).Click();


                    try
                    {
                        IWebElement t = driver.FindElement(By.XPath("//* 
                           [@id=\"conts\"]/div[3]/div[1]/div[1]/dl/dd[1]"));
                        temp = t.GetProperty("innerHTML").ToString();
                    }
                        catch(Exception ex)
                        {
                            continue;
                        }

                    Thread.Sleep(3000);



                    ws.Cells[cellcnt, textColum].Value= temp;

                }
            }
            else
            {
                MessageBox.Show("사이트가 설정되지않았습니다.");
                stopThread();
            }

            wb.SaveAs(@"D:\test.xls");
            wb.Close(true);
            application.Quit();

        }
        catch(Exception ex)
        {
            stopThread();
        }
        finally
        {
            // Clean up
            ReleaseExcelObject(ws);
            ReleaseExcelObject(wb);
            ReleaseExcelObject(application);
        }
    }

0 个答案:

没有答案