在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