Convert Excel Range to ADO.NET DataSet or DataTable, etc

后端 未结 5 1497
深忆病人
深忆病人 2020-12-19 11:39

I have an Excel spreadsheet that will sit out on a network share drive. It needs to be accessed by my Winforms C# 3.0 application (many users could be using the app and hit

5条回答
  •  眼角桃花
    2020-12-19 12:32

    I don't know what type of data you have.But for an excel data like shown in this link http://www.freeimagehosting.net/image.php?f8d4ef4173.png, you can use the following code to load into data table.

        private void Form1_Load(object sender, EventArgs e)
        {   
           try
           {        
                DataTable sheetTable = loadSingleSheet(@"C:\excelFile.xls", "Sheet1$");
                dataGridView1.DataSource = sheetTable;
           }
           catch (Exception Ex)
           {
                MessageBox.Show(Ex.Message, "");
           }  
        }        
    
        private OleDbConnection returnConnection(string fileName)
        {
            return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"");
        }
    
        private DataTable loadSingleSheet(string fileName, string sheetName)
        {           
            DataTable sheetData = new DataTable();
            using (OleDbConnection conn = this.returnConnection(fileName))
            {
               conn.Open();
               // retrieve the data using data adapter
               OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "]", conn);
                sheetAdapter.Fill(sheetData);
            }                        
            return sheetData;
        }
    

提交回复
热议问题