首页 > 代码库 > C#导入、导出功能
C#导入、导出功能
//导出功能 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#导入、导出功能
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。