将txt文件写进excel中
#region 将文本文件写进dataGridView,然后写进excel中
DataTable dt = new DataTable();
dt.Columns.Add("学生编号", typeof(string));
dt.Columns.Add("学生姓名", typeof(string));
dt.Columns.Add("学生密码", typeof(string));
dt.Columns.Add("学生描述", typeof(string));
using (StreamReader sr = new StreamReader(fileName, Encoding.UTF8))
{
while (!sr.EndOfStream)
{
string[] strs = sr.ReadLine().Split(',');
DataRow dr= dt.NewRow();
dr[0]= strs[0];
dr[1] = strs[1];
dr[2] = strs[2];
dr[3] = strs[3];
dt.Rows.Add(dr);
}
dataGridView1.DataSource = dt;
}
string saveFileName = "";
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel 97-2003|*.xls|Excel2007及以上|*.xlsx";
sfd.Title = "选择Excel文件保存的位置";
if (sfd.ShowDialog() == DialogResult.OK)
{
saveFileName = sfd.FileName;
}
ExcelHelper.DataTableToExcel(dt, saveFileName, "Sheet1", true);
#endregion
将txt文件写进sqlserver中
using (StreamReader sr=new StreamReader(fileName,Encoding.UTF8))
{
sr.ReadLine();
#region 写进数据库
while (!sr.EndOfStream)
{
string[] strs = sr.ReadLine().Split(',');
string sql = string.Format("insert into UserInfos (UserName,UserPwd,Describe) values ('{0}','{1}','{2}')", strs[1], strs[2], strs[3]);
SqlHelper.ExecuteNonQuery(sql,1);
}
#endregion
}