java上傳xls文件

using System;  

using System.Collections.Generic;  

using System.Web;  

using System.Web.UI;  

using System.Web.UI.WebControls;  

using PublicProject.ENTITY;  

using System.Data;  

using System.IO;  

using System.Data.OleDb;  

using PublicProject.BLL;  

public partial class 使用Excel讀取數據 : System.Web.UI.Page  

{  

//集合  

private List<School> schoolList = new List<School>();  

private DataSet dsall = new DataSet();  

private int count = 0;  

private SchoolBll schoolBll = new SchoolBll();  

protected void Page_Load(object sender, EventArgs e)  

{  

}  

//public void ReaderXls()  

//{  

//    string xlsFilePath = @"F:\項目代碼\公用架構\PublicProjectSolution\PublicProjectWeb\xls\DateReader.xls";  

//    Excel  

//}  

/// <summary>  

/// 單擊導入按鈕的事件  

/// </summary>  

/// <param name="sender"></param>  

/// <param name="e"></param>  

protected void BtnImport_Click1(object sender, EventArgs e)  

{  

string fileName = string.Empty;  

try 

{  

fileName= UpLoadXls(FileExcel);  

ImportXlsToData(fileName);//將XLS文件的數據導入數據庫  

if (fileName != string.Empty && System.IO.File.Exists(fileName))  

{  

System.IO.File.Delete(fileName);//刪除上傳的XLS文件  

}  

LblMessage.Text = "數據導入成功!";  

this.gvimport.DataSource = schoolList;  

this.gvimport.DataBind();  

this.lbimport.Text = schoolList.Count.ToString();  

int all = Convert.ToInt32(this.lballcount.Text.ToString());  

int import = Convert.ToInt32(this.lbimport.Text.ToString());  

int unimport = all - import;  

if (unimport > count)  

{  

this.lbunimport.Text = "," + unimport.ToString() + "條,因爲傳輸緣由未導入到數據庫!";  

}  

}  

catch (Exception ex)  

{  

LblMessage.Text=ex.Message;  

}  

}  

/// <summary>  

/// 上傳Excel文件  

/// </summary>  

/// <param name="inputfile">上傳的控件名</param>  

/// <returns></returns>  

private string UpLoadXls(System.Web.UI.HtmlControls.HtmlInputFile inputfile)  

{  

string orifilename = string.Empty;  

string uploadfilepath = string.Empty;  

string modifyfilename = string.Empty;  

string fileExtend = "";//文件擴展名  

int fileSize = 0;//文件大小  

try 

{  

if (inputfile.Value != string.Empty)  

{  

//獲得文件的大小  

fileSize = inputfile.PostedFile.ContentLength;  

if (fileSize == 0)  

{  

throw new Exception("導入的Excel文件大小爲0,請檢查是否正確!");  

}  

//獲得擴展名  

fileExtend = inputfile.Value.Substring(inputfile.Value.LastIndexOf(".") + 1);  

if (fileExtend.ToLower() != "xls")  

{  

throw new Exception("你選擇的文件格式不正確,只能導入EXCEL文件!");  

}  

//路徑  

uploadfilepath = Server.MapPath("~/xls/XlsUpLodes");  

//新文件名  

modifyfilename = System.Guid.NewGuid().ToString();  

modifyfilename += "." + inputfile.Value.Substring(inputfile.Value.LastIndexOf(".") + 1);  

//判斷是否有該目錄  

System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(uploadfilepath);  

if (!dir.Exists)  

{  

dir.Create();  

}  

orifilename = uploadfilepath + "\\" + modifyfilename;  

//若是存在,刪除文件  

if (File.Exists(orifilename))  

{  

File.Delete(orifilename);  

}  

// 上傳文件  

inputfile.PostedFile.SaveAs(orifilename);  

}  

else 

{  

throw new Exception("請選擇要導入的Excel文件!");  

}  

}  

catch (Exception ex)  

{  

throw ex;  

}  

return orifilename;  

}  

/// <summary>  

/// 將上傳文件中的數據讀取到數據庫中  

/// </summary>  

/// <param name="fileName">上傳的文件的地址</param>  

private void ImportXlsToData(string fileName)  

{  

try 

{  

if (fileName == string.Empty)  

{  

throw new ArgumentNullException("Excel文件上傳失敗!");  

}  

string oleDBConnString = String.Empty;  

oleDBConnString = "Provider=Microsoft.Jet.OLEDB.4.0;";  

oleDBConnString += "Data Source=";  

oleDBConnString += fileName;  

oleDBConnString += ";Extended Properties=Excel 8.0;";  

OleDbConnection oleDBConn = null;  

OleDbDataAdapter oleAdMaster = null;  

DataTable m_tableName = new DataTable();  

DataSet ds = new DataSet();  

oleDBConn = new OleDbConnection(oleDBConnString);  

oleDBConn.Open();  

m_tableName = oleDBConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);  

if (m_tableName != null && m_tableName.Rows.Count > 0)  

{  

m_tableName.TableName = m_tableName.Rows[0]["TABLE_NAME"].ToString();  

}  

string sqlMaster;  

sqlMaster = " SELECT *  FROM [" + m_tableName.TableName + "]";  

oleAdMaster = new OleDbDataAdapter(sqlMaster, oleDBConn);  

oleAdMaster.Fill(ds, "m_tableName");  

oleAdMaster.Dispose();  

oleDBConn.Close();  

oleDBConn.Dispose();  

AddDatasetToSQL(ds, 8);  

}  

catch (Exception ex)  

{  

throw ex;  

}  

}  

