职业IT人-IT人生活圈

 找回密码
 成为会员
搜索
查看: 4868|回复: 14

请高手帮忙txt中确切选中某行读取,并导入数据库表代码?

[复制链接]
.net青青 发表于 2007-3-7 13:14 | 显示全部楼层 |阅读模式
现在的txt文本中,虽然也是按那个表列有空格隔开,但是现在问题是用户不需要全部的这些列,只需要其中的某几列,交要求存入SQL数据库里同的某一个表里面?如何做啊?要求用C#代码编写!
梦段桥 发表于 2007-3-7 14:34 | 显示全部楼层
首先一行一行读,读第一行的时候是列名,从第二行起是列对应的值,把这些值放到不同的数组里,需要哪个列,就调用哪个数组出来!
你把你TXT中的几行数据贴上来
蓝色梦幻 发表于 2007-3-8 01:18 | 显示全部楼层
这里有了一个列子,只不过还没有测试到有空字段的情况, 算不上一个完整版,暂时贴出来而已
string fPath=this.fName.PostedFile.FileName;//获得要导入的文本文件                  
                        string extName=fPath.Substring(fPath.LastIndexOf(".")+1);//获得文件的扩展名            
                        SqlConnection con=new SqlConnection("server=.;database=WitKey;uid=sa;pwd=accp.includein;");//数据库连接对象
                        con.Open();
                        StreamReader sr=File .OpenText (fPath);
                        string input;
                        string one="",two="",three="",four="";
                        while((input=sr.ReadLine ())!=null)
                        {
                                //input=input.Replace (' ','空');
                                string[] small=input.Split (' ');
                                for(int i=0;i<small.Length ;i++)//第一列的时候
                                {
                                        //取列的数组
                                                                       
                                                 one=small[0];//第一列
                                             three=small[4];//第二列
                                                 
                                }
                                two=two+","+one;
                                four=four+","+three;
                        }
                        Response .Write (four);
                        input=sr.ReadLine ();
      
                        sr.Close ();
                        //取得的数组的值插入数据库
                        string [] sqlone=two.Split (',');
                        string [] sqltwo=four.Split (',');
                        for(int j=0;j<sqlone.Length ;j++)
                        {
                          string strsql="insert into test1(id,name)values('"+sqlone[j]+"','"+sqltwo[j]+"')";
                          SqlCommand com=new SqlCommand (strsql,con );
                          com.ExecuteNonQuery ();
                          Response.Write("<script language=javascript>alert('数据导入成功!')</script>");
                        }
                        con.Close ();
蓝色梦幻 发表于 2007-3-10 00:14 | 显示全部楼层
这个答案是<梦段桥>网友大侠的劳动果实,不过本人就在这里做个过渡:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;
namespace TXT文件解析
{
        /// <summary>
        /// Form1 的摘要说明。
        /// </summary>
        public class Form1 : System.Windows.Forms.Form
        {
                private System.Windows.Forms.DataGrid dataGrid1;
                private System.Windows.Forms.TextBox textBox1;
                private System.Windows.Forms.Button button1;
                private System.Windows.Forms.OpenFileDialog openFileDialog1;
                private System.Windows.Forms.Button button2;
                /// <summary>
                /// 必需的设计器变量。
                /// </summary>
                private System.ComponentModel.Container components = null;

                ArrayList title = new ArrayList();
                ArrayList value = new ArrayList();
                ArrayList valueMaxLen = new ArrayList();
                private System.Windows.Forms.ComboBox comboBox1;
                private System.Windows.Forms.Button button3;
                DataTable dt=new DataTable("TXT");
                public Form1()
                {
                        //
                        // Windows 窗体设计器支持所必需的
                        //
                        InitializeComponent();

                        //
                        // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
                        //
                }

                /// <summary>
                /// 清理所有正在使用的资源。
                /// </summary>
                protected override void Dispose( bool disposing )
                {
                        if( disposing )
                        {
                                if (components != null)
                                {
                                        components.Dispose();
                                }
                        }
                        base.Dispose( disposing );
                }

