[英]How do I import specific excel cell values to existing datagridview cells in C#
[英]How to import specific cells of an Excel file into datagridview using c#
我想将Excel文件的特定单元格导入到datagridview的特定单元格中。
我在这里遵循了许多导入Excel表的教程,但是由于我只想在datagridview的特定位置使用特定的单元格,因此我修改了代码。
代替: DataGridView1.DataSource = dt;
我做了: dataGridView1.Rows[0].Cells[0].Value = dt;
但这不起作用。
有人可以帮我吗?
谢谢
这是代码:
string constr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + textBox1.Text + @";Extended Properties=""Excel 12.0 Macro;HDR=YES;ImportMixedTypes=Text;TypeGuessRows=0""";
OleDbConnection con = new OleDbConnection(constr);
//specific cell 1 - product "code"
OleDbDataAdapter sda = new OleDbDataAdapter("Select * From [ARTIGOS$A" + textBox3.Text + ":A" + textBox3.Text + "]", con);
//specific cell 2 - product "description"
OleDbDataAdapter sdb = new OleDbDataAdapter("select * From [ARTIGOS$B" + textBox3.Text + ":B" + textBox3.Text + "]", con);
//specific cell 3 - product "price"
OleDbDataAdapter sdc = new OleDbDataAdapter("Select * From [ARTIGOS$I" + textBox3.Text + ":I" + textBox3.Text + "]", con);
DataTable dt = new DataTable();
DataTable dt2 = new DataTable();
DataTable dt3 = new DataTable();
sda.Fill(dt);
sdb.Fill(dt2);
sdc.Fill(dt3);
dataGridView1.Rows.Add();
dataGridView1.Rows[0].Cells[0].Value = dt;
dataGridView1.Rows[0].Cells[1].Value = dt2;
dataGridView1.Rows.Add();
dataGridView1.Rows[0].Cells[2].Value = textBox2.Text;
dataGridView1.Rows[0].Cells[3].Value = dt3;
请参阅以下代码:
private Excel.Application App;
private Excel.Range rng = null;
private void button1_Click_1(object sender, EventArgs e) {
OpenFileDialog OFD = new OpenFileDialog();
OFD.Filter = "Excel Worksheets|*.xls;*.xlsx;*.xlsm;*.csv";
if (OFD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
App = new Excel.Application();
App.Visible = true;
App.Workbooks.Open(OFD.FileName);
}
else { return; }
try { rng = (Excel.Range)App.InputBox("Please select a range", "Range Selection", Type: 8); }
catch { } // user pressed cancel on input box
if (rng != null) {
DataTable dt = ConvertRangeToDataTable();
if (dt != null) { dataGridView1.DataSource = dt; }
}
_Dispose();
}
private DataTable ConvertRangeToDataTable() {
try {
DataTable dt = new DataTable();
int ColCount = rng.Columns.Count;
int RowCount = rng.Rows.Count;
for (int i = 0; i < ColCount; i++) {
DataColumn dc = new DataColumn();
dt.Columns.Add(dc);
}
for (int i = 1; i <= RowCount; i++) {
DataRow dr = dt.NewRow();
for (int j = 1; j <= ColCount; j++) { dr[j - 1] = rng.Cells[i, j].Value2; }
dt.Rows.Add(dr);
}
return dt;
}
catch { return null; }
}
private void _Dispose() {
try { Marshal.ReleaseComObject(rng); }
catch { }
finally { rng = null; }
try { App.Quit(); Marshal.ReleaseComObject(App); }
catch { }
finally { App = null; }
}
有关将特定范围从xls文件导入到gridview的详细信息,请参见以下问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.