在 C# WPF 应用程序中打开和读取 Excel 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32643544/
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-09-13 13:25:23  来源:igfitidea点击:

Open and read Excel file in C# WPF application

c#wpfexcel

提问by crossemup

I am trying to open an Excel file located on my local computer and take out a few values from it. The values are a mix of strings and numbers located in different cells. The Excel file will be opened using openFileDialog. I am using C# and developing a desktop application (WPF). This is the code I am implementing:

我正在尝试打开位于本地计算机上的 Excel 文件并从中取出一些值。这些值是位于不同单元格中的字符串和数字的混合。Excel 文件将使用openFileDialog. 我正在使用 C# 并开发桌面应用程序 (WPF)。这是我正在实施的代码:

     Excel.Application excelApp = new Excel.Application();
        string workbookPath = "C:/Users/b_prashanth/Documents/26. Workload Modeling generic template.xlsx";
        Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath);
        Excel.Sheets excelSheets = excelWorkbook.Worksheets;
        string currentSheet = "Sheet1";
        Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
        Excel.Range excelCell =
    (Excel.Range)excelWorksheet.get_Range("A1", "A1");

回答by Charles Clayton

What about something like this? What's the problem you've faced?

像这样的事情怎么办?你遇到的问题是什么?

Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".xlsx";
bool? result = dlg.ShowDialog();

if (result != true) return;

string workbookPath = dlg.FileName;

Excel.Application excelApp = new Excel.Application();
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath);
Excel.Worksheet sheet = excelWorkbook.Sheets["Sheet1"] as Excel.Worksheet; 

if (sheet == null) return;

Excel.Range range = sheet.get_Range("A1", Missing.Value)

var yourValue = range.Text;

回答by Thorsten Dittmar

Instead of Office interop, which requires Office to be installed on the machine, you could access the Excel sheet like a database using the ADO driver.

您可以使用 ADO 驱动程序像访问数据库一样访问 Excel 工作表,而不是需要在计算机上安装 Office 的 Office 互操作。

This has been documented here many times and would be very easy.

这已在此处记录了很多次,并且非常容易。

回答by Mikhail Tulubaev

I think, OpenXML SDK should help you.
http://www.codeproject.com/Articles/670141/Read-and-Write-Microsoft-Excel-with-Open-XML-SDK
It's available via nuget - DocumentFormat.OpenXML, and hereyou can find all classes and algorithms, what you needed

我认为,OpenXML SDK 应该可以帮助您。
http://www.codeproject.com/Articles/670141/Read-and-Write-Microsoft-Excel-with-Open-XML-SDK
可通过 nuget - DocumentFormat.OpenXML 获得,在这里您可以找到所有类和算法,你需要什么