[英]How to import specific cells of an Excel file into datagridview using c#
[英]How to import an excel file to DataGridView in C#
我正在努力將Excel文件導入到DataGridView
。 但是,如何導入具有DataGridView
選定行和列的Excel文件? 我只有將整個excel文件加載到DataGridView
,這是C#中的新手
我打開對話框文件並搜索excel文件,假設我的數據以C:34,D:34
和E:34
的一列或包含EmploayeeName的數據開頭,然后選擇前24行並將其加載到我的DataGridView
。
預先感謝您的幫助! 這是我唯一的東西:(
private void OpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Select file";
fdlg.InitialDirectory = @"c:\";
fdlg.FileName = txtFileName.Text;
fdlg.Filter = "Excel Sheet(*.xlsx)|*.xlsx|All Files(*.*)|*.*";
fdlg.FilterIndex = 1;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
path = textBox1.Text;
txtFileName.Text = fdlg.FileName;
Application.DoEvents();
}
}
private void LoadExcel_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet DtSet;
System.Data.OleDb.OleDbDataAdapter MyCommand;
MyConnection = new System.Data.OleDb.OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "Net-informations.com");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dgrdReciver.DataSource = DtSet.Tables[0];
MyConnection.Close();
}
好吧,我將從獲取文件的路徑開始,然后使用如下所示的文件流:
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), file.Name);
using (Stream fileStream = File.OpenWrite(path))
{
// do what you want with the file stream.
sftp.DownloadFile(remoteDirectory + "/" + file.Name, fileStream);
}
我什至將這些數據放入SQL Server,因此更容易放入數據網格視圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.