                #region Windows 窗体设计器生成的代码
                /// <summary>
                /// 设计器支持所需的方法 - 不要使用代码编辑器修改
                /// 此方法的内容。
                /// </summary>
                private void InitializeComponent()
                {
                        this.dataGrid1 = new System.Windows.Forms.DataGrid();
                        this.textBox1 = new System.Windows.Forms.TextBox();
                        this.button1 = new System.Windows.Forms.Button();
                        this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
                        this.button2 = new System.Windows.Forms.Button();
                        this.comboBox1 = new System.Windows.Forms.ComboBox();
                        this.button3 = new System.Windows.Forms.Button();
                        ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
                        this.SuspendLayout();
                        //
                        // dataGrid1
                        //
                        this.dataGrid1.DataMember = "";
                        this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
                        this.dataGrid1.Location = new System.Drawing.Point(0, 32);
                        this.dataGrid1.Name = "dataGrid1";
                        this.dataGrid1.Size = new System.Drawing.Size(648, 472);
                        this.dataGrid1.TabIndex = 0;
                        //
                        // textBox1
                        //
                        this.textBox1.Location = new System.Drawing.Point(8, 3);
                        this.textBox1.Name = "textBox1";
                        this.textBox1.Size = new System.Drawing.Size(176, 21);
                        this.textBox1.TabIndex = 1;
                        this.textBox1.Text = "";
                        //
                        // button1
                        //
                        this.button1.Location = new System.Drawing.Point(184, 3);
                        this.button1.Name = "button1";
                        this.button1.Size = new System.Drawing.Size(48, 23);
                        this.button1.TabIndex = 2;
                        this.button1.Text = "选择";
                        this.button1.Click += new System.EventHandler(this.button1_Click);
                        //
                        // button2
                        //
                        this.button2.Location = new System.Drawing.Point(592, 4);
                        this.button2.Name = "button2";
                        this.button2.Size = new System.Drawing.Size(48, 23);
                        this.button2.TabIndex = 2;
                        this.button2.Text = "显示";
                        this.button2.Click += new System.EventHandler(this.button2_Click);
                        //
                        // comboBox1
                        //
                        this.comboBox1.Location = new System.Drawing.Point(240, 4);
                        this.comboBox1.Name = "comboBox1";
                        this.comboBox1.Size = new System.Drawing.Size(121, 20);
                        this.comboBox1.TabIndex = 3;
                        //
                        // button3
                        //
                        this.button3.Location = new System.Drawing.Point(368, 3);
                        this.button3.Name = "button3";
                        this.button3.Size = new System.Drawing.Size(80, 23);
                        this.button3.TabIndex = 2;
                        this.button3.Text = "删除指定列";
                        this.button3.Click += new System.EventHandler(this.button3_Click);
                        //
                        // Form1
                        //
                        this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
                        this.ClientSize = new System.Drawing.Size(648, 502);
                        this.Controls.Add(this.comboBox1);
                        this.Controls.Add(this.button1);
                        this.Controls.Add(this.textBox1);
                        this.Controls.Add(this.dataGrid1);
                        this.Controls.Add(this.button2);
                        this.Controls.Add(this.button3);
                        this.Name = "Form1";
                        this.Text = "Form1";
                        this.Load += new System.EventHandler(this.Form1_Load);
                        ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
                        this.ResumeLayout(false);

                }
                #endregion

                /// <summary>
                /// 应用程序的主入口点。
                /// </summary>
                [STAThread]
                static void Main()
                {
                        Application.Run(new Form1());
                }

                private void button1_Click(object sender, System.EventArgs e)
                {
                        if(this.openFileDialog1.ShowDialog()==DialogResult.OK)
                        {
                                this.textBox1.Text=this.openFileDialog1.FileName;
                        }
                }

