怎么在ASP.Net中动态读取Excel文件?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
Default.aspx.cs代码:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
delete();
}
protected void Button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter da = new OleDbDataAdapter();
DataSet ds = new DataSet();
string query = null;
string connString = "";
string strFileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
//string strFileName = Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName);
string strFileType = Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
if (strFileType == ".xls" || strFileType == ".xlsx")
{
FileUpload1.SaveAs(Server.MapPath("~/UploadedExcel/" + strFileName + strFileType));
}
else
{
return;
}
string strNewPath = Server.MapPath("~/UploadedExcel/" + strFileName + strFileType);
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strNewPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
query = "SELECT * FROM [Sheet1$]";
conn = new OleDbConnection(connString);
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
try
{
cmd = new OleDbCommand(query, conn);
da = new OleDbDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
Label1.Text = "读取成功";
}
catch (Exception ex)
{
Label1.Text = "读取失败";
Response.Write(ex);
}
finally
{
da.Dispose();
conn.Close();
conn.Dispose();
}
}
//定时任务
private void delete()
{
DirectoryInfo di = new DirectoryInfo(Server.MapPath("/UploadedExcel/"));
FileInfo[] fi = di.GetFiles("*." + "*");
DateTime dtNow = DateTime.Now;
foreach (FileInfo tmpfi in fi)
{
TimeSpan ts = dtNow.Subtract(tmpfi.LastWriteTime);
if (ts.Milliseconds > 100)
{
tmpfi.Attributes = FileAttributes.Normal;
tmpfi.Delete();
}
}
}
}
}
ASP.NET 是开源,跨平台,高性能,轻量级的 Web 应用构建框架,常用于通过 HTML、CSS、JavaScript 以及服务器脚本来构建网页和网站。
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。