/// <summary>  

/// 將Dataset的數據導入數據庫  

/// </summary>  

/// <param name="pds">數據集</param>  

/// <param name="Cols">數據集列數</param>  

/// <returns></returns>  

private bool AddDatasetToSQL(DataSet pds, int Cols)  

{  

int ic, ir;  

ic = pds.Tables[0].Columns.Count;  

if (pds.Tables[0].Columns.Count < Cols)  

{  

throw new Exception("導入Excel格式錯誤!Excel只有" + ic.ToString() + "列");  

}  

ir = pds.Tables[0].Rows.Count;  

if (pds != null && pds.Tables[0].Rows.Count > 0)  

{  

for (int i = 0; i < pds.Tables[0].Rows.Count; i++)  

{  

School model = new School();  

string schooolid = pds.Tables[0].Rows[i][3].ToString();  

model.Email = pds.Tables[0].Rows[i][0].ToString();  

model.Pass= pds.Tables[0].Rows[i][1].ToString();  

model.RealName = pds.Tables[0].Rows[i][2].ToString();  

model.School1 = pds.Tables[0].Rows[i][3].ToString();  

model.ColSchool = pds.Tables[0].Rows[i][4].ToString();  

model.SubName = pds.Tables[0].Rows[i][5].ToString();  

model.GradeName = pds.Tables[0].Rows[i][6].ToString();  

model.ClassName = pds.Tables[0].Rows[i][7].ToString();  

//excel的格式:必須是英文列頭  

//EMAIL 密碼     姓名       學校    學院     專業     年級   班級  

//email  PASS  REAL_NAME SCHOOL  COL_NAME SUB_NAME GRADE  CLASS  

// 0   1      2        3       4       5        6      7  

schoolBll.Add(model);  

schoolList.Add(model);  

}  

//所有信息  

this.gvgetall.DataSource = schoolList;  

this.gvgetall.DataBind();  

dsall = pds;  

this.lballcount.Text = pds.Tables[0].Rows.Count.ToString();  

}  

else 

{  

throw new Exception("導入數據爲空!");  

}  

return true;  

}  

/// <summary>  

/// 插入數據到數據庫  

/// </summary>  

//public void Add(ccwu.Model.T_RESUME_INFO model)  

//{  

//    string sql = "select * from T_STUDENT_INFO where email='" + model.EMAIL.ToString() + "'";//根據一個號去查詢  

//    DataSet ds = ccwu.DBUtility.DbHelperSQL.Query(sql.ToString());  

//    //  int count = 0;  

//    if (ds.Tables[0].Rows.Count == 0)  

//    {  

//        //insert into PersonRecord  

//        ccwu.DAL.T_STUDENT_INFO dalstudent = new ccwu.DAL.T_STUDENT_INFO();  

//        ccwu.DAL.T_RESUME_INFO dalresume = new ccwu.DAL.T_RESUME_INFO();  

//        ccwu.Model.T_STUDENT_INFO m = new ccwu.Model.T_STUDENT_INFO();  

//        m.EMAIL = model.EMAIL.ToString();  

//        m.PASS = model.pass.ToString();  

//        m.SCHOOL_INFO_ID = Convert.ToInt32(model.SCHOOL_INFO_ID.ToString());  

//        //向學生註冊表裏  

//        int lastid = dalstudent.Add(m);  

//        model.STUDENT_INFO_ID = lastid;  

//        //向簡歷表裏添加信息  

//        dalresume.AddForAll(model);  

//        list.Add(model);  

//    }  

//    if (ds.Tables[0].Rows.Count > 0)  

//    {  

//        count = count + 1;  

//    }  

//}  

protected void gvgetall_PageIndexChanging(object sender, GridViewPageEventArgs e)  

{  

}  

protected void gvimport_PageIndexChanging(object sender, GridViewPageEventArgs e)  

{  

}  

} 
相關文章
相關標籤/搜索