下载模板Excel导入导出
Posted xiaonangua
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了下载模板Excel导入导出相关的知识,希望对你有一定的参考价值。
下载模板
/// <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>
<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导入导出的主要内容,如果未能解决你的问题,请参考以下文章
autpoi 1.4.3版本发布—Excel傻瓜式API,快速实现Excel导入导出Word模板导出
autpoi 1.4.3版本发布—Excel傻瓜式API,快速实现Excel导入导出Word模板导出