嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 2 元微信扫码支付:2 元
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
C#所有导入导出功能,包括TXT导入,TXT导入出,EXCEL导入,EXCEK导出。-C# All import and export functions, including TXT import, TXT import out, EXCEL Import, EXCEK export.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
namespace ExpImpProj
{
public partial class Form1 : Form
{
private SMOHelper smoHelper = null;
public Form1()
{
InitializeComponent();
}
public static void ImportAccessToDataGridView(DataGridView dataGridview1)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Microsoft Access 文件(*.mdb)|*.mdb";
openFileDialog.Title = "选择Access文件";
if (DialogResult.Cancel == openFileDialog.ShowDialog())
{
return;
}
string AccessPath = openFileDialog.FileName;
string ConnectionAccess = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" AccessPath ";";
OleDbConnection conn = new OleDbConnection(ConnectionAccess);
conn.Open();
string tablename = "";
DataTable dt = conn.GetSchema("Tables");//获取ACCESS数据库中所有的表\查询\宏\窗体\模块
for (int i = 0; i < dt.Rows.Count; i )
{
if (dt.Rows[i].ItemArray[3].ToString() == "TABLE")//判断是否是用户表
{
tablename = dt.Rows[i].ItemArray[2].ToString();
}
}
dataGridview1.Rows.Clear();
dataGridview1.Columns.Clear();
OleDbDataAdapter adp = new OleDbDataAdapter("Select * from " tablename, conn);
DataSet ds = new DataSet();
adp.Fill(ds, "Book1");
dataGridview1.DataSource = ds.Tables[0].DefaultView;
conn.Close();
MessageBox.Show("导入完成");
}
public static void ExportDataGridViewToAccess(DataGridView dataGridview1)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Access files (*.mdb)|*.mdb";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出Access文件到";
if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
{
return;
}
string AccessPath = saveFileDialog.FileName;
DeleteFile(AccessPath); //文件存在则删除;
ADOX.CatalogClass cat = new ADOX.CatalogClass();
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" AccessPath ";"); //创建数据库文件
MessageBox.Show("数据库:" AccessPath "已经创建成功!");
OleDbParameter[] parm = new OleDbParameter[dataGridview1.ColumnCount];
string ConnectionAccess = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" AccessPath ";";
OleDbConnection conn = new OleDbConnection(ConnectionAccess);
conn.Open();
OleDbCommand objCmd = new OleDbCommand();
objCmd.Connection = conn;
//建立表结构
string CommTitleTxt = "";
CommTitleTxt = "CREATE TABLE Table1(";
//写标题
for (int i = 0; i < dataGridview1.ColumnCount; i )
{
if (i > 0)
{
CommTitleTxt = " varchar,";
}
CommTitleTxt = dataGridview1.Columns[i].HeaderText;
}
CommTitleTxt = " varchar)";
objCmd.CommandText = CommTitleTxt;
objCmd.ExecuteNonQuery();
//建立插入动作的Command
string CommContextstr = "";
CommContextstr = "INSERT INTO Table1(";
for (int j = 0; j < dataGridview1.ColumnCount; j )
{
if (j != 0)
CommContextstr = ",";
CommContextstr = dataGridview1.Columns[j].HeaderText;
}
CommContextstr = ")";
CommContextstr = " Values(";
for (int j = 0; j < dataGridview1.ColumnCount; j )
{
if (j != 0)
CommContextstr = ",";
CommContextstr = "@" dataGridview1.Columns[j].HeaderText;
}
CommContextstr = ")";
objCmd.CommandText = CommContextstr;
for (int k = 0; k < dataGridview1.ColumnCount; k )
{
parm[k] = new OleDbParameter("@" dataGridview1.Columns[k].HeaderText, OleDbType.VarChar);
objCmd.Parameters.Add(parm[k]);
}
////遍历DataGridView将数据插入新建的Access文件中
for (int j = 0; j < dataGridview1.Rows.Count - 1; j )
{
for (int k = 0; k < dataGridview1.Columns.Count; k )
{
if (dataGridview1.Rows[j].Cells[k].Value != null)
parm[k].Value = dataGridview1.Rows[j].Cells[k].Value.ToString();
}
objCmd.ExecuteNonQuery();
System.Windows.Forms.Application.DoEvents();
}
conn.Close();
MessageBox.Show("完成导出");
// Provider=Microsoft.Jet.OLEDB.4.0;Data Source="C:\Documents and Settings\Administrator\桌面\db1.mdb"
}
public static void ExportDataGridViewToWord(DataGridView dataGridview1)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "WORD files (*.DOC)|*.DOC";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出WORD文件到";
if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
{
return;
}
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
string str = "";
try
{
//写标题
for (int i = 0; i < dataGridview1.ColumnCount; i )
{
if (i > 0)
{
str = "\t";
}
str = dataGridview1.Columns[i].HeaderText;
}
sw.WriteLine(str);
//写内容
for (int j = 0; j < dataGridview1.Rows.Count; j )
{
string tempStr = "";
for (int k = 0; k < dataGridview1.Columns.Count; k )
{
if (k > 0)
{
tempStr = "\t";
}
if (dataGridview1.Rows[j].Cells[k].Value != null)
tempStr = dataGridview1.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
MessageBox.Show("完成导出");
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
public static void ImportExcelToDataGridView(DataGridView dataGridview1)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Microsoft Excel 文件(*.xls)|*.xls";
openFileDialog.Title = "选择Excel文件";
if (DialogResult.Cancel == openFileDialog.ShowDialog())
{
return;
}
string ExcelPath = openFileDialog.FileName;
// txtExcelPath.Text = ExcelPath;
string ConnectionExcel = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" ExcelPath ";" "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(ConnectionExcel);
conn.Open();
System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
dataGridview1.Rows.Clear();
dataGridview1.Columns.Clear();
string tableName = schemaTable.Rows[0][2].ToString().Trim(new char[] { '$', '\'' });
OleDbDataAdapter adp = new OleDbDataAdapter("Select * from [" tableName "$]", conn);
DataSet ds = new DataSet();
adp.Fill(ds, "Book1");
dataGridview1.DataSource = ds.Tables[0].DefaultView;
conn.Close();
MessageBox.Show("导入完成");
}
public static void ExportDataGridViewToTXT(DataGridView dataGridview1)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "TXT files (*.txt)|*.txt";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出TXT文件到";
if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
{
return;
}
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
string str = "";
try
{
//写标题
for (int i = 0; i < dataGridview1.ColumnCount; i )
{
if (i > 0)
{
str = "\t";
}
str = dataGridview1.Columns[i].HeaderText;
}
sw.WriteLine(str);
//写内容
for (int j = 0; j < dataGridview1.Rows.Count; j )
{
string tempStr = "";
for (int k = 0; k < dataGridview1.Columns.Count; k )
{
if (k > 0)
{
tempStr = "\t";
}
if (dataGridview1.Rows[j].Cells[k].Value != null)
tempStr = dataGridview1.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
MessageBox.Show("完成导出");
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
public static void ExportDataGridViewToExcel2(DataGridView dataGridview1)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出Excel文件到";
if (saveFileDialog.ShowDialog() != DialogResult.OK)
return;
string FileName = saveFileDialog.FileName;
DeleteFile(FileName); //文件已存在,则删除;
OleDbParameter[] parm = new OleDbParameter[dataGridview1.ColumnCount];
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" FileName ";" "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
OleDbCommand objCmd = new OleDbCommand();
objCmd.Connection = conn;
//建立表结构
string CommTitleTxt = "";
CommTitleTxt = "CREATE TABLE Sheet1(";
//写标题
for (int i = 0; i < dataGridview1.ColumnCount; i )
{
if (i > 0)
{
CommTitleTxt = " varchar,";
}
CommTitleTxt = dataGridview1.Columns[i].HeaderText;
}
CommTitleTxt = " varchar)";
objCmd.CommandText = CommTitleTxt;
objCmd.ExecuteNonQuery();
//建立插入动作的Command
string CommContextstr = "";
CommContextstr = "INSERT INTO Sheet1(";
for (int j = 0; j < dataGridview1.ColumnCount; j )
{
if (j != 0)
CommContextstr = ",";
CommContextstr = dataGridview1.Columns[j].HeaderText;
}
CommContextstr = ")";
CommContextstr = " Values(";
for (int j = 0; j < dataGridview1.ColumnCount; j )
{
if (j != 0)
CommContextstr = ",";
CommContextstr = "@" dataGridview1.Columns[j].HeaderText;
}
CommContextstr = ")";
objCmd.CommandText = CommContextstr;
for (int k = 0; k < dataGridview1.ColumnCount; k )
{
parm[k] = new OleDbParameter("@" dataGridview1.Columns[k].HeaderText, OleDbType.VarChar);
objCmd.Parameters.Add(parm[k]);
}
////遍历DataGridView将数据插入新建的Excel文件中
for (int j = 0; j < dataGridview1.Rows.Count - 1; j )
{
for (int k = 0; k < dataGridview1.Columns.Count; k )
{
if (dataGridview1.Rows[j].Cells[k].Value != null)
parm[k].Value = dataGridview1.Rows[j].Cells[k].Value.ToString();
}
objCmd.ExecuteNonQuery();
System.Windows.Forms.Application.DoEvents();
}
conn.Close();
MessageBox.Show("完成导出");
}
public static void ExportDataGridViewToExcel(DataGridView dataGridview1)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出Excel文件到";
saveFileDialog.ShowDialog();
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
string str = "";
try
{
//写标题
for (int i = 0; i < dataGridview1.ColumnCount; i )
{
if (i > 0)
{
str = "\t";
}
str = dataGridview1.Columns[i].HeaderText;
}
sw.WriteLine(str);
//写内容
for (int j = 0; j < dataGridview1.Rows.Count; j )
{
string tempStr = "";
for (int k = 0; k < dataGridview1.Columns.Count; k )
{
if (k > 0)
{
tempStr = "\t";
}
if (dataGridview1.Rows[j].Cells[k].Value != null)
tempStr = dataGridview1.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
MessageBox.Show("完成导出");
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
public static void ImportTxtToView(DataGridView DataGridview1)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "文本文件(*.txt)|*.txt";
openFileDialog.Title = "选择文本文件";
if (DialogResult.Cancel == openFileDialog.ShowDialog())
{
return;
}
string filename = openFileDialog.FileName;
//打开文件并显示其内容
StreamReader reader = null;
try
{
reader = new StreamReader(filename);
DataTable dt = new DataTable();
DataRow row;
int linenum = 0;
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
if (linenum == 0)
dt = MakeNamesTable(line); //首行为标题;
else
{
row = dt.NewRow();
int i = 0;
string[] tmpstrs = line.Split('\t');
foreach (string tmpstr in tmpstrs)
{
row[i] = tmpstr;
i ;
}
dt.Rows.Add(row);
}
linenum ;
}
DataGridview1.DataSource = dt;
}
catch (IOException e)
{
MessageBox.Show(e.Message);
}
finally
{
if (reader != null)
reader.Close();
}
}
public static DataTable MakeNamesTable(string linestr)
{
// Create a new DataTable titled 'Names.'
DataTable namesTable = new DataTable("Names");
string[] tmpstrs = linestr.Split('\t');
DataColumn[] idColumn = new DataColumn[tmpstrs.Length];
int i = 0;
foreach (string tmpstr in tmpstrs)
{
idColumn[i] = new DataColumn();
idColumn[i].DataType = System.Type.GetType("System.String");
idColumn[i].ColumnName = tmpstr;
namesTable.Columns.Add(idColumn[i]);
i ;
}
// Return the new DataTable.
return namesTable;
}
public static DataSet SqlQuery(string SqlStr, string connstr)
{
// Connectionstring "Data Source=JUNCHENG-AAE091;Initial Catalog=model;Integrated Security=True";
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connstr;
try
{
conn.Open();
SqlDataAdapter adap = new SqlDataAdapter(SqlStr, conn);
adap.Fill(ds, "Import");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
conn.Close();
}
return ds;
}
public static void ExportSqlToTxt(string Sqlstr, string connstr)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "TXT files (*.txt)|*.txt";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出TXT文件到";
if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
{
return;
}
DataSet ds = SqlQuery(Sqlstr, connstr); //获取SQL语句的结果集
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
string str = "";
try
{
//写标题
for (int i = 0; i < ds.Tables[0].Columns.Count; i )
{
if (i > 0)
{
str = "\t";
}
str = ds.Tables[0].Columns[i].ColumnName;
}
sw.WriteLine(str);
//写内容
for (int j = 0; j < ds.Tables[0].Rows.Count; j )
{
string tempStr = "";
for (int k = 0; k < ds.Tables[0].Columns.Count; k )
{
if (k > 0)
{
tempStr = "\t";
}
if (ds.Tables[0].Rows[j][k] != null)
tempStr = ds.Tables[0].Rows[j][k].ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
MessageBox.Show("完成导出");
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
public static void ExportSqlToExcel(string SqlStr, string connstr)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出Excel文件到";
if (saveFileDialog.ShowDialog() != DialogResult.OK)
return;
DataSet ds = SqlQuery(SqlStr, connstr);
string FileName = saveFileDialog.FileName;
DeleteFile(FileName); //文件已存在,则删除;
OleDbParameter[] parm = new OleDbParameter[ds.Tables[0].Columns.Count];
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" FileName ";" "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
OleDbCommand objCmd = new OleDbCommand();
objCmd.Connection = conn;
//建立表结构
string CommTitleTxt = "";
CommTitleTxt = "CREATE TABLE Sheet1(";
//写标题
for (int i = 0; i < ds.Tables[0].Columns.Count; i )
{
if (i > 0)
{
CommTitleTxt = " varchar,";
}
CommTitleTxt = ds.Tables[0].Columns[i].ColumnName;
}
CommTitleTxt = " varchar)";
objCmd.CommandText = CommTitleTxt;
objCmd.ExecuteNonQuery();
//建立插入动作的Command
string CommContextstr = "";
CommContextstr = "INSERT INTO Sheet1(";
for (int j = 0; j < ds.Tables[0].Columns.Count; j )
{
if (j != 0)
CommContextstr = ",";
CommContextstr = ds.Tables[0].Columns[j].ColumnName;
}
CommContextstr = ")";
CommContextstr = " Values(";
for (int j = 0; j < ds.Tables[0].Columns.Count; j )
{
if (j != 0)
CommContextstr = ",";
CommContextstr = "@" ds.Tables[0].Columns[j].ColumnName;
}
CommContextstr = ")";
objCmd.CommandText = CommContextstr;
for (int k = 0; k < ds.Tables[0].Columns.Count; k )
{
parm[k] = new OleDbParameter("@" ds.Tables[0].Columns[k].ColumnName, OleDbType.VarChar);
objCmd.Parameters.Add(parm[k]);
}
////遍历数据集DS将数据插入新建的Excel文件中
for (int j = 0; j < ds.Tables[0].Rows.Count - 1; j )
{
for (int k = 0; k < ds.Tables[0].Columns.Count; k )
{
if (ds.Tables[0].Rows[j][k] != null)
parm[k].Value = ds.Tables[0].Rows[j][k].ToString();
}
objCmd.ExecuteNonQuery();
System.Windows.Forms.Application.DoEvents();
}
conn.Close();
MessageBox.Show("完成导出");
}
public static void DeleteFile(string strPath)
{
if (File.Exists(strPath))
{
File.Delete(strPath);
}
}
public static void ExportSqlToAccess(string SqlStr, string connstr)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Access files (*.mdb)|*.mdb";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出Access文件到";
if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
{
return;
}
DataSet ds = SqlQuery(SqlStr, connstr);
string AccessPath = saveFileDialog.FileName;
DeleteFile(AccessPath); //文件已存在,则删除;
ADOX.CatalogClass cat = new ADOX.CatalogClass();
cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" AccessPath ";"); //创建数据库文件
MessageBox.Show("数据库:" AccessPath "已经创建成功!");
OleDbParameter[] parm = new OleDbParameter[ds.Tables[0].Columns.Count];
string ConnectionAccess = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" AccessPath ";";
OleDbConnection conn = new OleDbConnection(ConnectionAccess);
conn.Open();
OleDbCommand objCmd = new OleDbCommand();
objCmd.Connection = conn;
//建立表结构
string CommTitleTxt = "";
CommTitleTxt = "CREATE TABLE Table1(";
//写标题
for (int i = 0; i < ds.Tables[0].Columns.Count; i )
{
if (i > 0)
{
CommTitleTxt = " varchar,";
}
CommTitleTxt = ds.Tables[0].Columns[i].ColumnName;
}
CommTitleTxt = " varchar)";
objCmd.CommandText = CommTitleTxt;
objCmd.ExecuteNonQuery();
//建立插入动作的Command
string CommContextstr = "";
CommContextstr = "INSERT INTO Table1(";
for (int j = 0; j < ds.Tables[0].Columns.Count; j )
{
if (j != 0)
CommContextstr = ",";
CommContextstr = ds.Tables[0].Columns[j].ColumnName;
}
CommContextstr = ")";
CommContextstr = " Values(";
for (int j = 0; j < ds.Tables[0].Columns.Count; j )
{
if (j != 0)
CommContextstr = ",";
CommContextstr = "@" ds.Tables[0].Columns[j].ColumnName;
}
CommContextstr = ")";
objCmd.CommandText = CommContextstr;
for (int k = 0; k < ds.Tables[0].Columns.Count; k )
{
parm[k] = new OleDbParameter("@" ds.Tables[0].Columns[k].ColumnName, OleDbType.VarChar);
objCmd.Parameters.Add(parm[k]);
}
////遍历DataGridView将数据插入新建的Access文件中
for (int j = 0; j < ds.Tables[0].Rows.Count - 1; j )
{
for (int k = 0; k < ds.Tables[0].Columns.Count; k )
{
if (ds.Tables[0].Rows[j][k] != null)
parm[k].Value = ds.Tables[0].Rows[j][k].ToString();
}
objCmd.ExecuteNonQuery();
System.Windows.Forms.Application.DoEvents();
}
conn.Close();
MessageBox.Show("完成导出");
}
public static void MakeDbTable(SqlConnection conn, string tablename, string linestr) //在数据库中建表;
{
// Connectionstring "Data Source=JUNCHENG-AAE091;Initial Catalog=model;Integrated Security=True";
try
{
string commtxt = "CREATE TABLE " tablename "(";
string[] tmpstrs = linestr.Split('\t');
int i = 0;
foreach (string tmpstr in tmpstrs)
{
if (i != 0)
commtxt = ",";
commtxt = tmpstr;
commtxt = " varchar(50)";
i ;
}
commtxt = " )";
SqlCommand comm = new SqlCommand(commtxt, conn);
comm.ExecuteNonQuery();
conn.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
conn.Close();
}
}
public static void InsertToTable(SqlConnection conn, string tablename, string linestr, string Titlestr) //在表中插数据;
{
string[] tmpstrs2 = linestr.Split('\t');
if (tmpstrs2.Length == 0) //空数据直接返回;
return;
string commtxt = "Insert into " tablename "(";
string[] tmpstrs = Titlestr.Split('\t');
int i = 0;
foreach (string tmpstr in tmpstrs)
{
if (i != 0)
commtxt = ",";
commtxt = tmpstr;
i ;
}
commtxt = ") Values(";
int j = 0;
foreach (string tmpstr2 in tmpstrs2)
{
if (j != 0)
commtxt = ",";
commtxt = tmpstr2;
j ;
}
commtxt = ")";
SqlCommand comm = new SqlCommand(commtxt, conn);
comm.ExecuteNonQuery();
conn.Close();
}
public static void ImportTxtToDB(string SqlStr, string connstr, string tablename)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "文本文件(*.txt)|*.txt";
openFileDialog.Title = "选择文本文件";
if (DialogResult.Cancel == openFileDialog.ShowDialog())
{
return;
}
string filename = openFileDialog.FileName;
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
//打开文件并显示其内容
StreamReader reader = null;
try
{
reader = new StreamReader(filename);
string Titlestr = "";
int linenum = 0;
for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
{
if (linenum == 0)
{
Titlestr = line;
if (!TableIsExists(conn, tablename))
MakeDbTable(conn, tablename, line); //创建表;
}
else
{
InsertToTable(conn, tablename, line, Titlestr); //表数据插入;
}
linenum ;
}
MessageBox.Show("导入完成");
}
catch (IOException e)
{
MessageBox.Show(e.Message);
}
finally
{
if (reader != null)
reader.Close();
conn.Close();
}
}
public void ImportExcelToDB(string connstr, string tablename)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Microsoft Excel 文件(*.xls)|*.xls";
openFileDialog.Title = "选择Excel文件";
if (DialogResult.Cancel == openFileDialog.ShowDialog())
{
return;
}
string ExcelPath = openFileDialog.FileName;
// txtExcelPath.Text = ExcelPath;
string ConnectionExcel = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" ExcelPath ";" "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(ConnectionExcel);
conn.Open();
System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
string EtableName = schemaTable.Rows[0][2].ToString().Trim(new char[] { '$', '\'' });
OleDbDataAdapter adp = new OleDbDataAdapter("Select * from [" EtableName "$]", conn);
DataSet ds = new DataSet();
adp.Fill(ds, "Book1");
if (InsertSQLServer(ds, tablename, connstr))
{
MessageBox.Show("导入表数据完成");
}
else MessageBox.Show("导入表数据失败");
}
public void ImportAccessToDB(string connstr, string tablename)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Microsoft Access 文件(*.mdb)|*.mdb";
openFileDialog.Title = "选择Access文件";
if (DialogResult.Cancel == openFileDialog.ShowDialog())
{
return;
}
string AccessPath = openFileDialog.FileName;
string ConnectionAccess = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" AccessPath ";";
try
{
OleDbConnection conn = new OleDbConnection(ConnectionAccess);
conn.Open();
string Atablename = "";
DataTable dt = conn.GetSchema("Tables");//获取ACCESS数据库中所有的表\查询\宏\窗体\模块
for (int i = 0; i < dt.Rows.Count; i )
{
if (dt.Rows[i].ItemArray[3].ToString() == "TABLE")//判断是否是用户表
{
Atablename = dt.Rows[i].ItemArray[2].ToString();
}
}
OleDbDataAdapter adp = new OleDbDataAdapter("Select * from " Atablename, conn);
DataSet ds = new DataSet();
adp.Fill(ds, "Book1");
if (InsertSQLServer(ds, tablename, connstr))
MessageBox.Show("导入表数据完成");
else MessageBox.Show("导入表数据失败");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
public static bool TableIsExists(SqlConnection conn, string tablename) //表是否已经存在;
{
try
{
string SqlStr = "SELECT name FROM sysobjects WHERE type='U'and name ='" tablename "'";
SqlCommand comm = new SqlCommand(SqlStr, conn);
int iResult = 0;
iResult = comm.ExecuteNonQuery();
if (iResult == 0)
return false;
else return true;
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString());
return true;
}
}
public static bool InsertSQLServer(DataSet ds, string tablename, string connstr)
{
try
{
SqlConnection con = new SqlConnection(connstr);//创建连接
con.Open();
string Titlestr = "";
for (int i = 0; i < ds.Tables[0].Columns.Count; i ) //取字段名;
{
if (i != 0)
Titlestr = "\t"; //tab字符分隔;
Titlestr = ds.Tables[0].Columns[i].ColumnName;
}
if (!TableIsExists(con, tablename)) //表不存在创建表;
{
MakeDbTable(con, tablename, Titlestr);
}
for (int i = 0; i < ds.Tables[0].Rows.Count; i )
{
string linestr = "";
for (int j = 0; j < ds.Tables[0].Columns.Count; j )
{
if (j != 0)
linestr = "\t"; //Tab字符分隔;
if (ds.Tables[0].Rows[i][j] != null)
linestr = ds.Tables[0].Rows[i][j].ToString();
else linestr = " ";
}
InsertToTable(con, tablename, linestr, Titlestr);//插入数据
}
con.Close();
return true;
}
catch
{
return false;
}
}
public static bool btnExecuteSql(string SqlStr, string connstr, DataGridView dgv)
{
try
{
DataSet ds = SqlQuery(SqlStr, connstr);
if (ds.Tables.Count != 0)
dgv.DataSource = ds.Tables[0].DefaultView;
else dgv.DataSource = null;
return true;
}
catch
{
return false;
//不显示错误信息
}
}
/* public void DBBackup(string ServerName, string UserName, string Pwd, string DBName)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = "Backup" DateTime.Now.ToString("yyyyMMddhhmmss") ".bak";
saveFileDialog.Filter = "Backup files (*.bak)|*.bak";
saveFileDialog.FilterIndex = 0;
saveFileDialog.InitialDirectory = @"C:\";
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "备份文件到";
if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
{
return;
}
/* SQLDMO.Backup backup = new SQLDMO.BackupClass();
try
{
backup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database;
backup.Database = DBName;
backup.Files =
backup.BackupSetName = "DBName";
backup.BackupSetDescription = "数据库备份";
backup.Initialize = true;
backup.PercentCompleteNotification = 10;
backup.PercentComplete = new PercentCompleteEventHandler(backup_PercentComplete);
backup.Complete = new ServerMessageEventHandler(backup_Complete);
backup.SQLBackup(sqlserver);
}
catch (Exception ex)
{
throw (new Exception("备份数据库失败" ex));
}
finally
{
sqlserver.DisConnect();
}
}*/
/* public static void ReconveDB(string ServerName, string UserName, string Pwd, string DBName)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Backup files (*.bak)|*.bak";
openFileDialog.Title = "选择备份文件";
if (DialogResult.Cancel == openFileDialog.ShowDialog())
{
return;
}
SQLDMO.Restore restore = new SQLDMO.RestoreClass();
SQLDMO.SQLServer sqlserver = new SQLDMO.SQLServerClass();
try
{
sqlserver.LoginSecure = false;
sqlserver.Connect(ServerName, UserName, Pwd);
restore.Action = SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database;
restore.Database = DBName;
restore.Files = openFileDialog.FileName;
restore.FileNumber = 1;
restore.ReplaceDatabase = true;
restore.SQLRestore(sqlserver);
}
catch (Exception ex)
{
throw (new Exception("还原数据库失败" ex));
}
finally
{
sqlserver.DisConnect();
}
} */
private void btnExpExcel_Click(object sender, EventArgs e)
{
ExportDataGridViewToExcel(dgv);
}
private void button1_Click(object sender, EventArgs e)
{
ExportDataGridViewToWord(dgv);
}
private void button2_Click(object sender, EventArgs e)
{
ImportExcelToDataGridView(dgv1);
}
private void button3_Click(object sender, EventArgs e)
{
ExportDataGridViewToTXT(dgv);
}
private void button3_Click_1(object sender, EventArgs e)
{
ImportTxtToView(dgv1);
}
private void button3_Click_2(object sender, EventArgs e)
{
ExportDataGridViewToExcel2(dgv);
}
private void ViewToAccess_Click(object sender, EventArgs e)
{
ExportDataGridViewToAccess(dgv);
}
private void button2_Click_1(object sender, EventArgs e)
{
ImportAccessToDataGridView(dgv1);
}
private void SqlToTxt_Click(object sender, EventArgs e)
{
ExportSqlToTxt(rtbSql.Text.Trim(), tbConnStr.Text);
}
private void SqlToExcel_Click(object sender, EventArgs e)
{
ExportSqlToExcel(rtbSql.Text.Trim(), tbConnStr.Text);
}
private void SqlToAccess_Click(object sender, EventArgs e)
{
ExportSqlToAccess(rtbSql.Text.Trim(), tbConnStr.Text);
}
private void TxtToDB_Click(object sender, EventArgs e)
{
ImportTxtToDB(rtbSql.Text.Trim(), tbConnStr.Text, "TestTab");
}
private void ExcelToDB_Click(object sender, EventArgs e)
{
ImportExcelToDB(tbConnStr.Text, "TestTab");
}
private void Execute_Click(object sender, EventArgs e)
{
if (btnExecuteSql(rtbSql.Text.Trim(), tbConnStr.Text, dgvSQLResult))
lbResult.Text = "ExcuteResult:OK";
else lbResult.Text = "ExcuteResult:Fail";
}
private void AccessToDB_Click(object sender, EventArgs e)
{
ImportAccessToDB(tbConnStr.Text, "TestTab");
}
private void TabBackup_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = "Backup" DateTime.Now.ToString("yyyyMMddhhmmss") ".bak";
saveFileDialog.Filter = "Backup files (*.bak)|*.bak";
saveFileDialog.FilterIndex = 0;
saveFileDialog.InitialDirectory = @"C:\";
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "备份文件到";
if (saveFileDialog.ShowDialog() == DialogResult.Cancel)
{
return;
}
smoHelper = new SMOHelper("JUNCHENG-AAE091", "sa", "li", false);
smoHelper.Connect();
if (smoHelper.Server != null)
{
smoHelper.BackupPercentCompleteChanging = Backup_PercentCompleteChanging;
smoHelper.BackupComplete = Backup_Complete;
smoHelper.RestorePercentCompleteChanging = Restore_PercentCompleteChanging;
smoHelper.RestoreComplete = Restore_Complete;
}
pbar.Maximum = 100;
pbar.Style = ProgressBarStyle.Blocks;
pbar.Value = 0;
pbar.Step = 10;
string databaseName = "model";
smoHelper.BackupDatabase(databaseName, saveFileDialog.FileName);
smoHelper.DisConnect();
}
public void Backup_Complete(object sender, ServerMessageEventArgs e)
{
pbar.Value = pbar.Maximum;
string databaseName = ((Backup)sender).Database;
string msg = string.Format("Database {0} has been backed up successfully!", databaseName);
MessageBox.Show(msg);
pbar.Value = 0;
}
public void Backup_PercentCompleteChanging(object sender, PercentCompleteEventArgs e)
{
pbar.PerformStep();
}
public void Restore_Complete(object sender, ServerMessageEventArgs e)
{
pbar.Value = pbar.Maximum;
string databaseName = ((Restore)sender).Database;
string msg = string.Format("Database {0} has been restored successfully!", databaseName);
MessageBox.Show(msg);
pbar.Value = 0;
}
public void Restore_PercentCompleteChanging(object sender, PercentCompleteEventArgs e)
{
pbar.PerformStep();
}
private void ReconverDB_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "Backup files (*.bak)|*.bak";
openFileDialog.Title = "选择备份文件";
if (DialogResult.Cancel == openFileDialog.ShowDialog())
{
return;
}
smoHelper = new SMOHelper("JUNCHENG-AAE091", "sa", "li", false);
smoHelper.Connect();
if (smoHelper.Server != null)
{
smoHelper.BackupPercentCompleteChanging = Backup_PercentCompleteChanging;
smoHelper.BackupComplete = Backup_Complete;
smoHelper.RestorePercentCompleteChanging = Restore_PercentCompleteChanging;
smoHelper.RestoreComplete = Restore_Complete;
}
pbar.Maximum = 100;
pbar.Style = ProgressBarStyle.Blocks;
pbar.Value = 0;
pbar.Step = 10;
string databaseName = "model";
smoHelper.RestoreDB(databaseName, openFileDialog.FileName);
smoHelper.DisConnect();
}
private void tbConnStr_TextChanged(object sender, EventArgs e)
{
}
private void pbar_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
}
}