使用C#获取Excel行号

时间:2016-12-18 03:01:27

标签: c# excel

我想获取我的Excel数据的行号。在这里,我有excel文件,其中包含如下数据。

我有数据:

WSID  Nominal
123   1000
456   2000
789   3000
987   4000
654   5000
321   6000

我想显示DatagRidView中显示的数据的行号。我怎么能这样做?

string koneksi = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Program-Pengisian-Uang-ATM-BCA-SOY\Program-Pengisian-Uang-ATM-BCA-SOY\bin\x86\Debug\ATM SLA Surabaya.xlsx; Extended Properties='Excel 12.0 xml;HDR=YES;'";

    private void PrintScheduleBtn_Click(object sender, EventArgs e)
    {
    Excel.Application oApp;
    Excel.Worksheet oSheetCartridge;
    Excel.Workbook oBook;

    oApp = new Excel.Application();
    oApp.Visible = true;
    oApp.DisplayAlerts = false;

    oBook = oApp.Workbooks.Open(lokasifile, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
    oSheetCartridge = oBook.Sheets["Cartridge"];

    OleDbConnection kon2 = new OleDbConnection(koneksi); //database
    OleDbCommand comm = kon2.CreateCommand();

    foreach (DataGridViewRow row in JadwalisiGV.Rows)
    {
        if (!row.IsNewRow)
        {
        kon2.Open();    
        comm.CommandText = "SELECT * FROM [Data$] WHERE [WSID] = '"+ row.Cells["WSID"].Value +"'";
        listBox1.Items.Add(); // I want to show row number of my WSID data that is shown in JadwalisiGV here
        kon2.Close();

        }
    }

    } 

2 个答案:

答案 0 :(得分:1)

您可以尝试此代码

foreach (DataGridViewRow row in JadwalisiGV.Rows)
    {
        if (!row.IsNewRow)
        {
        kon2.Open();    
        comm.CommandText = "SELECT WSID, Nominal,ROW_NUMBER() over (order by WSID) FROM [Data$] WHERE [WSID] = '"+ row.Cells["WSID"].Value +"'";
        row.HeaderCell.Value = (row.Index + 1).ToString();
        listBox1.Items.Add(); // I want to show row number of my WSID data that is shown in JadwalisiGV here
        kon2.Close();

        }
    }

答案 1 :(得分:0)

试试这样:

  foreach (DataGridViewRow row in JadwalisiGV.Rows)
    {.
     .
      int index = JadwalisiGV.Rows.IndexOf(row);
     .
     .
    }