我基本上是在寻找构建代码来读取excel文件和创建用户帐户的最佳方法。
我已经有了读取excel文件和创建帐户的代码,但是我不确定将数据从Excel工作表传递到“CreateUser”函数的最佳方法。
感谢任何帮助。
干杯。
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
namespace INB201_SAMS.Admin
{
public partial class UploadList : System.Web.UI.Page
{
protected void UploadButton_Click(object sender, EventArgs e)
{
var upload = Path.Combine(Server.MapPath("~/upload"), "myfilename.xlsx");
CSVUpload.SaveAs(upload);
var excelConString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0", upload);
using (OleDbConnection con = new OleDbConnection(excelConString))
{
con.Open();
OleDbCommand com = new OleDbCommand("Select * from [UserUpload$]", con);
OleDbDataReader dr = com.ExecuteReader();
}
File.Delete(upload);
Response.Write("Upload Successfull!");
}
protected bool CreateUser(string UsersUsername, string UsersPassword)
{
try
{
MembershipUser newUser = System.Web.Security.Membership.CreateUser(UsersUsername, UsersPassword);
Roles.AddUserToRole(UsersUsername, "student");
return true;
}
catch (Exception ex)
{
MessageYo.Text = ex.ToString();
return false;
}
}
}
}
答案 0 :(得分:2)
这是一件非常简单的事情:
while(dr.Read()) {
string user = dr[0].ToString();
string pass = dr[1].ToString();
if(!String.IsNullOrWhiteSpace(user) && !String.IsNullOrWhiteSpace(pass))
CreateUser(user, pass)
}
dr.Close()
答案 1 :(得分:1)
我认为您的用户名和用户密码位于两列中。在这种情况下。您可以通过其特定标题读取Excel的特定列。这是对此的讨论:http://social.msdn.microsoft.com/Forums/en-US/exceldev/thread/6506b0b1-be8c-40f9-879f-21715bd2792e。然后你可以将值传递给函数。
解决方法:go through XML file这意味着将Excel转换为XML,然后从xml获取数据到函数。