標籤:
//匯出功能 protected void btnExport(object sender, EventArgs e) { //用來開啟下載視窗 string fileName = "中心連絡方式"; Response.ContentType = "application/vnd.ms-excel"; // Response.AddHeader("Content-Type", "application/vnd.ms-excel"); Response.HeaderEncoding = System.Text.Encoding.GetEncoding("utf-8"); Response.CacheControl = "no-cache"; // Response.AddHeader("Cache-Control","no-cache"); Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xls", System.Web.HttpUtility.UrlEncode(fileName))); Response.Clear(); //1將資料庫中的資料讀取到list中, //2設定workbook的值 //3寫入到memorystream中 //4以二進位的形式寫入到response流中 IList<ContactInfo> list = ContactBiz.Query(new ContactInfo()); ExcelToDB excelToDB = new ExcelToDB(); try { MemoryStream ms = excelToDB.ExportToExcel(fileName, list); Response.BinaryWrite(ms.ToArray()); //ms.GetBuffer(); Response.End(); } catch (Exception ex) { Logger.Write("中心連絡方式匯出失敗,原因:" + ex.Message); throw ex; } } //匯入功能 protected void Button1_Click(object sender, EventArgs e) { bool fileOK = false; string path = Server.MapPath("~/Temp/"); if (FileUpload1.HasFile) { string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower(); string[] allowedExtensions = { ".xls" }; for (int i = 0; i < allowedExtensions.Length; i++) { if (fileExtension == allowedExtensions[i]) { fileOK = true; } } } if (fileOK) { try { path = path + FileUpload1.FileName; FileUpload1.SaveAs(path); //提示檔案上傳成功 //LabMessage1.Text = "檔案上傳成功."; //LabMessage2.Text = "<b>原檔案路徑:</b>" + FileUpload1.PostedFile.FileName + "<br />" + // "<b>檔案大小:</b>" + FileUpload1.PostedFile.ContentLength + "位元組<br />" + // "<b>檔案類型:</b>" + FileUpload1.PostedFile.ContentType + "<br />"; ExcelToDB excelToDB = new ExcelToDB(); IList<ContactInfo> list = excelToDB.ExcelToList(path); IList<string> textList = new List<string>(); for (int i = 0; i < list.Count; i++) { ContactInfo conInfo = new ContactInfo { CenterName = list[i].CenterName }; IList<ContactInfo> list1 = ContactBiz.Query(conInfo); if (list1.Count == 0) { ContactBiz.Insert(list[i]); } else { textList.Add(list[i].CenterName);//add(list[i].CenterName); } } string text = ""; if (textList.Count > 0) { for (int i = 0; i < textList.Count; i++) { text += textList[i]; if (textList.Count > 1 && i < textList.Count - 1) { text += ","; } } Response.Write("<Script language=‘JavaScript‘>alert(‘匯入失敗的中心名稱:" + text + "‘);</Script>"); } else { Response.Write("<Script language=‘JavaScript‘>alert(‘資料全部匯入成功‘);</Script>"); } } catch (Exception ex) { Logger.Write("檔案上傳失敗,原因:" + ex.Message); Response.Write("<Script language=‘JavaScript‘>alert(‘檔案上傳失敗‘);</Script>"); } } else { Response.Write("<Script language=‘JavaScript‘>alert(‘只能夠上傳Excel檔案‘);</Script>"); } // string filePath = FileUpload1.PostedFile.FileName;//從fileupload控制項擷取檔案的全路徑 }
C#匯入、匯出功能