如何在C#控制台应用程序中基于标题值读取Excel工作表

时间:2018-07-09 05:57:31

标签: c# excel excel-interop

我希望程序根据工作表中指定的标头值读取Excel工作表。我有一列名为“ URL”的列,因此我想阅读基于“ URL”的列,然后它应该能够在读取该特定列的同时下载文件。

 static void Main(string[] args)
    {

        Excel.Application xlApp = new Excel.Application();

        /* if (xlApp == null)
        {
            Console.WriteLine("Excel is not installed!!");
             return;
        }*/

        Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"E:\ABC\ConsoleApplication1\ConsoleApplication1\Test-URL.xlsx");


        Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
        Excel.Range xlRange = xlWorksheet.UsedRange;

        int rowCount = xlRange.Rows.Count;
        int colCount = xlRange.Columns.Count;

        //iterate over the rows and columns and print to the console as it appears in the file
        //excel is not zero based!!
        for (int i = 1; i < rowCount; i++)
        {

            for (int j = 1; j <= colCount; j++)
            {
                //new line
                if (j == 1)
                    Console.Write("\r\n");


                //write the value to the console
                if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null)
                    Console.Write(xlRange.Cells[i, j].Value2.ToString() + "\t");


                //Downloading this file from excel sheet
                /*  string remoteUri ="Url";
                string fileName = "E:\\Hanifa\\ConsoleApplication1\\ConsoleApplication1\\Downloaded";
                WebClient myWebClient = new WebClient();
                myWebClient.DownloadFile(remoteUri, fileName); */



                Console.WriteLine("working");
                Console.WriteLine("Press enter to close...");
                Console.ReadLine();
            }
        }
    }

0 个答案:

没有答案