C# 在wpf应用程序中读取excel文件内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13320990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:12:02  来源:igfitidea点击:

Read excel file content in wpf application

c#wpfexcelexport-to-excelimport-from-excel

提问by SST

I want to read excel file in my C#,WPF application. which is running on different machines having different versions of excels(some has excel-2003 while some machines have excel-2007 etc and some machines doesn't have any office installed at all). I want to read excel file content regardless of with/without any excel versions/packages installed on the target machines.

我想在我的 C#、WPF 应用程序中读取 excel 文件。它在具有不同版本的 excels 的不同机器上运行(有些机器有 excel-2003,有些机器有 excel-2007 等,有些机器根本没有安装任何办公室)。无论目标计算机上是否安装了任何 excel 版本/包,我都想读取 excel 文件内容。

I am currently using Microsoft.Office.Interop.Excel to read data from excel file but on running my app on target machine which doesn't have any office installed, my application doesn't work.

我目前正在使用 Microsoft.Office.Interop.Excel 从 excel 文件中读取数据,但是在没有安装任何办公室的目标机器上运行我的应用程序时,我的应用程序不起作用。

How can I do it? I am doing it the following way, added namespaces

我该怎么做?我按照以下方式进行操作,添加了命名空间

 using Excel = Microsoft.Office.Interop.Excel;

Here comes the method's body:

这是方法的主体:

Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            Excel.Range range;
            xlWorkBook = xlApp.Workbooks.Open(_filePath);
            List<string> Folders = new List<string>();
            try
            {
                xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
                range = xlWorkSheet.UsedRange;


                for (int cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
                {
                    Folders.Add(((range.Cells[1, cCnt] as Excel.Range).Value).ToString());
                }
            }
            catch (Exception ex)
            {
                //some error msg
            }
            finally
            {
                xlWorkBook.Close();
                xlApp.Quit();
            }
            return Folders;
        }

采纳答案by Legoless

There are some solutions already here:

这里已经有一些解决方案:

How to open an Excel file in C#?

如何在 C# 中打开 Excel 文件?

If you are developing open source application, there are some third party libraries, so take a look at the following:

如果你正在开发开源应用程序,有一些第三方库,所以看看以下内容: