疯子的博客

做一件事,专注一件事
Excel表格数据导入导出数据库


一.导入数据库

能找到的方法大概有三种;

1.     excel转换为文本文件。转换后根据表格之间的分隔符获取各个字段,再一条一条导入,比较麻烦,先要转换文件格式(另存为)。

2.     在项目中引用excelcom组建。需要服务器安装excel,代码页比较麻烦。

3.     直接当做数据库使用,用System.Data.OleDb命名空间下的类。下面是个例子,用起来比较简单。

Code
using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Data.OleDb;

public partial class department_importstu : System.Web.UI.Page

{

    
protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    
protected void Button1_Click(object sender, EventArgs e)

    {

        
if (FileUpload1.PostedFile != null)

        {

            Random rd 
= new Random(1);

            
string filename = DateTime.Now.Date.ToString("yyyymmdd"+ DateTime.Now.ToLongTimeString().Replace(":"""+ rd.Next(9999).ToString() + ".xls";

            FileUpload1.PostedFile.SaveAs(@Server.MapPath(
"files/"+ filename);

            
string conn = "Provider=Microsoft.Jet.Oledb.4.0;Data Source   =" + Server.MapPath("files"+ "/" + filename + ";;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";   

            
string sql = "select   *   from   [table1$]";

            OleDbConnection thisconnection 
= new OleDbConnection(conn);

            thisconnection.Open();

            OleDbDataAdapter mycommand 
= new OleDbDataAdapter(sql, thisconnection);

            DataTable dt 
= new DataTable();

            mycommand.Fill(dt);

            thisconnection.Close();

            
string xb, zy, bj, xm, xh, dh, qq, email,nn;

            
string logfile =DateTime.Now.ToString("yyyy dd mm hh mm")+".log";

            
int badcount=0;

           

            
for (int i = 1;i < dt.Rows.Count;i++ )

            {

                xh 
= dt.Rows[i][4].ToString();

                
if (validatahx(xh))

                { 

                    
try{

                        xb 
= Getdptid(dt.Rows[i][0].ToString());

                        zy 
= Getspeid(dt.Rows[i][1].ToString());

                        bj 
= Getclassid(dt.Rows[i][2].ToString());

                        xm 
= dt.Rows[i][3].ToString();    

                        dh 
= dt.Rows[i][5].ToString();

                        qq 
= dt.Rows[i][6].ToString();

                        email 
= dt.Rows[i][7].ToString();

                        nn
=dt.Rows[i][8].ToString();

                        
string insertstr = "insert into tb_StuInfo(Dpt_ID,Spe_ID,Cla_ID,Stu_Name,Stu_Xuehao,Stu_Pwd,Stu_Sex,Stu_Qq,Stu_Email,Stu_Phone) values "+"(" + xb + "," + zy + "," + bj + ",'" + xm+ "','" + xh +"','123','" + nn + "','" + qq + "','" + email + "','" + dh + "')";

                        DB.execnonsql(insertstr);

                    }

                    
catch (System.Exception e1)

                    {

                        badcount
++;

                        LogManager.Writefile(Server.MapPath(
@"~\log"+ @"\" + logfile,"学号:"+xh+e1.Message);

                    }

                }
else{

                        badcount
++;

                        LogManager.Writefile(Server.MapPath(
@"~\log"+ @"\" + logfile,"学号:"+xh+ "  学号存在" );

                }          

            }

            
this.HyperLink2.NavigateUrl = @"~\log\" + logfile;

            
this.HyperLink2.Text = "" + badcount+"条错误,点击查看";

            
this.HyperLink2.Visible = true;

        }

    }

    
protected string Getdptid(string name)

    {

        
string ret = DB.FindString("select dpt_id from tb_department where dpt_name='" + name + "'");

        
if (ret.Equals(""|| ret == null)

        {

            
throw new Exception("学院名错误");

        }

        
return ret;

    }

    
protected string Getspeid(string name)

    {

        
string ret = DB.FindString("select spe_id from tb_specialty where spe_name='" + name + "'");

        
if (ret.Equals(""|| ret == null)

        {

            
throw new Exception("专业名错误");

        }

        
return ret;

    }

    
protected string Getclassid(string name)

    {

        
string ret = DB.FindString("select cla_id from tb_class where cla_name='" + name + "'");

        
if (ret.Equals(""|| ret == null)

        {

            
throw new Exception("班级名错误");

        }

        
return ret;

    }

    
protected bool validatahx(string xh)

    {

        
if (DB.FindString("select stu_Xuehao from tb_StuInfo where Stu_Xuehao='" + xh + "'").Equals(""))

        {

            
return true;

        }

        
return false;

    }

}

二.导出到excel

1.  和导入数据库相反你可以先将数据库里的数据转换为文本格式,用特定的字符隔开,要用的地方直接用excel打开即可,但很显然这样的话要手工参与。

2.  引用Com组建,和导入一样麻烦

3.  同样当做数据库处理,调用ado.net。不过据说容易出错。

4.  利用数据库控件,如gridview

            

Code
 Response.Charset = "UTF-8";

        Response.ContentEncoding 
= System.Text.Encoding.UTF8;

        Response.ContentType 
= "application/ms-excel";

        Response.AppendHeader(
"Content-Disposition""attachment;filename=" + "" + filename);

        GridView1.Page.EnableViewState 
= false;

        System.IO.StringWriter tw 
= new System.IO.StringWriter();

        HtmlTextWriter hw 
= new HtmlTextWriter(tw);

        GridView1.RenderControl(hw);

        Response.Write(tw.ToString());

        Response.End();

posted on 2009-10-09 07:29  老陈  阅读(6091)  评论(0)    收藏  举报