v C# pracujem krátko, programujem vo visual studio. Narazil som na jeden problém. Potrebujem prepojiť c# s Excelom. Úplne by mi stačilo, keby som si z Combobox-u vybral jednu z možností z Excelu stĺpca A a v textboxe by sa mi objavila príslušná bunka zo stĺpca B.
Tento kód som našiel na nete
Kód: Vybrať všetko
http://social.msdn.microsoft.com/Forums/eu/csharpgeneral/thread/c095c46e-c926-4332-8c2c-dd964bdacceaPred tým som zapal Microsofr Excel Object Library v Project -> Add Reference -> COM
Kód: Vybrať všetko
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string query = "Select Time from [Sheet1$] where Name = '" + comboBox1.SelectedItem.ToString() + "'";
ConExcel(query);
}
private void ConExcel(string query)
{
string str = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\example.xls;Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";";
try
{
OleDbConnection con = new OleDbConnection(str);
con.Open();
OleDbCommand cmd = new OleDbCommand(query, con);
string result = cmd.ExecuteScalar().ToString();
textBox1.Text = result;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
Ďakujem