                private void button2_Click(object sender, System.EventArgs e)
                {
                        int hulue = 0;//Int32.Parse(this.textBox2.Text);
                        hulue=10;
                        string FilePath = @textBox1.Text;
                       
                        StreamReader sr = new StreamReader(@FilePath, System.Text.Encoding.GetEncoding("GB2312"), true);
                        //先读第10行 ,列名
                        string lie = "";
                        for (int i = 0; i < hulue; i++)
                        {
                                lie = sr.ReadLine();
                        }
                        string line = "";
                        foreach (char c in lie)
                        {
                                if (c == ' ')
                                {
                                        if (line.Trim() != null && line.Trim() != "")
                                        {
                                                title.Add(line);
                                                line = "";
                                        }
                                }
                                else
                                {
                                        line = line + c;
                                }
                        }
                        title.Add(line);
                        /*填充列*/
            for (int i = 0; i < title.Count; i++)
                        {
                                DataColumn dc=new DataColumn();
                                dc.ColumnName=title.ToString();
                                this.dt.Columns.Add(dc);
                        }
                        /*读出列的值*/


                        //读取个个列的长度
                        string str1 = sr.ReadLine();
                        int ii = 0;
                        int jsq = 0;
                        string temp = "";
                        foreach (char c in str1)
                        {
                                if (c == ' ')
                                {
                                        //结束的条件
                                        if (temp.Substring(temp.Length - 1) != " ")
                                        {
                                                if (jsq != 0)
                                                {
                                                        valueMaxLen.Add(jsq.ToString());
                                                        jsq = 0;
                                                        temp = "";
                                                }

                                        }

                                }
                                else if (c != ' ')
                                {
                                        //开始的条件
                                        if (jsq == 0)
                                        {
                                                jsq++;
                                        }
                                                //继续的条件
                                        else if (temp.Substring(temp.Length - 1) != " ")
                                        {
                                                jsq++;
                                        }

                                }
                                temp += c;
                                ii++;
                        }
                        valueMaxLen.Add(jsq.ToString());
                        if (valueMaxLen.Count != title.Count)
                        {
                                MessageBox.Show("读取的列个数和txt文本中的个数不一样");
                                return;
                        }
                        int[] lieLen = new int[this.title.Count];//每列最大长度
                        for (int i = 0; i < valueMaxLen.Count; i++)
                                lieLen = Int32.Parse(valueMaxLen.ToString());
                        /*一行一行的解析值*/
                        jsq = 0;

                        while (sr.Peek() > -1)
                        {

                                string hang = sr.ReadLine();
                                if (hang.Trim().Substring(0, 1) == "-")
                                        break;
                                int i = 0, backi = 0, iii = 0;
                                ArrayList arr = new ArrayList();

                                foreach (char c in hang)
                                {
                                        //最开始
                                        if (backi == 0)
                                        {
                                                string temp2 = hang.Substring(0, lieLen[iii]);
                                                //检测中文字符数量
                                                int chineseJsq = 0;//中文字符数量计数器
                                                foreach (char cc in temp2)
                                                {
                                                        if (cc >= 21 && cc <= 172)
                                                        {
                                                        }
                                                        else
                                                                chineseJsq++;
                                                }
                                                if (chineseJsq != 0)
                                                {
                                                        temp2 = temp2.Substring(temp2.Length - chineseJsq);
                                                        arr.Add(temp2);
                                                }
                                                else
                                                        arr.Add(temp2);

                                                backi = (lieLen[iii] + 2);
                                                backi = backi - chineseJsq;
                                                iii++;
                                                //MessageBox.Show("ok"+temp2+"ok");
                                        }
                                                //下一个
                                        else if (i == backi)
                                        {
                                                //最后一个
                                                if (iii == (lieLen.Length - 1))
                                                {
                                                        arr.Add(hang.Substring(backi));
                                                        break;
                                                }
                                                string temp2 = hang.Substring(backi, lieLen[iii]);
                                                //检测中文字符数量
                                                int chineseJsq = 0;//中文字符数量计数器
                                                foreach (char cc in temp2)
                                                {
                                                        if (cc >= 21 && cc <= 172)
                                                        {
                                                        }
                                                        else
                                                                chineseJsq++;
                                                }
                                                if (chineseJsq != 0)
                                                {
                                                        temp2 = temp2.Substring(0, (temp2.Length - chineseJsq));
                                                        arr.Add(temp2);
                                                }
                                                else
                                                        arr.Add(temp2);
                                                backi = (backi + (lieLen[iii] + 2));
                                                backi = backi - chineseJsq;
                                                iii++;
                                                //MessageBox.Show("ok"+temp2+"ok");

                                                //bb = true;
                                        }

                                        i++;

                                }
                                value.Add(arr);
                                jsq++;
                        }
                        sr.Close();
                       
                        /*显示列的值导如DataTable*/
                        for (int i = 0; i < value.Count; i++)
                        {
                                if (i < 10 || (value.Count - i) < 10)
                                {
                                        ArrayList temps = new ArrayList();//保存一行
                                        temps = (ArrayList)value;
                                        DataRow dr=dt.NewRow();
                                        for (int j = 0; j < temps.Count; j++)
                                        {
                                                dr[j]=temps[j].ToString();
                                        }
                                        dt.Rows.Add(dr);
                                       
                                }
                        }
                        this.dataGrid1.DataSource=dt.DefaultView;
                        /*把列名显示在comBox1上**/
                        for(int i=0;i<this.title.Count;i++)
                        {
                                this.comboBox1.Items.Add(title.ToString());
                        }       
                }

