我想从excel文件中读取特定列并选择每个值并使用c#将其放入查询中。我编写了一个代码来读取excel文件并在datagridview中显示它,但在读取特定列时卡住了。
需要一些帮助。以下是代码。
private void button1_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel Workbook|*.xls", ValidateNames = true })
{
if (ofd.ShowDialog() == DialogResult.OK)
{
FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
IExcelDataReader reader = ExcelReaderFactory.CreateBinaryReader(fs);
var conf = new ExcelDataSetConfiguration
{
ConfigureDataTable = _ => new ExcelDataTableConfiguration
{
UseHeaderRow = true
}
};
dataSet = reader.AsDataSet(conf);
cboSheet.Items.Clear();
foreach (DataTable dt in dataSet.Tables)
cboSheet.Items.Add(dt.TableName);
reader.Close();
}
}
}
private void cboSheet_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView.DataSource = dataSet.Tables[cboSheet.SelectedIndex];
}
答案 0 :(得分:0)
你知道excel文件每次都一样吗?如果您可以确保文件始终保持不变而不进行任何列修改,则可以使用OfficeOpenXml
包执行以下操作。
public IEnumerable<string> ReadFile(string path)
{
using(var file = new FileStream(path, FileMode.Open))
using(var memory = new MemoryStream())
{
file.CopyTo(memory);
using(var package = new ExcelPackage(memory))
if(package.Workbook.Worksheets.Count != 0)
foreach(ExcelWorksheet worksheet in package.Workbook.Worksheets)
for(var row = 0; worksheet.Dimension.Start.Row; row <= worksheet.Dimension.End.Row; row++)
yield return worksheet.Cells[row, 2].Value;
}
}
为简洁起见,我没有抽象,你可以通过分离多个循环来使代码更清晰,对于工作表然后是行。如您所见,“2”表示指定的列。但是这会给你一个集合,你可以迭代转储到你的查询中进行处理。
答案 1 :(得分:0)
您可以使用ExcelDataReader,这将为您提供DataTable
或者您可以使用OleDbCommand
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelPath + "; Extended Properties = 'Excel 12.0;HDR=YES;';");
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = SELECT [Colum1], [Colum2] FROM [Sheet1$];
OleDbDataReader reader = cmd.ExecuteReader();