因为输入数据是以excel表格式存储的,计算时需要将excel表格式导入数据库,然后datagrid控件显示于界面。这只是我个人的想法,打算这样实现,急于请教各位高手,有没有好的办法呢?先谢过。

解决方案 »

  1.   

    private void Button1_Click(object sender, System.EventArgs e)
    {
    // 获取Excel文件的完整路径
    string source=this.File1.PostedFile.FileName.ToString();

    if(""!=source)
    {
    //取得文件类型        
    string filename=Path.GetFileName(source);
    //取得文件扩展名
    string fileType= source.Substring(source.LastIndexOf(".")+1);
    //判断是否是xls文件
    if("xls" != fileType)
    {
    Response.Write("<script language='javascript'> alert('对不起!请您选择EXCEL文件!');</script>");
    return;
    }
    }
    else
    {
    return;
    }
    //
    DataSet DSexcel=GetDSFromExcel(source);

    // 数据绑定
    this.DataGrid1.DataSource = DSexcel;
    this.DataGrid1.Columns[0].Visible=false;//掩藏第0列考勤时间
    this.DataGrid1.Columns[1].Visible=false;//掩藏第1列个人代码
    this.DataGrid1.DataMember = "[Sheet1$]";
    this.DataGrid1.DataBind(); //获得原数据表名并传给ToDB()将数据导进SQL表中
             DataTable DTexcel=DSexcel.Tables[0];
    ToDB(DTexcel);
    this.Label2.Visible=true;
    this.Label2.Text="<font size=2 color=red>数据导入成功</font>";
    } /// <summary>
    /// 填充表格并返回表
    /// </summary>
    /// <param name="source"></param>
    /// <returns></returns>
    public static DataSet GetDSFromExcel(string source)
    {
    try
    {
    string ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + source + ";Extended Properties=Excel 8.0";
    string query = "SELECT * FROM [Sheet1$]"; OleDbCommand oleCommand = new OleDbCommand(query, new OleDbConnection(ConnStr));
    OleDbDataAdapter oleAdapter = new OleDbDataAdapter(oleCommand);
    DataSet myDataSet = new DataSet(); // 将 Excel 的[Sheet1]表内容填充到 DataSet 对象
    oleAdapter.Fill(myDataSet, "[Sheet1$]");
    return myDataSet;
    }
    catch(System.Data.OleDb.OleDbException oe)
    {
    throw new Exception("ERROR:"+oe.ToString());
    }
    }

    /// <summary>
    /// 将表格数据导进SQL表
    /// </summary>
    public static void ToDB(DataTable tab)
    {
    DataRow empRow=null;
    try
    {
    if(Con.State==System.Data.ConnectionState.Closed)
    {
    Con.Open();
    }
    //获取表结构
    SqlCommand  selcmd=new SqlCommand("select * from 考勤",Con);
    SqlDataAdapter adapter=new SqlDataAdapter(selcmd);
    //创建 SqlCommandBuilder 对象,并和 SqlDataAdapter 关联
    SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
    DataSet ds=new DataSet();
    adapter.Fill(ds,"考勤"); // 从第二行开始读取数据填充到SQL表
    for(int i=0;i<tab.Rows.Count;i++)
    {
    //创建新行
    empRow=ds.Tables["考勤"].NewRow();
    for(int j=0;j<tab.Columns.Count;j++)
    {
    if(tab.Rows[i][j].ToString()!="")   
    empRow[j]=(string)tab.Rows[i][j].ToString();
    }
    //添加此行到表中
    ds.Tables["考勤"].Rows.Add(empRow);
    }
    //更新表到数据集中
    adapter.Update(ds,"考勤");
    }
    catch(System.Data.SqlClient.SqlException ex)
    {
    throw new Exception(ex.ToString());
    }
    finally
    {
    Con.Close();
    }
       }
    }找到了一个很久前的练习,是通过的.仅供参考.