c# winform 程式 讀取Excel
來源:互聯網
上載者:User
/**//// <summary>
/// 上傳Excel檔案到伺服器端
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnUpdateComment_Click(object sender, EventArgs e) {
//第一步,上傳EXCEL到伺服器端
if (FileUpload1.HasFile) {
//驗證EXCEL檔案格式
if (FileUpload1.FileName.ToLower().IndexOf(".xls") == -1) {
RequiredFieldValidator1.ErrorMessage = "不是有效Excel檔案";
RequiredFieldValidator1.IsValid = false;
return;
}
//EXCEL評論儲存位置
string _FilePath = string.Empty;
if (System.Configuration.ConfigurationManager.AppSettings["CommentExcelFile"] != null) {
_FilePath = System.Configuration.ConfigurationManager.AppSettings["CommentExcelFile"].ToString();
}
//如果此目錄不存在則建立此目錄
if (!System.IO.Directory.Exists(_FilePath)) {
System.IO.Directory.CreateDirectory(_FilePath);
}
//組建檔案名稱
string _FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "-" + DateTime.Now.Ticks.ToString().Substring(0, 4) + ".xls";
_FileName = _FilePath + @"\" + _FileName;
//儲存此檔案到伺服器指定位置
try {
FileUpload1.SaveAs(_FileName);
Response.Redirect(string.Format("CommentDetail.aspx?FileName={0}", _FileName));
} catch (Exception exp) {
throw exp;
}
}
}
讀取EXCEL#region 讀取EXCEL
/**//// <summary>
/// 讀取Excel文檔
/// </summary>
/// <param name="Path">檔案名稱</param>
/// <returns>返回一個資料集</returns>
/// http://dev.csdn.net/article/72/72658.shtm
public static DataSet ExcelToDS(string Path) {
if (!string.IsNullOrEmpty(Path)) {
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
DataSet ds = null;
strExcel = "select * from [sheet1$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
ds = new DataSet();
myCommand.Fill(ds);
return ds;
}
return null;
}
#endregion
try {
DataSet ds = CommUtil.ExcelToDS(_FileName);
if (ds != null
&& ds.Tables.Count > 0
&& ds.Tables[0].Rows.Count > 0) {
//略