4. Như vậy, đã có một DataTable tạm chứa dữ liệu được load từ file Excel. DataTable này là đối tượng trung gian quan trọng nhất: Nó được dùng để lấy dữ liệu từ file vào, sau đó đổ lên dataGridview để kiểm tra (có thể bỏ đoạn này nếu muốn), nếu dữ liệu hiện ra trên Grid đúng thì sẽ làm động tác cuối cùng là đổ dữ liệu vào Database bằng cách dùng câu SQL Insert quen thuộc (thủ tục thứ tư).
PHP Code:
class clsImport
{
//Khai bao mot Datatable de dung chung
public DataTable m_dtCSV = new DataTable();
public Int32 m_iColumnCount = 0;
//Thu tuc thu 1 (tao ra mot DataTable tam co dinh dang giong het file Excel)
public void PopulateDataTableFromUploadedFile(System.IO.Stream strm)
{
System.IO.StreamReader srdr = new System.IO.StreamReader(strm);
String strLine = String.Empty;
Int32 iLineCount = 0;
do
{
strLine = srdr.ReadLine();
if (strLine == null)
{
break;
}
if (0 == iLineCount++)
{
m_dtCSV = this.CreateDataTableForCSVData(strLine);
}
this.AddDataRowToTable(strLine, m_dtCSV);
} while (true);
}
//Thu tuc thu 2 (duoc goi boi 1)
private DataTable CreateDataTableForCSVData(String strLine)
{
DataTable dt = new DataTable("CSVTable");
String[] strVals = strLine.Split(new char[] { '\t' });
Int32 m_iColumnCount = strVals.Length;
int idx = 0;
foreach (String strVal in strVals)
{
idx++;
String strColumnName = "Column" + Convert.ToString(idx);
dt.Columns.Add(strColumnName, Type.GetType("System.String"));
}
return dt;
}
//Thu tuc thu 3 (duoc goi boi 1)
private DataRow AddDataRowToTable(String strCSVLine, DataTable dt)
{
String[] strVals = strCSVLine.Split(new char[] { '\t' });
Int32 iTotalNumberOfValues = strVals.Length;
int idx = 0;
DataRow drow = dt.NewRow();
foreach (String strVal in strVals)
{
//String strColumnName = String.Format("Column-{0}", idx++);
idx++;
String strColumnName = "Column" + Convert.ToString(idx);
drow[strColumnName] = strVal.Trim().ToString();
}
dt.Rows.Add(drow);
return drow;
}
//Thu tuc thu 4 (Insert du lieu tu DataTable vao Database co ten la Test, co bang Project_Library)
public void InsertDB() // insert manually into Project_Library
{
try
{
SqlConnection con1 = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlCommand cmd1 = new SqlCommand();
cmd.Connection = con1;
cmd.CommandType = CommandType.Text;
con1.Open();
for (int i = 0; i <= m_dtCSV.Rows.Count-1; i++) //Dong
{
int j = 0; //Cot
{
cmd.CommandText = "Insert into Project_Library (Temp1,Temp2,Temp3,Temp4,Temp5) values ('" + m_dtCSV.Rows[i].ItemArray.GetValue(j) + "','" + m_dtCSV.Rows[i].ItemArray.GetValue(j += 1) + "','" + m_dtCSV.Rows[i].ItemArray.GetValue(j += 1) + "','" + m_dtCSV.Rows[i].ItemArray.GetValue(j += 1) + "','" + m_dtCSV.Rows[i].ItemArray.GetValue(j += 1) + "')";
}
cmd.ExecuteNonQuery();
}
con1.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Info");
}
}