lấy dữ liệu từ file txt thì sao bạn, mình thấy từ file txt dễ hơn đúng không ?
bạn viết giúp mình code khi xử lý với file txt được không ?
Thì dùng StreamReader mà đọc hết tất cả các dòng rồi xử lý thôi. Với mỗi dòng bạn phải thực hiện Split('|') để cắt chuỗi rồi đưa vào 1 mảng chứa các object sau khi cắt thôi. Việc còn lại là gắn các object đó vào datatable và hiển thị Grid thôi.
Mình có đoạn code cho bạn tham khảo:
Đầu tiên chọn thư mục chứa file và load vào 1 ListBox
Mã:
private void btnChoose_Click(object sender, EventArgs e)
{
// Đường dẫn mặc định, nếu chưa chọn thư mục thì Load đường dẫn này
string strPath = "C:\\Desktop\\TextFile";
//Mình tạo 1 List Box chứa các file đc chọn. Phát triển cho trường hợp muốn chọn nhiều file 1 lúc
lstListSource.Items.Clear();
FolderBrowserDialog fi = new FolderBrowserDialog();
if (txtFileName.Text.Trim() != string.Empty)
{
fi.SelectedPath = txtFileName.Text.Trim();
}
else
{
fi.SelectedPath = strPath;
}
DialogResult result = fi.ShowDialog();
if (result == DialogResult.OK)
{
string[] files = Directory.GetFiles(fi.SelectedPath, "*.txt", SearchOption.TopDirectoryOnly);
foreach (string file in files)
{
string strFile = file.Substring(file.LastIndexOf("\\") + 1);
lstListSource.Items.Add(strFile);
}
// Hiển thị đường dẫn thư mục
this.txtFileName.Text = fi.SelectedPath;
}
}
- Sau đó lựa chọn 1 file trong ListBox và tiến hành xử lý dữ liệu
Mã:
private void btnAccecpt_Click(object sender, EventArgs e)
{
// Lấy đường dẫn của file được chọn để load dữ liệu
string filename = txtFileName.Text + "\\" + lstListSource.SelectedItem.ToString();
DataTable dt= new DataTable();
DataRow dr=null;
string strOutput = null;
string[] strArr = null;
string[] strArrItem = null;
// Trường hợp select nhiều file thì foreach(string sFile in lstListSource.SelectedItem) và add từng đường dẫn file vào 1 mảng,
//khi xử lý thì lấy đường dẫn file ra mà xử lý
//Sử dụng StreamReader để đọc từng dòng trong file txt
using (StreamReader sr = new StreamReader(filename))
{
strOutput = sr.ReadToEnd();
strArr = null;
char[] kytu = { '
', '
' }; // ký tự xuống dòng
// Cắt chuỗi theo từng dòng, mỗi dòng vào 1 object trong mảng
strArr = strOutput.Split(kytu, StringSplitOptions.RemoveEmptyEntries);
// Add cột chưa dữ liệu
dt.Columns.Add("");
dt.Columns.Add("");
for (int i = 0; i <= strArr.Length - 1; i++)
{
strArrItem = strArr[i].Split('|');
dr = dt.NewRow();
dr[0] = strArrItem[0].ToString().Trim();
dr[1] = strArrItem[1].ToString().Trim();
dt.Rows.Add(dr);
}
gdcData.DataSource = dt;
}
}
Giảm giá khi mua pallet nhựa Trà Vinh Tại Trà Vinh, một trong những địa điểm nổi tiếng với ngành nông nghiệp và sản xuất, pallet nhựa Trà Vinh đóng vai trò không thể phủ nhận trong quá trình vận...
Giảm giá khi mua pallet nhựa Trà...