码迷,mamicode.com
首页 > 其他好文 > 详细

下载模板、Excel导入、导出

时间:2018-06-13 15:06:27      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:window   word   dcom   template   sage   rda   The   重复   car   

下载模板

 /// <summary>
    /// 下载模板
    /// </summary>
    /// <returns></returns>
    public ActionResult DownTemplate()
    {
        string path = Server.MapPath("/Template/TeacherTpl.xlsx");
        return File(new FileStream(path, FileMode.Open), "application/octet-stream", "教师模板.xlsx");
    }

使用时直接请求方法就行

window.location.href = ‘/Student/DownTemplate‘;

导入

引文件

<link href="~/Scripts/webuploader-0.1.5/webuploader.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/webuploader-0.1.5/webuploader.js"></script>

html

<div id="import">
    <input type="hidden" id="filePath" />
    <div id="uploader" class="wu-example">
        <!--用来存放文件信息-->
        <div id="thelist" class="uploader-list"></div>
        <div class="btns">
            <div id="picker">选择文件</div>
            <button type="button" id="ctlBtn" class="btn btn-default">开始上传</button>
        </div>
    </div>
</div>

初始化webuploader

function initUpload() {
        var $list = $("#thelist");
        var uploader = WebUploader.create({

            // swf文件路径
            swf: ‘~/Scripts/webuploader-0.1.5/Uploader.swf‘,
            // 文件接收服务端。
            server: ‘/Files/UploadFile?address=TemplateData‘,
            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建,可能是input元素,也可能是flash.
            pick: {
                id: ‘#picker‘,
                multiple: false
            },
            // 不压缩image, 默认如果是jpeg,文件上传前会压缩一把再上传!
            resize: false,
            fileNumLimit: 1,
            fileSingleSizeLimit: 1024 * 1024 * 10,
            accept: {
                extensions: ‘xlsx,xls‘
            }
        });
        // 当有文件被添加进队列的时候
        uploader.on(‘fileQueued‘, function (file) {
            $(‘#uploader .item‘).remove();
            $list.append(‘<div id="‘ + file.id + ‘" class="item">‘ +
                ‘<h4 class="info">‘ + file.name + ‘</h4><a class="upload-del" my-data-fid=‘ + file.id + ‘>x<a/><p class="state">等待上传...</p></div>‘);
        });
        // 文件上传过程中创建进度条实时显示。
        uploader.on(‘uploadProgress‘, function (file, percentage) {
            var $li = $(‘#‘ + file.id);
            //    $percent = $li.find(‘.progress .progress-bar‘);

            //// 避免重复创建
            //if (!$percent.length) {
            //    $percent = $(‘<div class="progress progress-striped active">‘ +
            //        ‘<div class="progress-bar" role="progressbar" style="width: 0%">‘ +
            //        ‘</div>‘ +
            //        ‘</div>‘).appendTo($li).find(‘.progress-bar‘);
            //}

            $li.find(‘p.state‘).text(‘上传中‘);

            // $percent.css(‘width‘, percentage * 100 + ‘%‘);
        });

        uploader.on(‘uploadSuccess‘, function (file, data) {
            if (data.error == 1) {
                $(‘#filePath‘).val(data.filePath);
                $(‘#‘ + file.id).find(‘p.state‘).text(‘已上传‘);
                uploader.removeFile(file.id);
            } else {
                $(‘#‘ + file.id).find(‘p.state‘).text(res.msg);
            }
        });

        uploader.on(‘uploadError‘, function (file) {
            $(‘#‘ + file.id).find(‘p.state‘).text(‘上传出错‘);
        });

        uploader.on(‘uploadComplete‘, function (file) {
            $(‘#‘ + file.id).find(‘.progress‘).fadeOut();
        });
        $(‘#thelist‘).on(‘click‘, ‘.upload-del‘, function () {
            var fid = $(this).attr(‘my-data-fid‘);
            uploader.removeFile(fid);
            $(this).parent(‘.item‘).remove();
        });
        uploader.on("error", function (type) {
            if (type == "F_EXCEED_SIZE") {
                layer.msg("文件大小不能超过10M");
            }
            else if (type == "Q_EXCEED_SIZE_LIMIT") {
                layer.msg("文件大小不能超过10M");
            } else if (type == ‘Q_EXCEED_NUM_LIMIT‘) {
                layer.msg("请先移除文件,再添加新文件");
            } else {
                layer.msg("上传出错!请检查后重新上传!错误代码" + type);
            }
        });

文件上传后台方法

 public ActionResult UploadFile()
        {
            if (Request.Files.Count <= 0)
            {
                return Content(JsonConvert.SerializeObject(new {error = "0", msg = "文件为空。"}));
            }
            string addr = Request["Address"];
            if (string.IsNullOrEmpty(addr))
            {
                return Content(JsonConvert.SerializeObject(new { error = "0", msg = "地址为空。" }));
            }
            string dirPath = Server.MapPath("/UploadFiles/" + addr);
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            var file = Request.Files[0];
            string ext = Path.GetExtension(file.FileName);
            string fileName = Guid.NewGuid().ToString() + ext;
            string filePath = Path.Combine(dirPath, fileName); // 绝对路径
            string returnPath = Path.Combine("/UploadFiles/" + addr, fileName); // 返回的路径
            try
            {
                file.SaveAs(filePath);
                return Content(JsonConvert.SerializeObject(new { error = "1", msg = "上传成功", filePath = returnPath }));
            }
            catch (Exception e)
            {
                return Content(JsonConvert.SerializeObject(new { error = "0", msg = "上传失败" }));
            }
        }

请求后台方法

var url = $(‘#filePath‘).val();
                    $.post(‘/Student/AddImportData‘, { path: url }, function (msg) {
                        if (msg=="success") {
                            $(‘#filePath‘).val(‘‘);
                            $("#thelist").remove();
                            $.messager.alert("提示", "导入成功",‘info‘);
                            ReloadClearData();
                            $("#import").dialog(‘close‘);
                            return;
                        }
                        $.messager.alert("提示", msg, ‘error‘);
                    })

后台方法

 /// <summary>
        /// 插入导入数据
        /// </summary>
        /// <returns></returns>
        public ActionResult AddImportData()
        {
            bool flag;
            string path;
            if (string.IsNullOrEmpty(Request["path"]))
            {
                return Content("参数错误");
            }

            path = Server.MapPath(Request["path"]);
            if (!System.IO.File.Exists(path))
            {
                return Content("路径不存在");
            }
            var list = Import(path, out flag);
            if (!flag)
            {
                return Content("导入失败");
            }return bo.AddBulk(list) ? Content("ok") : Content("导入失败");
        }

 

/// <summary>
    /// 导入
    /// </summary>
    /// <returns></returns>
    public List<Model.Teacher> Import(string path, out bool flag)
    {
        flag = true;
        List<Teacher> list = new List<Teacher>();
        //TODO 更改文件路径
        using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            IWorkbook wb = new XSSFWorkbook(fs); ;
            var extension = Path.GetExtension(path);
            ISheet sheet = wb.GetSheetAt(0);
            int index = 1;
            IRow row = sheet.GetRow(1);
            try
            {
                while (row != null)
                {
                    list.Add(new Teacher()
                    {
                        TeacherName = row.GetCell(0).ToString(),
                        Password = WebHelper.ToMD5("123456"),
                        Birthday = WebHelper.StrToDate(row.GetCell(1).ToString()),
                        IDCard = row.GetCell(2).ToString(),
                        Gender = row.GetCell(3).ToString() == "" ? 1 : 0,
                        MobilePhone = row.GetCell(4).ToString(),
                        QQNum = row.GetCell(5).ToString(),
                        WechatNum = row.GetCell(6).ToString(),
                        EmailNum = row.GetCell(7).ToString()
                    });
                    row = sheet.GetRow(++index);
                }
                return list;
            }
            catch (Exception)
            {
                flag = false;
                return null;
            }
        }
    }

 导出(待测)

  var workBook = new HSSFWorkbook();
  var table = workBook.CreateSheet("writeExcel");
  for (int i = 0; i < 20; i++)
  {
      var row = table.CreateRow(i);
      for (int j = 0; j < 20; j++)
      {
          var cell = row.CreateCell(j);
          cell.SetCellValue(j);
      }
  }
  using (var fs = File.OpenWrite(@"D:/writeExcels.xls"))
  {
      workBook.Write(fs);
      MessageBox.Show("Create succeed!");
  }

 

下载模板、Excel导入、导出

标签:window   word   dcom   template   sage   rda   The   重复   car   

原文地址:https://www.cnblogs.com/xiaonangua/p/9176965.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!