首先添加命名空間
復制代碼 代碼如下:
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的實現代碼