0

我需要编写一个 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();                
4

1 回答 1

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());
    }
}
于 2012-10-17T04:53:51.020 回答