我是一名學生,對編程頗爲陌生,並且我被授予了一項使用ASP.NET和C#的任務,但未被教授。計劃是學會自學。試圖將csv和xls文件導入到使用ASP.NET和C的SQL數據庫中#
我堅持的任務是將網站從CSV或XLS文件導入校園周圍去年房間預訂的SQL數據庫。
雖然我通過以下教程學到了一些東西,但我一直在尋找一種方法來編程c#以「讀取」一個csv文件(使用分隔符分隔條目是逗號「,」)和一個xls使用Microsoft的SQL數據庫將文件轉換成表格。
所以,我所做的是,在已下載的Visual Studio,並開始使用asp.net的web表單,我開始在.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(在結果CSVfile行) { 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。網似乎很混亂。 有沒有辦法做到這一點,而不使用外部庫? 我可以讓gridview從數據庫中顯示錶格嗎? 什麼是最好的方法?
非常感謝!
UPDATE:
@Tim再次
感謝所有幫助!
這是我的時刻:
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();
}
}
}
}
我試圖使它工作的CSV只有2項對於初學者文件: 請求ID和優先級,使一些簡單的構建之上。
爲了使事情變得很短,我很困惑如何把我的代碼,你的代碼和我的隊友的代碼,使一些工作(我不明白在代碼的一切)
更新2:
這裏是我的.aspx代碼,沒有什麼特別的,只是1個按鈕,1個gridview的
<!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>");
}
}
}
}
}
此外,只是想說,在: table.Rows.Add(row.Request_ID,row.Priority); } 我只是測試代碼只有2個變量,而不是全部使用它們,這就是爲什麼它不包含所有這些代碼 – 2013-05-11 03:00:30