How to import data from one column of Excel to listbox using C#

后端 未结 1 467
萌比男神i
萌比男神i 2021-01-27 09:25

I have an openFileDialog tool. I will choose a excel file from my computer and my programme read a column (for example A column) and write my listbox on GUI. How can i do it via

1条回答
  •  再見小時候
    2021-01-27 10:00

    In order to use the OLEDB provider successfully we have to consider a few points.

    • The OLEDB provider for Excel 2003 files is different from the one used for Excel 2007/2010 files. So, the first thing we have to do is determining the Excel file format in order to select the correct provider. In the code example below I simply check the extension of the file to determine the Excel file format. Please note, that there are more elaborated methods to determine the Excel file format (e.g. via the magic bytes).

    • To select all rows of a Excel sheet we need to know the name of the Excel sheet. The standard sheet names are language dependent and could be renamed by the user. So, we need a way to determine the name of the sheets included in a Excel file to be language independent (and of course independent of renamed sheets). Fortunately, the OleDbConnection class provides a method called GetOleDbSchemaTable which allows us to get all the sheet names in an Excel file.

    • The OLEDB provider for Excel supports an extended property called HDR. Setting HDR to Yes means that the first row of a sheet contains the column titles. So, if you use column titles you should set HDR=Yes.

    So, to summarize the code sample below does the following (on button click):

    1. Determines the Excel file type based on the file extension.
    2. Selects the correct OLEDB provider based on the excel file type to build the connection string.
    3. Determines the sheet names included in the Excel file.
    4. Selects the first sheet, selects all rows and stores the rows in a DataTable called mytable.
    5. Displays all values of the first column in a listbox called listbox1.

    Code sample:

    private static bool IsExcelXmlFileFormat(string fileName)
    {
      return fileName.EndsWith("xlsx", StringComparison.OrdinalIgnoreCase);
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
      // Open your FileOpenDialog and let the user select a file...
    
      string fileName = "c:\\temp\\myexcelfile.xlsx";      
    
      OleDbConnectionStringBuilder connStringBuilder =
        new OleDbConnectionStringBuilder();
    
      connStringBuilder.DataSource = fileName;
      if (IsExcelXmlFileFormat(fileName))
      {
        // Set HDR=Yes if first row contains column titles.        
        connStringBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
        connStringBuilder.Add("Extended Properties", "Excel 8.0;HDR=NO;");        
      }
      else
      {
        connStringBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";
        connStringBuilder.Add("Extended Properties", "Excel 8.0;");        
      }
    
      DataSet data = new DataSet();
      using (OleDbConnection dbConn = new OleDbConnection(connStringBuilder.ConnectionString))
      {
        dbConn.Open();
    
        DataTable sheets = dbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);                
    
        using (OleDbCommand selectCmd = new OleDbCommand(
          String.Format("SELECT * FROM [{0}]", sheets.Rows[0]["TABLE_NAME"]), dbConn))
        {
          using (OleDbDataAdapter dbAdapter = new OleDbDataAdapter())
          {
            dbAdapter.SelectCommand = selectCmd;           
            dbAdapter.Fill(data, "mytable");                       
          }
        }
      }
    
      // To enumerate all rows use the following code.
      // foreach (DataRow row in data.Tables["mytable"].Rows)
      // {
      //   Console.Out.WriteLine(row[0]);
      // }
    
      // Display the values of column 0 in a listbox called listBox1.
      listBox1.ValueMember = data.Tables["mytable"].Columns[0].ColumnName;
      listBox1.DisplayMember = data.Tables["mytable"].Columns[0].ColumnName;
      listBox1.DataSource = data.Tables["mytable"];             
    }
    

    0 讨论(0)
提交回复
热议问题