zoukankan      html  css  js  c++  java
  • 导入导出

    后台导出

    控制器:

     1 public void Exportexcel()
     2 {
     3 List<Questionnaire> paperList = nairebll.SearchQuestionnaire();
     4 nairebll.ExportResult(paperList, "../CourseFile/新建Excel.xls");
     5 }
     6 
     7 DAL:
     8 public void ExportResult(List<Questionnaire> paperList, string excelName)
     9 {
    10 HttpContext.Current.Response.Clear();
    11 //HttpContext.Current.Response.Charset = "UTF-8";
    12 Response.ContentEncoding = System.Text.Encoding.UTF8;
    13 HttpContext.Current.Response.ContentType = "application/vnd.ms-xls";
    14 StringWriter stringWrite = new StringWriter(); //导出的数据只能是字符串
    15 HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
    16 
    17 DataGrid dg = new DataGrid();
    18 dg.DataSource = paperList;
    19 dg.DataBind();
    20 dg.RenderControl(htmlWrite);
    21 HttpContext.Current.Response.AddHeader
    22 ("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(excelName));
    23 HttpContext.Current.Response.Write(stringWrite.ToString());
    24 HttpContext.Current.Response.End();
    25 }
    26 BLL: public void ExportResult(List<Questionnaire> paperList, string excelName)
    27 {
    28 nairedal.ExportResult(paperList,excelName);
    29 }

    导出到word

     1 Random rd = new Random();
     2 string fileName = DateTime.Now.ToString("yyyyMMddhhmm") + rd.Next() + ".doc";
     3 if (useid == 2)
     4 {
     5 fileName = "学习试卷" + fileName;
     6 }
     7 if (useid == 3)
     8 {
     9 fileName = "考试试卷" + fileName;
    10 }
    11 //存储路径
    12 string path = Server.MapPath("../uploads/Questions/" + fileName);
    13 //创建字符输出流
    14 StreamWriter sw = new StreamWriter(path, true, System.Text.UnicodeEncoding.UTF8);
    15 sw.Write(html);//保存数据 HTML是数据
    16 sw.Close();
    17 Response.Clear();
    18 Response.Buffer = true;
    19 this.EnableViewState = false;
    20 string strFileName = HttpUtility.UrlEncode(Path.GetFileName(path));
    21 //Response.Charset = "utf-8";
    22 Response.ContentType = "application/octet-stream";
    23 Response.AppendHeader("Content-Disposition", "attachment;filename=" + strFileName);
    24 Response.Flush();//向客户端发送当前所有缓冲的输出;
    25 Response.WriteFile(path, false);
    26 Response.End();

    导入

    网址:http://www.cnblogs.com/bianlan/archive/2012/05/14/2500705.html

    控制器:

      1 public ActionResult ImportSelectQuestion(int tid, string tname)
      2 {
      3 try
      4 {
      5 HttpPostedFileBase file = Request.Files["files"];
      6 string FileName;
      7 string savePath;
      8 string FileType;
      9 string fileEx;
     10 if (file == null || file.ContentLength <= 0)
     11 {
     12 ViewBag.error = "文件不能为空";
     13 return Content("<script>alert('文件不能为空!');history.go(-1);</script>");
     14 }
     15 else
     16 {
     17 string filename = Path.GetFileName(file.FileName);
     18 int filesize = file.ContentLength;//获取上传文件的大小单位为字节byte
     19 fileEx = System.IO.Path.GetExtension(filename);//获取上传文件的扩展名
     20 string NoFileName = System.IO.Path.GetFileNameWithoutExtension(filename);//获取无扩展名的文件名
     21 int Maxsize = 4000 * 1024;//定义上传文件的最大空间大小为4M
     22 FileType = ".xls,.xlsx";//定义上传文件的类型字符串
     23 
     24 FileName = NoFileName + DateTime.Now.ToString("yyyyMMddhhmmss") + fileEx;
     25 if (!FileType.Contains(fileEx))
     26 {
     27 ViewBag.error = "文件类型不对,只能导入xls和xlsx格式的文件";
     28 return Content("<script>alert('文件类型不对,只能导入xls和xlsx格式的文件!');history.go(-1);</script>");
     29 }
     30 if (filesize >= Maxsize)
     31 {
     32 ViewBag.error = "上传文件超过4M,不能上传";
     33 return Content("<script>alert('上传文件超过4M,不能上传!');history.go(-1);</script>");
     34 }
     35 string path = AppDomain.CurrentDomain.BaseDirectory + "CourseFile";
     36 savePath = Path.Combine(path, FileName);
     37 file.SaveAs(savePath);
     38 }
     39 string strConn = "";
     40 if (fileEx.Equals(".xlsx"))
     41 {
     42 strConn = "Provider=Microsoft.Ace.OleDb.12.0;Data Source=" + savePath + ";Extended Properties='Excel 12.0 Xml; HDR=YES; IMEX=1'";
     43 }
     44 else if (fileEx.Equals(".xls"))
     45 {
     46 strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + savePath + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
     47 }
     48 OleDbConnection conn = new OleDbConnection(strConn);
     49 conn.Open();
     50 OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$]", strConn);
     51 DataSet myDataSet = new DataSet();
     52 try
     53 {
     54 myCommand.Fill(myDataSet, "ExcelInfo");
     55 }
     56 catch (Exception ex)
     57 {
     58 ViewBag.error = ex.Message;
     59 return Content("<script>alert('导入失败!');history.go(-1);</script>");
     60 }
     61 DataTable table = myDataSet.Tables["ExcelInfo"].DefaultView.ToTable();
     62 var result = selectbll.ImportSelectQuestion(table, tid, tname); 
     63 else
     64 {
     65 ViewBag.error = "导入成功";
     66 System.Threading.Thread.Sleep(2000);
     67 return Content("<script>alert('导入成功!');history.go(-2);</script>");
     68 }
     69 
     70 }
     71 catch (Exception)
     72 {
     73 
     74 ViewBag.error = "导入失败";
     75 return Content("<script>alert('导入失败!');history.go(-1);</script>");
     76 }
     77 }
     78 
     79  
     80 
     81 
     82 DAL:
     83 public int ImportSelectQuestion(DataTable table, int tid, string tname)
     84 {
     85 var userID = int.Parse(HttpContext.Current.Request.Cookies["UserID"].Value);
     86 if (table.Columns.Count != 8)
     87 {
     88 return 1;
     89 }
     90 else
     91 {
     92 using (TransactionScope transaction = new TransactionScope())
     93 {
     94 for (int i = 0; i < table.Rows.Count; i++)
     95 {
     96 
     97 Exam_SelectQuestion quesinfo = new Exam_SelectQuestion();
     98 quesinfo.question_info = table.Rows[i][0].ToString().Trim();
     99 quesinfo.option_A = table.Rows[i][1].ToString().Trim();
    100 quesinfo.option_B = table.Rows[i][2].ToString().Trim();
    101 quesinfo.option_C = table.Rows[i][3].ToString().Trim();
    102 quesinfo.option_D = table.Rows[i][4].ToString().Trim();
    103 quesinfo.option_E = table.Rows[i][5].ToString().Trim();
    104 quesinfo.option_F = table.Rows[i][6].ToString().Trim();
    105 quesinfo.option_G = "";
    106 quesinfo.option_H = "";
    107 quesinfo.option_I = "";
    108 quesinfo.option_J = "";
    109 quesinfo.option_count = 6;
    110 quesinfo.question_type = "单选";
    111 quesinfo.answer_info = table.Rows[i][7].ToString().Trim();
    112 //用三元运算符来设置分值
    113 //quesinfo.score = Convert.ToDecimal(table.Rows[i][8] != DBNull.Value ? table.Rows[i][8] : 0);
    114 quesinfo.question_answer = "";
    115 quesinfo.difficulty_level = "";
    116 quesinfo.score = 0;
    117 quesinfo.state = 1;
    118 quesinfo.type_id = tid;
    119 quesinfo.type_name = tname;
    120 quesinfo.create_id = userID;
    121 if (table.Rows[i][0].ToString().Trim() == "")
    122 {
    123 return 2;
    124 } 
    125 else
    126 {
    127 ZKQIEntities db = new ZKQIEntities();
    128 db.Exam_SelectQuestion.AddObject(quesinfo);
    129 db.SaveChanges();
    130 }
    131 }
    132 transaction.Complete();
    133 }
    134 return 6;
    135 
    136 }
    View Code

    文件下载

    1 public FileResult GetFile()
    2 {
    3 string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/excel/";
    4 string fileName = "基站信息Excel模版.xls";
    5 return File(path + fileName, "text/plain", fileName);
    6 }
  • 相关阅读:
    [ Scala ]关于scala环境搭建过程中,sbt编译中maven下载失败的解决方案(改成阿里的maven仓库)
    复习笔记:一个简单的动态代理实现
    复习笔记:一个简单的反射工厂Demo
    定时器Timer如何终止运行的问题
    Python RESTful接口开发02
    python 内置模块 logging的使用
    Django项目数据处理的流程是怎样的
    Django-Redis:在Django中使用redis作为缓存
    Python RESTful 接口开发01
    teamview
  • 原文地址:https://www.cnblogs.com/sdya233/p/13219602.html
Copyright © 2011-2022 走看看