我使用 openfiledialog 并对其进行过滤以获取:.xls、.xlsx 和 .xlsm 文件。 但我不知道下一步该怎么做,我用 firstName 和 lastName 建立了一类 worker ,我想从 excel 文件中获取数据并将其放入变量中。
这是我打开文件对话框的代码:
private void ExcelLoad_Click(object sender, EventArgs e)
{
int size = -1;
openFileDialog1.Title = "Browse Excel file";
openFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
Stream excelOpenFile= openFileDialog1.OpenFile();
}
那么我如何从这种文件中读取数据。(成功打开它但我不知道如何使用该文件并从中获取数据)。
最佳答案
您需要使用用于读取 XLS 文件的库,
引用Reading Excel files from C# & https://github.com/ExcelDataReader/ExcelDataReader
更新 1: 来自 Github,如何使用它,将包安装为 nuget 包。
It is recommended to use Nuget
Install-Package ExcelDataReader
The current binaries are still on the codeplex site, but these will not be updated going forward. If there are enough requests for separate binary hosting other than nuget then we'll come up with some other solution.
更新 2:从 Excel 数据阅读器读取代码
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
//5. Data Reader methods
while (excelReader.Read())
{
//excelReader.GetInt32(0);
}
//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();
在第 3 步之后,您将获得 DataSet 中的 Excel 数据
DataSet result = excelReader.AsDataSet();
接下来,您可以使用以下代码遍历数据集
foreach (DataColumn col in result.Table[0].Columns)
{
foreach (DataRow row in result.Table[0].Rows)
{
Console.WriteLine(row[col.ColumnName].ToString());
}
}
P.S :我使用 Table[0]
只是为了指定第一个 DataTable 或第一个 Excel 工作表中的数据。您也可以遍历各种数据表。
关于c# - 如何在 C# 中读取 .xls 和 .xlsx 以及 .xlsm 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31502226/