1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
namespace projetBE
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void openFileButton_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string filePath = openFileDialog1.FileName;
string extension = Path.GetExtension(filePath);
string Excel03ConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";
string Excel07ConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";
string header = rbHeaderYes.Checked ? "YES" : "NO";
string conStr;
conStr = string.Empty;
switch (extension)
{
case ".xls": //Excel 97-03
conStr = string.Format(Excel03ConString, filePath, header);
break;
case ".xlsx": //Excel 07
conStr = string.Format(Excel07ConString, filePath, header);
break;
}
//Get all worksheet names from the Excel file selected using GetSchema of an OleDbConnection
OleDbConnection connection = new OleDbConnection(conStr);
connection.Open();
DataTable tables = connection.GetSchema("Tables", new String[] { null, null, null, "TABLE" });
connection.Dispose();
//Add each table name to the combo box
if (tables != null && tables.Rows.Count > 0)
{
worksheetsComboBox.Items.Clear();
foreach (DataRow row in tables.Rows)
{
worksheetsComboBox.Items.Add(row["TABLE_NAME"].ToString());
}
}
}
private void worksheetsComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
//Display the data from the selected Worksheet
string filePath = openFileDialog1.FileName;
string extension = Path.GetExtension(filePath);
string Excel03ConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";
string Excel07ConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'";
string header = rbHeaderYes.Checked ? "YES" : "NO";
string conStr;
conStr = string.Empty;
switch (extension)
{
case ".xls": //Excel 97-03
conStr = string.Format(Excel03ConString, filePath, header);
break;
case ".xlsx": //Excel 07
conStr = string.Format(Excel07ConString, filePath, header);
break;
}
OleDbDataAdapter adapter = new OleDbDataAdapter(String.Format("SELECT * FROM [{0}]", worksheetsComboBox.SelectedItem.ToString()), conStr);
DataTable currentSheet = new DataTable();
adapter.Fill(currentSheet);
adapter.Dispose();
excelDataGridView.DataSource = currentSheet;
}
}
} |
Partager