在CS文件中,首先在頂部引入操作Excel數據的命名空間
using System.Data.OleDb;
正式代碼如下:
private void Button_Click(object sender, System.EventArgs e)
{
string thefullname = this.uploadFile.PostedFile.FileName;//獲取完整路徑
ClientScriptManager csm = Page.ClientScript;
if (thefullname == "")
{
csm.RegisterStartupScript(GetType, "Error", "alert('請選擇要上傳得Excel文件');", true);
return;
}
int fileLength = this.uploadFile.PostedFile.ContentLength;
if (fileLength > 512000)
{
csm.RegisterStartupScript(GetType, "Error", "alert('文件已超過500K,無法上傳!');", true);
return;
}
FileInfo info = new FileInfo(thefullname);
string fileExt = info.Extension;
if (fileExt.ToLower() != ".xls")
{
csm.RegisterStartupScript(GetType, "Error", "alert('不是Excel文件,請使用正確的文件格式!');", true);
return;
}
string uploadPath = Page.MapPath(@"uploadfile/report.xls");
bool upSuccess = Upload(uploadPath);
if (!upSuccess)
{
csm.RegisterStartupScript(GetType, "Error", "alert('文件上傳失敗!');", true);
return;
}
DataTable table = GetExcelTable(uploadPath);
if (table == null)
{
csm.RegisterStartupScript(GetType, "Error", "alert('文件讀取失敗!');", true);
return;
}
}
private bool Upload(string uploadPath)
{
try
{
this.uploadFile.PostedFile.SaveAs(uploadPath);//上傳Excel並保存,在這裏判斷是否保存成功
return true;
}
catch
{
return false;
}
}
private DataTable GetExcelTable(string uploadPath)
{
DataSet ds;
string Xls_ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + uploadPath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1';";
OleDbConnection Conn = new OleDbConnection(Xls_ConnStr);
try
{
Conn.Open();
string sql_str = "select * from [Sheet1$]";
OleDbDataAdapter da = new OleDbDataAdapter(sql_str, Conn);
ds = new DataSet();
da.Fill(ds, "excel_data");
Conn.Close();
}
catch
{
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
return null;
}
finally
{
Conn.Dispose();
}
if (ds == null)
{
return null;
}
if (ds.Tables.Count < 1)
{
return null;
}
return ds.Tables[0];
}
說明:
"HDR=Yes;" :說明第一行包含的是列名,而不是數據。若爲"HDR=No;",則自動添加列F1,F2……
"IMEX=1;" :告訴驅動總是讀交叉數據列作爲文本。
Remark:
"HDR=Yes;": indicates that the first row contains ColumnNames,not data
"IMEX=1;": tells the driver to always read "intermixed" data columns as text