本帖最后由 杜鹏 于 2013-6-24 18:07 编辑
/// <summary>
/// 从指定的路径中读取excel,此方法单独写在了ASPNETControlHelper 这个类中;
/// </summary>
/// <param name="fileupload">上传控件名称</param>
/// <param name="savePath">保存的路径</param>
/// <param name="fileExtension">文件的扩展名</param>
/// <returns></returns>
public static string UploadFile(FileUpload fileupload,string savePath,params string[] fileExtension)
{
bool flag = false;
string type = fileupload.FileName.Substring(fileupload.FileName.LastIndexOf('.')+1);
foreach (string s in fileExtension)
{
if (type == s)
{
flag = true;
break;
}
}
if (flag)
{
string name = "";
savePath = string.Format("{0}{1}.{2}",savePath,Guid.NewGuid().ToString(),type);
fileupload.SaveAs(savePath);
FileInfo ft = new FileInfo(savePath);
if (ft.Length > 0)
{
name = savePath.Substring(savePath.LastIndexOf("\\") + 1);
}
else
{
name = "0";
}
return name;
}
return null;
}
/// <summary>
/// 从Excel中读取数据并提交到数据库,次方法写在了 Common类下的ExcelHelper通用方法中 ;
/// </summary>
/// <param name="uploadFile">上传控件的名称</param>
/// <returns></returns>
public static DataTable GetDataSetFromExcel(FileUpload uploadFile)
{
try
{
string filename = ASPNETControlHelper.UploadFile(uploadFile, System.Web.HttpContext.Current.Server.MapPath("~/Template/"),"xls","xlsx");
OleDbConnection conn = new OleDbConnection(string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0",System.Web.HttpContext.Current.Server.MapPath("~/Template/")+filename));
try
{
conn.Open();
}
catch
{
conn = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0", System.Web.HttpContext.Current.Server.MapPath("~/Template/") + filename));
conn.Open();
}
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = "select * from [Sheet1$]";
OleDbDataAdapter oda = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
oda.Fill(ds);
DataTable dt = ds.Tables[0];
return dt;
}
catch
{
throw;
}
}
protected void btnImport_Click(object sender, EventArgs e)
{
DataTable dt = Common.ExcelHelper.GetDataSetFromExcel(uploadFile);//至此,将Excel中的数据源存到DataTable中,继而可以进行其他操作
} |