我是一名学生,对编程很陌生,我被分配了一项使用 ASP.NET 和 C# 的任务,但也没有被教过。计划是学会自学。
我坚持的任务是将网站从 CSV 或 XLS 文件导入到校园内去年房间预订的 SQL 数据库。
虽然我通过遵循教程学到了一些东西,但我一直坚持寻找一种方法来编程 c# 以“读取”一个 csv 文件(用于分隔条目的分隔符是逗号“,”)和一个 xls 文件到一个表中使用微软的 SQL 数据库。
所以,我所做的是,在下载了 Visual Studio 并开始使用 asp.net 的 webforms 之后,我首先在 .aspx 表单上创建了一个按钮,以便在单击时触发导入:
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Import_button_Click"/>
我将我的函数命名为“Import_Button_Click”
在这里,我在教程中找到了一个名为 Filehelpers 的 .dll 库。我看起来很有希望,所以我试了一下。我在 Visual Studio 中添加了它的引用,还添加了“使用 Filehelpers;” 在 C# 表单的开头。
这是一个链接: http: //filehelpers.sourceforge.net/
所以,我使用:
FileHelperEngine engine = new FileHelperEngine(typeof(CSVfile));
和
CSVfile[] result = engine.ReadFile("C:\\CSVDATA\\previousyear.csv") as CSVfile[];
使其读取 CSV 文件。同时,我创建了一个类来将 CSV 文件的每个条目存储为变量:
[DelimitedRecord(",")]
public class CSVfile //CSVfile class being defined
{
public int Request_ID;
public int Priority;
public int Module_ID;
public string Day;
public string Start_Time;
public int Length;
public string Park;
public int Students;
public string Room_Code;
public string Status;
public int Semester_ID;
public int Linked_Request;
public int Week_1;
public int Week_2;
public int Week_3;
public int Week_4;
public int Week_5;
public int Week_6;
public int Week_7;
public int Week_8;
public int Week_9;
public int Week_10;
public int Week_11;
public int Week_12;
public int Week_13;
public int Week_14;
public int Week_15;
}
之后,在它读取 previousyear.csv 的正下方,我执行循环,它将获取每个条目并将其放在正确的变量中:
DataTable table = new DataTable();
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(string));
table.Columns.Add(" ", typeof(string));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(string));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(string));
table.Columns.Add(" ", typeof(string));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
table.Columns.Add(" ", typeof(int));
foreach(结果中的 CSV 文件行){ Console.WriteLine(row.Request_ID + " " + row.Priority);
table.Rows.Add(row.Request_ID, row.Priority);
}
但问题是,我不能让它在任何地方输出结果,甚至不能使用 gridview
此外,在添加了库的其他计算机上运行它也很麻烦。
今天,我的一个队友给了我一个 SQL 代码,我应该用它来把我的变量放到数据库中,它是这样的:
public string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["team03ConnectionString"].ConnectionString;
//the "ConnStringName" is the name of your Connection String that was set up from the Web.Config
}
protected void BookRoom_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(GetConnectionString());
// string sql = "INSERT INTO tests (column6,Column2,Column3,Column4,Column5) VALUES (@Val1,@Val2,@Val3,@Val4,@Val5)";
// string sql = "Insert INTO Requests (Priority, Module_ID, Day,Start_Time, Length, Park, Students, Room_Code, Status, Semester_ID, Week_1,Week_2,Week_3,Week_4,Week_5,Week_6,Week_7,Week_8,Week_9,Week_10,Week_11,Week_12,Week_13,Week_14,Week_15) VALUES (@Priority, @Module_ID, @Day,@Start_Time, @Length, @Park, @Students, @Room_Code, @Status, @Semester_ID, @Week_1, @Week_2, @Week_3, @Week_4, @Week_5, @Week_6, @Week_7, @Week_8, @Week_9, @Week_10, @Week_11, @Week_12, @Week_13, @Week_14, @Week_15)";
string sql = "Insert INTO Requests (Priority, Module_ID, Day,Start_Time, Length, Park, Students, Room_Code, Status,Room_Allocated, Semester_ID, Week_1,Week_2,Week_3,Week_4,Week_5,Week_6,Week_7,Week_8,Week_9,Week_10,Week_11,Week_12,Week_13,Week_14,Week_15) OUTPUT INSERTED.Request_ID VALUES (@Priority, @Module_ID, @Day,@Start_Time, @Length, @Park, @Students, @Room_Code, @Status,@Room_Allocated, @Semester_ID, @Week_1, @Week_2, @Week_3, @Week_4, @Week_5, @Week_6, @Week_7, @Week_8, @Week_9, @Week_10, @Week_11, @Week_12, @Week_13, @Week_14, @Week_15)";
try
{
conn.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@Priority", "0");
cmd.Parameters.AddWithValue("@Module_ID", moduleSelect.Text);
cmd.Parameters.AddWithValue("@Day", Day.Text);
cmd.Parameters.AddWithValue("@Start_Time", StartTime.Text);
cmd.Parameters.AddWithValue("@Length", "1");
cmd.Parameters.AddWithValue("@Park", Request.QueryString["Pk"].ToString());
cmd.Parameters.AddWithValue("@Students", NumOfStudents.Text);
cmd.Parameters.AddWithValue("@Room_Code", roomChosen.Text);
cmd.Parameters.AddWithValue("@Status", "Pending");
cmd.Parameters.AddWithValue("@Room_Allocated", roomChosen.Text);
cmd.Parameters.AddWithValue("@Semester_ID", "7");
cmd.Parameters.AddWithValue("@Week_1", weeknumber1.Text);
cmd.Parameters.AddWithValue("@Week_2", weeknumber2.Text);
cmd.Parameters.AddWithValue("@Week_3", weeknumber3.Text);
cmd.Parameters.AddWithValue("@Week_4", weeknumber4.Text);
cmd.Parameters.AddWithValue("@Week_5", weeknumber5.Text);
cmd.Parameters.AddWithValue("@Week_6", weeknumber6.Text);
cmd.Parameters.AddWithValue("@Week_7", weeknumber7.Text);
cmd.Parameters.AddWithValue("@Week_8", weeknumber8.Text);
cmd.Parameters.AddWithValue("@Week_9", weeknumber9.Text);
cmd.Parameters.AddWithValue("@Week_10", weeknumber10.Text);
cmd.Parameters.AddWithValue("@Week_11", weeknumber11.Text);
cmd.Parameters.AddWithValue("@Week_12", weeknumber12.Text);
cmd.Parameters.AddWithValue("@Week_13", weeknumber13.Text);
cmd.Parameters.AddWithValue("@Week_14", weeknumber14.Text);
cmd.Parameters.AddWithValue("@Week_15", weeknumber15.Text);
//cmd.CommandType = System.Data.CommandType.Text;
//Int32 newId = (Int32)cmd.ExecuteScalar();
cmd.ExecuteNonQuery();
} //End of try
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
catch (FormatException ee)
{
System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Please enter a valid value');</SCRIPT>");
}
catch (System.Exception eeee)
{
System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('System Exception');</SCRIPT>");
}
finally
{
conn.Close();
}
}//End of insertInfor()
}
他告诉我,我要到周日才能弄清楚剩下的事情。
所以说了这么多,我不是在找人来做我的课程,而是从这里有经验的人那里得到建议,因为asp.net看起来很混乱。有没有办法在不使用外部库的情况下做到这一点?我可以让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.Data.OleDb;
using FileHelpers;
namespace ImportPage
{
public class CSVFile
{
public int Request_ID { get; set; }
public int Priority { get; set; }
//...
}
public class CSV
{
public string GetConnectionString()
{ return System.Configuration.ConfigurationManager.ConnectionStrings["team03ConnectionString"].ConnectionString; }
protected void button1_Click(object sender, EventArgs e)
{
List<CSVFile> entries = new List<CSVFile>();
using (TextFieldParser parser = new TextFieldParser(@"C:\CSVDATA\PreviousYear.csv"))
{
parser.TextFieldType = FieldType.Delimited;
parser.Delimiters = new string[] { "," };
string[] fields;
while (!parser.EndOfData)
{
fields = parser.ReadFields();
entries.Add(new CSVFile()
{
Request_ID = Convert.ToInt32(fields[0]),
Priority = Convert.ToInt32(fields[1]),
//...
});
}
}
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(GetConnectionString());
string sql = "Insert INTO Requests (Priority) OUTPUT INSERTED.Request_ID VALUES (@Priority)";
try
{
conn.Open();
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@Priority", "0");
cmd.ExecuteNonQuery();
} //End of try
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
catch (FormatException ee)
{
System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Please enter a valid value');</SCRIPT>");
}
catch (System.Exception eeee)
{
System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('System Exception');</SCRIPT>");
}
finally
{
conn.Close();
}
}
}
}
我正在尝试使其适用于只有 2 个入门条目的 CSV 文件:请求 ID 和优先级,以简化并以此为基础。
简而言之,我对如何放置我的代码、您的代码和我的队友的代码以使某些东西正常工作感到困惑(因为我不理解代码中的所有内容)
更新 2:
这是我的 .aspx 代码,没什么特别的,只有 1 个按钮,1 个网格视图
<!DOCTYPE html>
<script runat="server">
Protected Sub Import_button_Click(sender As Object, e As EventArgs)
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs)
End Sub
</script>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Timetabling Support Website</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Loading Bootstrap -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- Loading Flat UI -->
<link href="css/flat-ui.css" rel="stylesheet">
<!-- Loading Unsemantic -->
<link href="css/unsemantic-grid-responsive.css" rel="stylesheet">
<!-- Loading Personalized Style -->
<link href="css/style.css" rel="stylesheet">
<link rel="shortcut icon" href="images/favicon.ico">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements. All other JS at the end of file. -->
<!--[if lt IE 9]>
<script src="js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<form id="form1" runat="server">
<div class="grid-container">
<div class="header grid-100">
<div class="banner grid-70">
<img src="images/banner3.png" id="banner" alt="Loughborough Uni Logo" />
</div>
<div class="logout grid-30">
<p id="logout"> Welcome, Computer Science Timetabler. | <a href="index.html">Logout</a></p>
</div>
</div>
<div class="navbar navbar-inverse">
<div class="navbar-inner">
<ul class="nav">
<li>
<a href="home.html">
Home
</a>
</li>
<li>
<a href="#">
Requests
</a>
<ul>
<li>
<a href="request_new.html">New Request</a>
</li>
<li>
<a href="request_import.html">Import Requests</a>
</li>
<li>
<a href="request_current.html">Current Requests</a>
</li>
<li>
<a href="request_adhoc.html">Ad-Hoc Request</a>
</li>
</ul> <!-- /Sub menu -->
</li>
<li>
<a href="room_availability.html">
Room Availability
</a>
</li>
<li>
<a href="#">
History
</a>
<ul>
<li>
<a href="#">Semester 1</a>
<ul>
<li>
<a href="history_s1priority.html">Priority Round</a>
</li>
<li>
<a href="history_s1round1.html">Round 1</a>
</li>
<li>
<a href="history_current.html">Round 2</a>
</li>
<li>
<a href="history.html">Final Allocations</a>
</li>
</ul> <!-- /Sub menu -->
</li>
<li>
<a href="#">Semester 2</a>
<ul>
<li>
<a href="history.html">Priority Round</a>
</li>
<li>
<a href="history.html">Round 1</a>
</li>
<li>
<a href="history.html">Round 2</a>
</li>
<li>
<a href="history.html">Final Allocations</a>
</li>
</ul> <!-- /Sub menu -->
</li>
</ul> <!-- /Sub menu -->
</li>
<li>
<a href="#">
Maintenance
</a>
<ul>
<li>
<a href="module_add.html">Add Module</a>
</li>
<li>
<a href="module_edit.html">Edit Module</a>
</li>
</ul> <!-- /Sub menu -->
</li>
<li>
<a href="help.html">
Help
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
<div class="content center">
<h1>Import Request
</h1>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Import_button_Click"/>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
<div class="grid-100 footer">
<p>Copyright © 2013 Team 3 Timetabling Support Website</p>
</div>
</div> <!-- /container -->
<asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>
<!-- Load JS here for greater good =============================-->
<script src="js/jquery-1.8.2.min.js"></script>
<script src="js/jquery-ui-1.10.0.custom.min.js"></script>
<script src="js/jquery.dropkick-1.0.0.js"></script>
<script src="js/custom_checkbox_and_radio.js"></script>
<script src="js/custom_radio.js"></script>
<script src="js/jquery.tagsinput.js"></script>
<script src="js/bootstrap-tooltip.js"></script>
<script src="js/jquery.placeholder.js"></script>
<script src="http://vjs.zencdn.net/c/video.js"></script>
<script src="js/application.js"></script>
<!--[if lt IE 8]>
<script src="js/icon-font-ie7.js"></script>
<script src="js/icon-font-ie7-24.js"></script>
<![endif]-->
</form>
</body>
</html>
这部分代码似乎有很多问题:
string sql = "Insert INTO Requests (Priority);
OUTPUT INSERTED.Request_ID
VALUES (@Priority)";
更新 3:
好的,修复了那段代码。只需要把它们都放在同一行。现在,当我尝试构建应用程序时,只有 1 个错误:
错误 3 找不到类型或命名空间名称“SqlCommand”(您是否缺少 using 指令或程序集引用?)
因此,无法识别 SqlCommand。我是否需要添加参考或其他内容才能被识别?SqlConnection 也是如此
更新 4
这是我现在使用的代码,因为我让它在 Visual Studio 中工作
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.VisualBasic.FileIO;
using System.Data.SqlClient;
namespace ImportPage
{
public class CSVFile
{
public int Request_ID { get; set; }
public int Priority { get; set; }
public int Module_ID { get; set; }
//...
}
public class CSV
{
public string GetConnectionString()
{ return System.Configuration.ConfigurationManager.ConnectionStrings["team03ConnectionString"].ConnectionString; }
protected void button1_Click(object sender, EventArgs e)
{
List<CSVFile> entries = new List<CSVFile>();
using (TextFieldParser parser = new TextFieldParser(@"PreviousYear.csv"))
{
parser.TextFieldType = FieldType.Delimited;
parser.Delimiters = new string[] { "," };
string[] fields;
while (!parser.EndOfData)
{
fields = parser.ReadFields();
entries.Add(new CSVFile()
{
Request_ID = Convert.ToInt32(fields[0]),
Priority = Convert.ToInt32(fields[1]),
Module_ID = Convert.ToInt32(fields[2])
//...
});
}
}
using (SqlConnection conn = new SqlConnection(GetConnectionString()))
{
string sql = "Insert INTO Requests (Priority, Module_ID) OUTPUT INSERTED.Request_ID VALUES (@Priority, @Module_ID)";
try
{
conn.Open();
foreach (CSVFile entry in entries)
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@Priority", entry.Priority);
cmd.Parameters.AddWithValue("@Module_ID", entry.Module_ID);
// ...
cmd.ExecuteNonQuery();
}
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
catch (FormatException ee)
{
System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Please enter a valid value');</SCRIPT>");
}
catch (System.Exception eeee)
{
System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('System Exception');</SCRIPT>");
}
}
}
}
}