首页 > 代码库 > 自学.net(2)数据的导入和导出

自学.net(2)数据的导入和导出

 1 using Microsoft.Win32; 2 using System; 3 using System.Collections.Generic; 4 using System.Data.SqlClient; 5 using System.IO; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows;10 using System.Windows.Controls;11 using System.Windows.Data;12 using System.Windows.Documents;13 using System.Windows.Input;14 using System.Windows.Media;15 using System.Windows.Media.Imaging;16 using System.Windows.Navigation;17 using System.Windows.Shapes;18 19 namespace wenjianduqu20 {21     /// <summary>22     /// MainWindow.xaml 的交互逻辑23     /// </summary>24     public partial class MainWindow : Window25     {26         public MainWindow()27         {28             InitializeComponent();29         }30 31         private void btnImport_Click(object sender, RoutedEventArgs e)32         {33             OpenFileDialog ofg = new OpenFileDialog();34             ofg.Filter = "文本文件|*.txt";
         //如果没选择任何文件,则返回
35 if (ofg.ShowDialog()!=true)36 {37 return;38 }39 string filename = ofg.FileName;
          //返回的是一个数组,所以要用IEnumerable接口
40 IEnumerable<string> lines = File.ReadLines(filename,Encoding.Default);
            //需要考虑数据读取和写入的编码问题,所以要用Encoding.Default,要不然会出乱码
41 foreach (string line in lines)42 {43 string[]segs=line.Split(|);44 string name=segs[0];45 string age=segs[1];46 SqlHelper.ExecuteNonQuery("insert into T_Customer (Name,Age)
              values(@Name,@Age)
",47 new SqlParameter("@Name", name), new SqlParameter("@Age",
              Convert.ToInt32(age)));
48 }49 MessageBox.Show("导入成功!成功导入"+lines.Count()+"条数据");50 } 51 }52 }

 

自学.net(2)数据的导入和导出