2012-09-20 68 views
0

幫我用我的代碼,因爲我現在不怎麼做這個簡單的任務。如何從Excel文件中選擇10個隨機行?來自excel的10個隨機行

 string filepath = @"C:\1.xlsx"; 
     OleDbConnection conn = new OleDbConnection(); 
     conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + @";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text"""; 
     OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]", conn); 
     DataSet ds = new DataSet(); 
     OleDbDataAdapter adapter = new OleDbDataAdapter(command); 
     adapter.Fill(ds); 
     showdata.DataSource = ds.Tables[0]; 
+0

你能選擇的前10行? – Doomsknight

+1

看起來您已經將Excel數據導入到DataTable中,所以對於隨機化,您已將Excel從等式中刪除。 (這是好事,分離關切和所有這些。)你有沒有嘗試隨機化呢?有一個「Random」對象可以爲你生成數字。你可以給它的行數,並要求它的10個數字,這將是行索引。 (假設你需要檢查重複索引並重新詢問另一個隨機數,因爲真正的隨機性允許重複,但聽起來你不想這麼做。) – David

+0

必須沒有dublicates,因爲在excel包含名稱,姓氏,聯繫人等列的人員列表。分享您的代碼變體。 –

回答

0

如果你創建你的Windows窗體稱爲RandomExcelRows一個DataGridView,創建一個名爲button1按鈕,並把點擊事件處理程序中下面的代碼button1

private void button1_Click(object sender, EventArgs e) 
{ 
    Excel.Range[] rows = RandomRows(10, @"C:\test\whatever.xlsx"); 

    DataTable dt = new DataTable(); 

    bool ColumnsCreated = false; 

    foreach(Excel.Range row in rows) 
    { 
     object[,] values = row.Value; 

     int columnCount = values.Length; 

     if(!ColumnsCreated) 
     { 
      for(int i = 0; i < columnCount; i++) 
      { 
       DataColumn dc = new DataColumn(String.Format("Column {0}", i)); 
       dt.Columns.Add(dc); 
       ColumnsCreated = true; 
      } 
     } 

     DataRow dr = dt.NewRow(); 

     for (int i = 0; i < columnCount; i++) 
     { 
      dr[String.Format("Column {0}", i)] = values[1,i+1]; 
     } 

     dt.Rows.Add(dr); 
    } 

    RandomExcelRows.DataSource = dt; 
} 

,然後創建一個方法名爲RandomRows包含以下內容:

private Excel.Range[] RandomRows(int randomRowsToGet, string worksheetLocation, int worksheetNumber = 1, int lowestRow = 0, int highestRow = 99) 
{ 
    Excel.Range[] rows = new Excel.Range[randomRowsToGet]; 

    Excel.Application excel = new Excel.Application(); 
    Excel.Workbook workbook = excel.Workbooks.Open(worksheetLocation); 
    Excel.Worksheet worksheet = workbook.Worksheets[worksheetNumber]; 

    List<int> rowNumbers = new List<int>(); 

    bool allUniqueNumbers = false; 

    Random random = new Random(); 

    while (!allUniqueNumbers) 
    { 
     int nextNumber = random.Next(lowestRow, highestRow); 

     if (!rowNumbers.Contains(nextNumber)) 
      rowNumbers.Add(nextNumber); 

     if (rowNumbers.Count == randomRowsToGet) 
      allUniqueNumbers = true; 
    } 

    for (int i = 0; i < randomRowsToGet; i++) 
    { 
     rows[i] = worksheet.UsedRange.Rows[rowNumbers[i]]; 
    } 

    Marshal.ReleaseComObject(excel); 

    return rows; 
} 

程序將從您指定的電子表格中隨機選取一行(這個數量由您指定),並將這些行放入您的DataGridView中。

這是非常粗糙的,需要重構,但它是你需要的基礎。您也可以從文本框中獲取包含文件位置的字符串,而不是對其進行硬編碼,這同樣適用於所需的行數以及其他參數,如最小和最大行。

同樣,你可以使用一個OpenFileDialog,使您的用戶瀏覽到您的Excel文件,等等等等

+0

哇!十分感謝!如何在WinForms中將這個Excel.Range對象數組輸出到DataGridView? –

+0

我更新了我的答案! – JMK

0

這裏是我的解決方案:

 string filepath = @"C:\1.xlsx"; 
     OleDbConnection conn = new OleDbConnection(); 
     conn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + @";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text"""; 
     OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]", conn); 
     DataSet ds = new DataSet(); 
     OleDbDataAdapter adapter = new OleDbDataAdapter(command); 
     adapter.Fill(ds); 
     // above code block is yours as is. 
     // below part is for sorting. 

     DataTable data = ds.Tables[0]; 
     data.Columns.Add(new DataColumn("Guid")); 
     for (int i = 0; i < data.Rows.Count; i++) 
     { 
      data.Rows[i].SetField("Guid", Guid.NewGuid()); 
     } 
     DataView dv = data.DefaultView; 
     dv.Sort = "Guid desc";    
     showdata.DataSource = dv.ToTable();