                private void Form1_Load(object sender, System.EventArgs e)
                {
               
                }

                private void button3_Click(object sender, System.EventArgs e)
                {
                        dt.Clear();
                        dt=null;
                        dt=new DataTable();
                        this.dataGrid1.DataSource=null;
                        string delTitle=this.comboBox1.Text;
                        for(int i =0 ;i<this.title.Count;i++)
                        {
                                //找到要删除的列
                                if(delTitle==title.ToString())
                                {
                                        //找到后删除列,和列的所有值
                                        title.RemoveAt(i);
                                        title.TrimToSize();
                                        for(int j=0;j<this.value.Count;j++)
                                        {
                                                ArrayList temp =(ArrayList)this.value[j];
                                                this.value.RemoveAt(j);
                                                temp.RemoveAt(i);
                                                temp.TrimToSize();
                                                this.value.Insert(j,temp);
                                               
                                        }
                                        break;
                                }
                        }
                        /*重新填充DataTable*/
                       
                        for (int i = 0; i < title.Count; i++)
                        {
                                DataColumn dc=new DataColumn();
                                dc.ColumnName=title.ToString();
                               
                                this.dt.Columns.Add(dc);
                        }
                        for (int i = 0; i < value.Count; i++)
                        {
                                if (i < 10 || (value.Count - i) < 10)
                                {
                                        ArrayList temps = new ArrayList();//保存一行
                                        temps = (ArrayList)value;
                                        DataRow dr=dt.NewRow();
                                        for (int j = 0; j < temps.Count; j++)
                                        {
                                                dr[j]=temps[j].ToString();
                                        }
                                        dt.Rows.Add(dr);
                                       
                                }
                        }
                        /*更新conBox1状态*/
                        this.comboBox1.Text="";
                        this.comboBox1.Items.Clear();
                        for(int i =0;i<this.title.Count;i++)
                        {
                                this.comboBox1.Items.Add(this.title.ToString());
                        }
                        this.dataGrid1.DataSource=dt.DefaultView;
                }
        }
}
//这是后台代码
前台内容:
就是一个选文件的OpenFileDialog,放文件路径的txtbox,一个下拉框,一个datagrid,二个按钮.
上面代码里面也有了.
梦段桥 发表于 2007-3-10 00:29 | 显示全部楼层
表扬的不够热烈啊!!!
joe 发表于 2007-3-10 00:32 | 显示全部楼层
确实不够热烈.....
蓝色梦幻 发表于 2007-3-11 13:30 | 显示全部楼层
上面由 <梦段桥>大侠做了最经典的从txt读出文本,并展现出来,自由选择删除列的全部功能,我现在就狗尾续貂:
  读出来以后的数据插入sql2000数据库的程序代码:
        private void button4_Click(object sender, System.EventArgs e)
                {
                        SqlConnection con=new SqlConnection ("server=.;database=WitKey;uid=sa;pwd=accp.includein");
                        con.Open ();
                               
                        string inserstr="insert into test1(min_num,name)values(@min_num,@name)";
                        SqlCommand cmd=new SqlCommand (inserstr,con);
                        for(int i=0;i< dt.Rows.Count;i++)//切记这个程序是基于上面《梦》之做上的,所以这个dt ,就是上面程序中声明的Datatable的dt
                        {
                                setDataSet(dataGrid1 ,dt.Rows,cmd ,con);
                        }
                        con.Close ();
                       
                }
                public void setDataSet(DataGrid dataGrid1, DataRow dr,SqlCommand  cmd,SqlConnection  con)//数据导入dataGrid里面的函数
                {
               
                        int count= dataGrid1 .VisibleRowCount ;
                        showtype(cmd);
                        showresult(cmd,dr);
                        try
                        {
                                cmd.ExecuteNonQuery();
                                MessageBox .Show("已成功插入数据库");
                        }
                        catch(Exception e)
                        {
                                MessageBox.Show(e.Message);
                        }
                        finally
                        {
                                con.Close ();
                        }
                }
                public void showtype(SqlCommand  cmd)
                {
                        cmd.Parameters .Add ("@min_num",SqlDbType .VarChar ,50);
                        cmd.Parameters .Add ("@name",SqlDbType .VarChar ,50);
                       
                }
                public void showresult(SqlCommand cmd,DataRow dr)
                {
                        cmd.Parameters["@min_num"].Value=dr["min_num"];
                        cmd.Parameters["@name"].Value=dr["name"];
               
                }
