实例介绍
【实例截图】
【核心代码】
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.Data.OleDb;
using System.Data.SqlClient;
using System.Reflection;
using System.IO;
namespace FrmMain
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OpenFileDialog dialog = new OpenFileDialog();
private void button1_Click(object sender, EventArgs e)
{
if (TableName.Text == "")
{
MessageBox.Show("请选择要表名", "提示");
TableName.Focus();
return;
}
if (textBox2.Text=="")
{
MessageBox.Show("请选择要导入的文件", "提示");
textBox2.Focus();
return;
}
string table = TableName.Text.Trim();
string connString = "server=localhost;uid=sa;pwd=123;database=TSHIS_PATIENT";
string url = textBox2.Text.Trim();
TransferData(url, table, connString);
}
private void button2_Click(object sender, EventArgs e)
{
//try
//{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel文件|*.xlsx|所有文件|*.*";
ofd.Title = "打开文件夹";
string b = "";
ofd.InitialDirectory = "c:\\";
ofd.FilterIndex = 1;
if (ofd.ShowDialog() == DialogResult.OK) //如果点击的是打开文件
{
this.textBox2.Text = ofd.FileName; //获取全路径文件名
b = this.textBox2.Text;
}
//string tablename = gete(b);
//string TSql = "SELECT*FROM[" tablename "]";
//DataTable table = etds(b, TSql).Tables[0];
//SqlBulkCopyInsert(sqlConnStr, tablename, table);
//dataGridView1.DataSource = table;
//将DataSet类对象table中存储的excel中的值放入
//}
//catch (Exception ex)
//{
// MessageBox.Show(ex.Message);
//}
//dialog.Filter = "所有文件(*.xls)|*.xls";
//if (dialog.ShowDialog() == DialogResult.OK)
//{
// this.textBox2.Text = dialog.FileName;
//}
}
/// <summary>
/// 获得表名
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string gete(string path)
{
string tablename = null;
if (File.Exists(path))
{
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
path ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"))
{
conn.Open();
tablename = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0][2].ToString().Trim();
}
}
return tablename;
}
/// <summary>
/// 使用OleDbDataAdapter对象mycommand将查询结果填充到DataTable对象ds中
/// </summary>
/// <param name="filename"></param>
/// <param name="tsql"></param>
/// <returns></returns>
public static DataSet etds(string filename, string tsql)
{
DataSet ds;
string strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
filename ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
OleDbConnection myConn = new OleDbConnection(strcon);
string strcom = tsql;
myConn.Open();
OleDbDataAdapter mycommand = new OleDbDataAdapter(strcom, myConn);
ds = new DataSet();
mycommand.Fill(ds);
//使用OleDbDataAdapter对象mycommand将查询结果填充到DataTable对象ds中
myConn.Close();
return ds;
}
public void TransferData(string excelFile, string sheetName, string connectionString)
{
DataSet ds = new DataSet();
try
{
//获取全部数据
string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" "data source=" excelFile ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'";
//string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" "Data Source=" excelFile ";" "Extended Properties='Excel 12.0;Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
//包含excel中表名的字符串数组
string[] strTableNames = new string[dtSheetName.Rows.Count];
for (int k = 0; k < dtSheetName.Rows.Count; k )
{
strTableNames[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
}
strExcel = string.Format("select * from [" strTableNames[0] "]", sheetName);
myCommand = new OleDbDataAdapter(strExcel, strConn);
myCommand.Fill(ds, sheetName);
//如果目标表不存在则创建
string strSql = string.Format("if object_id('{0}') is null create table {0}(", sheetName);
foreach (System.Data.DataColumn c in ds.Tables[0].Columns)
{
strSql = string.Format("[{0}] varchar(255),", c.ColumnName);
}
strSql = strSql.Trim(',') ")";
using (System.Data.SqlClient.SqlConnection sqlconn = new System.Data.SqlClient.SqlConnection(connectionString))
{
sqlconn.Open();
System.Data.SqlClient.SqlCommand command = sqlconn.CreateCommand();
command.CommandText = strSql;
command.ExecuteNonQuery();
sqlconn.Close();
}
//用bcp导入数据
using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(connectionString))
{
bcp.SqlRowsCopied = new System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);
bcp.BatchSize = 1000;//每次传输的行数
bcp.NotifyAfter = 1;//进度提示的行数
bcp.DestinationTableName = sheetName;//目标表
bcp.WriteToServer(ds.Tables[0]);
string tablename = TableName.Text.Trim();
MessageBox.Show("表 [" tablename "]导入成功", "提示");
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
//进度显示
void bcp_SqlRowsCopied(object sender, System.Data.SqlClient.SqlRowsCopiedEventArgs e)
{
//this.Text = e.RowsCopied.ToString();
this.textBox1.Text = e.RowsCopied.ToString();
this.Update();
}
private void button3_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论