您的位置:首页 > 其它

读取Excel文件,将内容存储在DataSet中

2009-09-12 21:01 549 查看
/// <summary>
/// 上传文件
/// </summary>
/// <returns></returns>
private string UploadFile()
{
if (FileUpload1.PostedFile.ContentLength > 0)
{
string UploadFileLastName = FileUpload1.PostedFile.FileName.Substring(FileUpload1.PostedFile.FileName.LastIndexOf(".") + 1);//得到文件的扩展名
Random rnd = new Random();
string UpLoadFileTime = DateTime.Now.ToString("HHmmss") + rnd.Next(9999).ToString("0000"); //生成一个新的数文件名称
string fileName = UpLoadFileTime + "." + UploadFileLastName;//产生上传文件的名称

string saveFile = DateTime.Now.ToString("yyyy/MM").Replace("-", "/") + "/";

string savedDir = System.Web.VirtualPathUtility.Combine(ConfigurationManager.AppSettings["Gwry_UploadPath"].ToString(), saveFile);
string phyDir = this.Page.Server.MapPath(savedDir);
if (!System.IO.Directory.Exists(phyDir))
{
System.IO.Directory.CreateDirectory(phyDir);
}
string path = phyDir + fileName;
FileUpload1.PostedFile.SaveAs(path);
return path;
}
return "";
}

/// <summary>
/// 读取Excel文件,将内容存储在DataSet中
/// </summary>
/// <param name="opnFileName">带路径的Excel文件名</param>
/// <returns>DataSet</returns>
private DataSet ExcelToDataSet(string opnFileName)
{
DataSet ds = new DataSet();
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + opnFileName + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
OleDbConnection conn = new OleDbConnection(strConn);
string strExcel = "";
OleDbDataAdapter myCommand = null;
strExcel = string.Format("select * from [{0}$]", System.Configuration.ConfigurationManager.AppSettings["TableName"].ToString());
try
{
conn.Open();
myCommand = new OleDbDataAdapter(strExcel, strConn);
myCommand.Fill(ds, "dtSource");
return ds;
}
catch (Exception ex)
{
string str = ex.Message;
this.Response.Write(opnFileName + str);
return null;
}
finally
{
conn.Close();
conn.Dispose();
}
}

绑定到GridView:

DataSet ds = new DataSet();
ds = ExcelToDataSet(UploadFile());
this.GridView1.DataSource = ds;
this.GridView1.DataBind();

这里说明下,如果Execl不上传到服务器直接读取的话,可能会有权限问题,所以一定要上传
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: