怎样用C#代码实现将数据库中的记录添加到excel中

怎样用C#代码实现将数据库中的记录添加到excel中
2025-01-27 13:42:51
推荐回答(2个)
回答1:

给你copy一段:

string filename =Application.StartupPath+@"\信息.xls";
            string connstr = @"Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;
Data Source=" + filename + ";Extended Properties='Excel 8.0;HDR=Yes'";//这个链接字符串是excel2003的
            OleDbConnection oleConn = new OleDbConnection(connstr);
            try
            {
                oleConn.Open();
                string sqlStr;
                DataTable dt = oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables_Info, null);
                bool existTable = false;
                foreach (DataRow dr in dt.Rows)//检查是否有信息表
                {
                    if(dr["TABLE_NAME"].ToString()=="信息表$")//要加个$号
                        existTable = true;
                }
                if (!existTable)
                {
                    sqlStr = @"create table 信息表(手机 char(15),姓名 nvarchar(10),生日 char(8),工作 nvarchar(20),邮箱 varchar(30),地址 nvarchar(50))";
                    OleDbCommand oleCmd = new OleDbCommand(sqlStr, oleConn);
                    oleCmd.ExecuteNonQuery();
                }
                string phone = textBox1.Text;
                string name = textBox2.Text;
                string birthday = comboBox1.Text + "/" + comboBox2.Text + "/" + comboBox3.Text;
                string workplace = textBox3.Text;
                string email = textBox4.Text;
                string address = textBox5.Text;
                //下面的代码用OleDbCommand的parameter添加参数
                sqlStr = "insert into 信息表 values('"+phone+"','"+name+"','"+birthday+"','"+workplace+"','"+email+"','"+address+"')";
                OleDbCommand Cmd = new OleDbCommand(sqlStr, oleConn);
                Cmd.ExecuteNonQuery();
            }
            catch (Exception te)
            {
                MessageBox.Show(te.Message);
            }
            finally {
                oleConn.Close();
            }

回答2:

用insert into 命令