vs2010中导入所选的Excel文件的第一个sheet到GridView C#语言实现

1、创建一个 新空页.aspx

2、拖入三个控件

   html控件: input(file) 在html代码中 runat=“server” 用于获得所选excel文件的全路径

   button控件 单击导入

  GridView控件 显示导入表格

3、添加引用

引用.com中的:micsoft office **.* object library
引用.net中的:micsoft.office.interop.excel

4、添加命名空间

using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
using Microsoft.Office.Core;
using Microsoft.Office.Interop;

5、全部代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
using Microsoft.Office.Core;
using Microsoft.Office.Interop;
/*  增加命名控件
  using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
using Microsoft.Office.Core;
using Microsoft.Office.Interop;
 * 
 */
//在HTML页中添加属性runat="server"
//引用.com中的:micsoft office **.* object library
//引用.net中的:micsoft.office.interop.excel

namespace test1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
         
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            #region
            //获取文件全路径
            string pPath = File1.Value.ToString();
            //调用文件的table 作为数据控件的数据源 并进行绑定
            GridView1.DataSource = LoadExcel(pPath);
            GridView1.DataBind();

            #endregion


        }


      //载入选择excel文件第一个sheet的工作表到 table
        public DataTable LoadExcel(string pPath)
        {
            #region  载入全路径名为 ppath 的excel 返回 table
            string connString = "Driver={Driver do Microsoft Excel(*.xls)};DriverId=790;SafeTransactions=0;ReadOnly=1;MaxScanRows=16;Threads=3;MaxBufferSize=2024;UserCommitSync=Yes;FIL=excel 8.0;PageTimeout=5;";
            connString += "DBQ=" + pPath;
            OdbcConnection conn = new OdbcConnection(connString);
            OdbcCommand cmd = new OdbcCommand();
            cmd.Connection = conn;
            //获取Excel中第一个Sheet名称,作为查询时的表名
            string sheetName = this.GetExcelSheetName(pPath);
            string sql = "select * from [" + sheetName.Replace('.', '#') + "$]";
            cmd.CommandText = sql;
            OdbcDataAdapter da = new OdbcDataAdapter(cmd);
            DataSet ds = new DataSet();
            try
            {
                da.Fill(ds);
                return ds.Tables[0];
            }
            catch (Exception x)
            {
                ds = null;
                throw new Exception("从Excel文件中获取数据时发生错误!");
            }
            finally
            {
                cmd.Dispose();
                cmd = null;
                da.Dispose();
                da = null;
                if (conn.State == ConnectionState.Open)
                {
                    conn.Close();
                }
                conn = null;
            }

             #endregion
        }

       //获取表名
        private string GetExcelSheetName(string pPath)
        {
           
            #region 获取sheet表名

            //打开一个Excel应用

            Microsoft.Office.Interop.Excel.Application _excelApp = new Microsoft.Office.Interop.Excel.Application();
            if (_excelApp == null)
            {
                throw new Exception("打开Excel应用时发生错误!");
            }
            Microsoft.Office.Interop.Excel.Workbooks _books = _excelApp.Workbooks;
            //打开一个现有的工作薄
            Microsoft.Office.Interop.Excel.Workbook _book = _books.Add(pPath);
            Microsoft.Office.Interop.Excel.Sheets _sheets = _book.Sheets;
            //选择第一个Sheet页
            
            string sheetName = _sheets.get_Item(1).Name;

   
            ReleaseCOM(_sheets);
            ReleaseCOM(_book);
            ReleaseCOM(_books);
            _excelApp.Quit();
            ReleaseCOM(_excelApp);
            return sheetName;
             #endregion
        }


        //释放控件
        private void ReleaseCOM(object pObj)
        {
            #region 释放端口
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pObj);
            }
            catch
            {
                throw new Exception("释放资源时发生错误!");
            }
            finally
            {
                pObj = null;
            }
            #endregion

        }




    }
}

 

注:修改了http://www.cnblogs.com/zoupeiyang/边写边唱 博客中的代码来实现的

 

 

 

posted @ 2012-06-16 01:25  老沙  阅读(1110)  评论(0编辑  收藏  举报