我在stackoverflow上寻找类似的线程并尝试调整我的代码,但它仍然不起作用所以我不妨在这里问。
他告诉我,对象引用没有设置为:
DataRow[] result = tablez.Select("Release = 1");
以下是整个代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.OleDb;
using System.IO;
using System.Data;
namespace TestExcelSelect
{
class Program
{
static void Main(string[] args)
{
string physicalPath = Path.Combine(Environment.CurrentDirectory, "Mapping.xlsx");
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter da = new OleDbDataAdapter();
DataSet ds = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + physicalPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
String query = "SELECT Release, StructuralElement FROM Mapping"; // You can use any different queries to get the data from the excel sheet
OleDbConnection conn = new OleDbConnection(connString);
if (conn.State == ConnectionState.Closed) conn.Open();
try
{
cmd = new OleDbCommand(query, conn);
da = new OleDbDataAdapter(cmd);
da.Fill(ds, "Mapping");
}
catch
{
// Exception Msg
}
finally
{
da.Dispose();
conn.Close();
}
if (ds == null)
{
Console.WriteLine("Mapping not found");
return;
}
DataTable tablez = ds.Tables["Mapping"];
DataRow[] result = table.Select("Release = 1"); // this will return one row for above data
foreach (DataRow row in tablez.Rows)
{
Console.WriteLine("{0}, {1}", row[0], row[1]);
Console.WriteLine(row["Column1"].ToString());
}
//DataTable data = ds.Tables["data"];
//string key = data.Rows[0].Field<string>("Release");
//string value = data.Rows[0].Field<string>("StructuralElement");
}
}
}
我基本上想要通过一个对象列表,将该对象列表与我的Release行进行比较,如果匹配,则将StructuralElement行写入某处。
编辑:也许我的名字失败了?
我的xslx称为Mapping
里面的工作表叫做Mapping2
这些列称为Release,StructuralElement