using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 讀取excel到datagridview
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
/// <summary>
/// 選擇文件,並且讀取excel中sheet
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
try
{
//獲取Excel文件路徑和名稱
OpenFileDialog odXls = new OpenFileDialog();
// 指定相應的打開文檔的目錄
odXls.InitialDirectory = "C://";
// 設置文件格式
odXls.Filter = "Excel files (*.xls)|*.xls|Excel files (*.xlsx)|*.xlsx";
odXls.FilterIndex = 2;
odXls.RestoreDirectory = true;
if (odXls.ShowDialog() == DialogResult.OK)
{
txtFilePath.Text = odXls.FileName;
OleDbConnection oledbConn = null;
string sConnString = "provider=Microsoft.ACE.OLEDB.12.0;data source=" + odXls.FileName + ";Extended Properties=Excel 12.0;Persist Security Info=False";
oledbConn = new OleDbConnection(sConnString);
oledbConn.Open();
DataTable dt = oledbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
combox1.Items.Clear();
foreach (DataRow dr in dt.Rows)
{
combox1.Items.Add((String)dr["TABLE_NAME"]);
}
if (combox1.Items.Count > 0)
combox1.SelectedIndex = 0;
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
richTextBox1.Text = Ex.Message;
}
}
/// <summary>
/// 讀取文件具體內容
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
string connectionString = @"Data Source=ZHANGP;Initial Catalog=Test_Z;Integrated Security=True";
OleDbConnection ole = null;
OleDbDataAdapter da = null;
DataTable dt = null;
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=" + txtFilePath.Text.Trim() + ";"
+ "Extended Properties=Excel 12.0";
string sTableName = combox1.Text.Trim();
string strExcel = "select * from [" + sTableName + "]";
try
{
ole = new OleDbConnection(strConn);
ole.Open();
da = new OleDbDataAdapter(strExcel, ole);
dt = new DataTable();
da.Fill(dt);
using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(connectionString))
{
bcp.BatchSize = 1000;//每次傳輸的行數
bcp.DestinationTableName = "SA_CusTotal";//目標表
bcp.WriteToServer(dt);
MessageBox.Show("導入完成!");
}
//爲datagridview設置數據源
this.xlsExpData.DataSource = dt;
ole.Close();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
finally
{
if (ole != null)
ole.Close();
}
}
//進度顯示
void bcp_SqlRowsCopied(object sender, System.Data.SqlClient.SqlRowsCopiedEventArgs e)
{
this.Text = e.RowsCopied.ToString();
this.Update();
}
}
}