本來想把導入數據庫後的數據通過gridview控件全部顯示到界面,因為一旦進入頁面所有控件的已經初始化好了,所以必須使用刷新數據源或用代碼實現不用控件來綁定數據源,某位實現了這個功能可以發表下自己的意見
本來想把導入數據庫後的數據通過gridview控件全部顯示到界面,因為一旦進入頁面所有控件的已經初始化好了,所以必須使用刷新數據源或用代碼實現不用控件來綁定數據源,某位實現了這個功能可以發表下自己的意見
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;
public partial class Excel導入_Default : System.Web.UI.Page
{
private static string filename;
private static string savePath;
private static DataSet ds; //要插入的數據
private static DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
}
//上傳文件到指定的服務器
protected void Button1_Click1(object sender, EventArgs e)
{
filename = this.fileUploadExcel.FileName;
//savePath必須包含表名在內的所有路徑名
savePath = @"G:\項目組文件\項目.net學習資料\工程\Health\Excel導入\Files\" + this.fileUploadExcel.FileName; //上傳服務器文件的存儲,存在當前新建的文件夾
this.fileUploadExcel.SaveAs(savePath);
Boolean judge_excel = Judge_Excel();
if (!judge_excel)
{
MessageBox.Show("上傳的不是excel文件", "標題", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
return;
}
else
MessageBox.Show("上傳文件成功", "標題", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
//測試,將excel中的sheet1導入到sqlserver中
//string connString = "server=localhost;uid=sa;pwd=sqlgis;database=master";
//System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog();
//if (fd.ShowDialog() == DialogResult.OK)
//{
// //TransferData(fd.FileName, "sheet1", connString);
//}
}
//判斷文件是否是excel文件函數
protected Boolean Judge_Excel()
{
string fileExtend = System.IO.Path.GetExtension(this.fileUploadExcel.FileName);
if (fileExtend == ".xlsx" || fileExtend == ".xls")
return true;
else
return false;
}
//獲取excel數據按鈕的觸發,
protected void Button2_Click(object sender, EventArgs e)
{
ExcelToDataSet();
MessageBox.Show("獲取數據成功", "標題", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
//從excel表中獲取數據的函數
public void ExcelToDataSet()
{
string strConn = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + savePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
OleDbConnection conn = new OleDbConnection(strConn); //連接excel
if (conn.State.ToString() == "Open")
{
conn.Close();
}
conn.Open(); //外部表不是預期格式,不兼容2010的excel表結構
string s = conn.State.ToString();
OleDbDataAdapter myCommand = null;
ds = null;
/*DataTable yTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" });//獲取表的框架,幾行幾列
string tableName = yTable.Rows[0]["filename"].ToString(); //表示的是幾行幾列
string strSel = "select * from [" + filename + "]";//xls */
string strExcel = "select * from [sheet1$]"; //如果有多個sheet表時可以選擇是第幾張sheet表
myCommand = new OleDbDataAdapter(strExcel, conn);//用strExcel初始化myCommand,查看myCommand裡面的表的數據??
ds = new DataSet();
myCommand.Fill(ds); //把表中的數據存放在ds(dataSet)
conn.Close();
try
{
dt = ds.Tables[0];
this.dataGridView1.DataSource = dt;
}
catch (Exception err)
{
MessageBox.Show("操作失敗!" + err.ToString());
}
}
//excel導入數據庫sql的按鈕觸發
protected void Button3_Click(object sender, EventArgs e)
{
//string path = @"D:\數據庫SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Test.mdf";
string connString = "server=localhost;uid=sa;pwd=1234;database=Test"; //連接數據庫的路徑方法
//String connString=@"server=localhost;uid=sa;pwd=1234;database=D:\數據庫SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Test.mdf";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
DataRow dr = null;
int C_Count = dt.Columns.Count;//獲取列數
for (int i = 0; i < dt.Rows.Count; i++) //記錄表中的行數,循環插入
{
dr = dt.Rows[i];
insertToSql(dr, C_Count, conn);
}
conn.Close();
if (dataGridView1.Rows.Count > 0) //把數據庫表中的數據顯示到表中,可判斷有沒有數據
{
MessageBox.Show("導入成功!");
}
else
{
MessageBox.Show("沒有數據!");
}
}
//使用bcp,不容易出錯而且效率高
/*try
{
using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(connString))
{
bcp.SqlRowsCopied += new System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);
bcp.BatchSize = 100;//每次傳輸的行數
bcp.NotifyAfter = 100;//進度提示的行數
bcp.DestinationTableName = savePath;//目標表
bcp.WriteToServer(ds.Tables[0]);
}
}
catch
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}*/
//插入數據庫的函數
protected void insertToSql(DataRow dr, int column_count, SqlConnection conn)
{
//excel表中的列名和數據庫中的列名一定要對應
string name = dr[0].ToString();//需要把內個列都列出來
string age = dr[1].ToString();
string sex = dr[2].ToString();
//當數據庫中有多個表時,怎麼分辨插入的表
string sql = "insert into 客戶 values('" + name + "','" + age + "','" + sex + "')";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
//從excel表中獲取數據並存在
// protected void ImportFromExcel()
// {
// string execelConnectionStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=filename;
// Extended Properties=""Excel 8.0;HDR=YES;IMEX=1\""";//表第一行是標題,不做為數據使用, Excel 檔案只能用來做“讀取”用途。
// ds = new DataSet();
// string connString = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = "
// + savePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
// DataTable table = OleDbHelper.GetExcelTables(connString);
// if (table == null || table.Rows.Count <= 0)
// {
// return;
// }
// foreach (DataRow dr in table.Rows)
// {
// string cmdText = "select * from [" + dr["TABLE_NAME"].ToString() + "]";
// DataTable dt = OleDbHelper.FillDataTable(connString, cmdText);
// dt.TableName = dr["TABLE_NAME"].ToString();
// ds.Tables.Add(dt);
// }
// }
}