我需要编写一个sql查询(在c#中),从C19开始,在仅“C”列中选择excel表数据。但我无法指定结束单元格编号,因为更多数据将添加到列中。因此,我需要知道如何指定列的结尾。请帮忙。我已经提到了我正在使用的查询。我附上了我正在使用的excel表格的图像!。我附加了输出datagridview!
//Generte Oracle Datatable
OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;"
+ @"Data Source=" + textBox1.Text + ";" + @"Extended Properties=""Excel 12.0 Macro;HDR=Yes""");
conn.Open();
OleDbCommand ccmd = new OleDbCommand(@"Select * From [SPAT$]", conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(ccmd);
DataTable Oracle = new DataTable();
adapter.Fill(Oracle);
for (int y = 19; y < Oracle.Rows.Count; y++)
{
var value = Oracle.Rows[y][3].ToString();
}
dataGridView1.DataSource = Oracle.AsEnumerable().Where((row, index) => index > 3).CopyToDataTable();
答案 0 :(得分:1)
第一种方法,使用OLE查询:
OleDbCommand ccmd = new OleDbCommand(@"Select * From [SPAT$]", conn);
OleDbDataAdapter da = new OleDbDataAdapter(ccmd);
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 19; i < dt.Rows.Count; i++)
{
var value = dt.Rows[i][3].ToString(); // here 3 refers to column 'C'
}
适用于基于标准的DataTable
dataGridView1.DataSource = dt.AsEnumerable()
.Where((row, index) => index >= 19)
.CopyToDataTable();
仅适用于“C”列
dataGridView1.DataSource = dt.AsEnumerable()
.Where((row, index) => index >= 19)
.Select(t => t[3].ToString()).ToList();
第二种方法,使用Excel COM对象:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("path to book");
Excel.Worksheet xlSheet = xlWorkbook.Sheets[1]; // get first sheet
Excel.Range xlRange = xlSheet.UsedRange; // get the entire used range
int numberOfRows = xlRange.Rows.Count;
List<string> columnValue = new List<string>();
// loop over each column number and add results to the list
int c = 3; // Column 'C'
for(int r = 19; r <= numberOfRows; r++)
{
if(xlRange.Cells[r,c].Value2 != null) // ADDED IN EDIT
{
columnValue.Add(xlRange.Cells[r,c].Value2.ToString());
}
}