protected void Button1_Click(object sender, EventArgs e)
...{
string filepath=FileUpload1.PostedFile.FileName;
ReadExcel(filepath, gdBom);
}
public void ReadExcel(string sExcelFile,GridView dgBom)
...{
DataTable ExcelTable;
DataSet ds = new DataSet();
//Excel的連接
OleDbConnection objConn = newOleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +sExcelFile + ";" + "Extended Properties=Excel 8.0;");
objConn.Open();
DataTable schemaTable = objConn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
string tableName = schemaTable.Rows[0][2].ToString().Trim();//獲取 Excel 的表名,默認值是sheet1
string strSql = "select * from [" + tableName + "]";
OleDbCommand objCmd = new OleDbCommand(strSql, objConn);
OleDbDataAdapter myData = new OleDbDataAdapter(strSql, objConn);
myData.Fill(ds, tableName);//填充數(shù)據(jù)
dgBom.DataSource =ds;
dgBom.DataBind();
objConn.Close();
ExcelTable = ds.Tables[tableName];
int iColums = ExcelTable.Columns.Count;//列數(shù)
int iRows = ExcelTable.Rows.Count;//行數(shù)
//定義二維數(shù)組存儲 Excel 表中讀取的數(shù)據(jù)
string[,] storedata = new string[iRows, iColums];
for(int i=0;i<ExcelTable.Rows.Count;i++)
for (int j = 0; j < ExcelTable.Columns.Count; j++)
...{
//將Excel表中的數(shù)據(jù)存儲到數(shù)組
storedata[i, j] = ExcelTable.Rows[i][j].ToString();
}
int excelBom = 0;//記錄表中有用信息的行數(shù),有用信息是指除去表的標題和表的欄目,本例中表的用用信息是從第三行開始
//確定有用的行數(shù)
for (int k = 2; k < ExcelTable.Rows.Count; k++)
if (storedata[k, 1] != "")
excelBom++;
if (excelBom == 0)
...{
Response.Write("<script language=javascript>alert('您導入的表格不合格式!')</script>");
}
else
...{
//LoadDataToDataBase(storedata,excelBom)//該函數(shù)主要負責將 storedata 中有用的數(shù)據(jù)寫入到數(shù)據(jù)庫中,在此不是問題的關鍵省略
}
}
運行效果如下圖:選擇BOM表的路徑,點確定后