//test1是插入数据库的表名,原文件txt中的列名假设为 min_num,name两列列名,数据库里面的列名也是同样,
 楼主| .net青青 发表于 2007-3-11 13:42 | 显示全部楼层
结帖,本问题全部得到解决,而且得到意外的收获,象<梦段桥>高手所示代码,我都可以随时判断那个列名,新建表都可以用得上!谢谢!
dab 发表于 2010-11-18 11:04 | 显示全部楼层
今天我也来表扬下。
木已 发表于 2011-6-1 13:59 | 显示全部楼层
没有天生的信心,只有不断培养的信心。
hxy 发表于 2011-7-17 10:21 | 显示全部楼层
看你快沉底了~~~~~~
Jethro 发表于 2011-7-22 10:52 | 显示全部楼层
呵呵 没事怎么有点被讽刺的味道啊
Jethro 发表于 2011-8-5 12:13 | 显示全部楼层
楼主福如东海,万寿无疆!
醉倚西风 发表于 2011-8-15 09:42 | 显示全部楼层
哎 天理何在啊??
fl 发表于 2011-8-16 10:45 | 显示全部楼层
不知道说些什么
您需要登录后才可以回帖 登录 | 成为会员

本版积分规则

QQ|手机版|小黑屋|网站帮助|职业IT人-IT人生活圈 ( 粤ICP备12053935号-1 )|网站地图
本站文章版权归原发布者及原出处所有。内容为作者个人观点,并不代表本站赞同其观点和对其真实性负责,本站只提供参考并不构成任何投资及应用建议。本站是信息平台,网站上部分文章为转载,并不用于任何商业目的,我们已经尽可能的对作者和来源进行了通告,但是能力有限或疏忽造成漏登,请及时联系我们,我们将根据著作权人的要求立即更正或者删除有关内容。

GMT+8, 2024-3-29 13:48 , Processed in 0.171709 second(s), 20 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表