标签:
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.Data.OleDb;
using System.Collections;
using System.Data.SqlClient;
using Budget.DBUtility;
namespace Budget.Web.Admin.RMBase.SysUser
{
public partial class ceshi : System.Web.UI.Page
{
SqlConnection sqlcon;
SqlCommand sqlcom;
string strCon = "MyOfficeConnectionString";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// bind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Fileupload1.HasFile)
{
//获取文件路径
//string path = Fileupload1.PostedFile.FileName;
string path = HttpContext.Current.Request.MapPath("../upload/预算管理系统用户模板.xlsx");
//获取文件名
string FileName = Fileupload1.FileName;
//根据文件结尾名判断文件格式
if (FileName.ToLower().Substring(FileName.Length - 3) != "xls" && FileName.ToLower().Substring(FileName.Length - 4) != "xlsx")
{
Response.Write("<script type=‘text/JavaScript‘>alert(‘请选择Excel文件!‘)</script>");
return;
}
//获取Excel的数据datatable
DataTable dt = GetTable(path, FileName);
using (SqlConnection conn = new SqlConnection("server=192.168.29.59;database=ExpenseBudget4.0Test;uid=sa;pwd=123;"))
{
conn.Open();
SqlTransaction sqlTransaction = conn.BeginTransaction();
// 将事务应用于Command
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = conn;
sqlCommand.Transaction = sqlTransaction;
try
{
foreach (DataRow row in dt.Rows)
{
string user_id = Guid.NewGuid().ToString().ToLower();
string user_code = row["工号"].ToString();
string user_name = row["姓名"].ToString();
string shouji = row["手机号/电话"].ToString();
string User_Account = row["登录ID"].ToString();
string sql= string.Format("insert into Base_UserInfo(User_ID,User_Code,User_Name,User_Account) values(‘{0}‘,‘{1}‘,‘{2}‘,‘{3}‘)", user_id, user_code, user_name, User_Account);//sql数据库
int a = new SqlServerHelper().RunSqlGetRowCount(sql);
sqlCommand.CommandText = string.Format("insert into Base_AppendPropertyInstance(PropertyInstance_ID,PropertyInstance_Key,Property_Control_ID,PropertyInstance_Value) values(NEWID(),‘{0}‘,‘{1}‘,‘{2}‘)", user_id, "User_Tel", shouji);//sql数据库
sqlCommand.ExecuteNonQuery();
}
//成功提交
sqlTransaction.Commit();
Response.Write("<script type=‘text/JavaScript‘>alert(‘已成功导入文件!‘)</script>");
}
catch (Exception ex)
{
// 出错回滚
sqlTransaction.Rollback();
Response.Write("<script type=‘text/JavaScript‘>alert(‘导入文件失败!‘)</script>");
}
finally
{
conn.Close();
}
}
}
else
{
Response.Write("<script type=‘text/JavaScript‘>alert(‘请选择要导入的文件!‘)</script>");
}
}
//将Execl的数据读取到Datatable
protected DataTable GetTable(string path, string fileName)
{
string connString = "";
if (fileName.ToLower().IndexOf(".xlsx") < 0)
{
connString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=‘{0}‘;Extended Properties=‘Excel 8.0;IMEX=1‘", path);
}
else
{
connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=‘{0}‘;Extended Properties=‘Excel 12.0;HDR=YES‘", path);
}
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connString);
string sql = "SELECT * FROM [Sheet1$]";
DataTable dt;
try
{
conn.Open();
System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(sql, conn);
DataSet ds = new DataSet();
myCommand.Fill(ds, "[Sheet1$]");
conn.Close();
dt = ds.Tables[0];
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception err)
{
return null;
}
return dt;
}
//上传文件方法
private bool Upload(FileUpload myFileUpload)
{
bool flag = false;
//是否允许上载
bool fileAllow = false;
//设定允许上载的扩展文件名类型
string[] allowExtensions = { ".xls", ".xlsx" };
//取得网站根目录路径
string path = HttpContext.Current.Request.MapPath("../upload/");
if (myFileUpload.HasFile)
{
string fileExtension = System.IO.Path.GetExtension(myFileUpload.FileName).ToLower();
for (int i = 0; i < allowExtensions.Length; i++)
{
if (fileExtension == allowExtensions[i])
{
fileAllow = true;
}
}
if (fileAllow)
{
try
{
//存储文件到文件夹
myFileUpload.SaveAs(path + myFileUpload.FileName);
lblMes.Text = "文件导入成功";
flag = true;
}
catch (Exception ex)
{
lblMes.Text += ex.Message;
flag = false;
}
}
else
{
lblMes.Text = "不允许上载:" + myFileUpload.PostedFile.FileName + ",只能上传xls的文件,请检查!";
flag = false;
}
}
else
{
lblMes.Text = "请选择要导入的excel文件!";
flag = false;
}
return flag;
}
}
}
标签:
原文地址:http://www.cnblogs.com/jingyong001/p/5457208.html