首先添加命名空間
複製代碼 代碼如下: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;
}
}
asp.net 讀取並顯示excel資料的實現代碼
在Asp.net用C#建立動態Excel
asp.net 操作excel的實現代碼