ASP.Net接続Excel

8084 ワード

まず名前空間を追加

  
  
  
  
using System.Data.OleDb;

protected void Page_Load( object sender, EventArgs e)
{
if ( ! IsPostBack)
{
strfile
= Request.QueryString[ " filename " ]; //
Excel(strfile);
}
}

private void Excel( string filepath)
{
try
{
Dataset ds
= new DataSet();

string ConnStr = " Provider=Microsoft.Jet.OleDb.4.0;data source= " + filepath +
" ;Extended Properties='Excel 8.0; HDR=YES; IMEX=1' " ; // Excel
string query = " SELECT * FROM [student$] " ; // Excel

OleDbCommand oleCommand
= new OleDbCommand(query, new OleDbConnection(ConnStr));
OleDbDataAdapter oleAdapter
= new OleDbDataAdapter(oleCommand);
oleAdapter.Fill(ds,
" [student$] " );
rowcount
= ds.Tables[ 0 ].Rows.Count;
gridview1.DataSource
= ds;
gridview1.DataBind();

lblmes.Text
= " , , : " ; // lblmes label,
}
catch (OleDbException)
{
string filename = filepath.Substring(filepath.LastIndexOf( ' / ' ) + 1 );
lblmes.Text
= " ! ! : " + filename;
lbtnSure.Visible
= false ;
}

catch (Exception ee)
{
lblmes.Text
= ee.Message;
}
}