aspose.cells 带模板导出excel

模板格式:

 aspose.cells 带模板导出excel_第1张图片

#region 带模板带出excel
        public HttpResponseMessage ExportExcelModel(dynamic obj)
        {
            int num = 0;
            long formId = obj.id;
            string selectedModel = obj.selectedModel;
            string tempFile = HttpContext.Current.Server.MapPath("~/ExcelModel/" + selectedModel).ToString();//获取模板路径
            var formData = "你的数据";
            if (formData.Count() != 0)
            {
                var dic = new Dictionary();
                Workbook workbook = new Workbook();
                workbook.Open(tempFile);
                Cells cells = workbook.Worksheets[0].Cells;
                DataTable dt = cells.ExportDataTableAsString(0, 0, cells.MaxDataRow + 1, cells.MaxDataColumn + 1, true);
                string filePathId = formData[0].formName + formId * 4564;// 防止表单名称重复,加上表单的唯一值id
                string saveFilePath = HttpContext.Current.Server.MapPath("~/SaveExcel/" + filePathId).ToString(); // 保存表格 
                try // 为空的时候会提示找不到文件夹
                {
                    ClearDownloadDirectory(saveFilePath, ""); // 保证每次导出时zip文件都是最新的
                }
                catch { }
                if (!Directory.Exists(saveFilePath))
                {
                    Directory.CreateDirectory(saveFilePath); //如果路径不存在则创建
                }
                for (int k = 0; k < formData.Count(); k++)// 循环多条数据
                {
                    JArray tempData = (JArray)JsonConvert.DeserializeObject(formData[k].formData);  //序列化(也可使用JToken代替JObject)
                    dic = CommonFun.JsonToDir(tempData);
                    for (int i = 0; i < cells.MaxDataRow + 1; i++)
                    {
                        for (int j = 0; j < cells.MaxDataColumn + 1; j++)
                        {
                            foreach (var key in dic.Keys)
                            {
                                if (cells[i, j].Value != null && cells[i, j].Value.ToString() == "&" + key + "&") // 找到exce模板里面和数据相同的字段 则替换
                                {
                                    cells[i, j].PutValue(dic[key]);
                                }
                            }
                        }
                    }
                    string fileName = filePathId + num++ + ".xlsx";//客户端保存的文件名
                    workbook.Save(saveFilePath + "/" + fileName); // 保存表格
                }
                var respose = DownloadZip(filePathId);

                return respose;
            }
            else
            {
                var response = new HttpResponseMessage();
                response.StatusCode = HttpStatusCode.OK;
                return response;
            }
           
        }

        #endregion

ClearDownloadDirectory方法,当fileName为空的时候文件夹的所有内容全部删除

 #region 删除指定文件夹下的内容
        private void ClearDownloadDirectory(string directory, string fileName)
        {
            var files = Directory.GetFiles(directory);
            if (fileName == "") // 全部删除
            {
                foreach (var file in files)
                {
                    try
                    {
                        File.Delete(file);
                    }
                    catch
                    {
                    }
                }
            }
            else
            {
                foreach (var file in files)
                {
                    if (file == fileName) // 中删除指定文件名
                    {
                        try
                        {
                            File.Delete(file);
                        }
                        catch
                        {
                        }
                    }
                }
            }

        }
        #endregion

DownZip:

#region 将整个文件夹打包成zip并下载
        public HttpResponseMessage DownloadZip(string filePath)
        {
            var response = new HttpResponseMessage();
            try
            {
                var zipFileName = string.Format("{0}.zip", filePath);
                var downloadDir = HttpContext.Current.Server.MapPath("~/SaveExcel/zip/" + filePath); // 组成的zip文件夹保存路径
                var archive = $"{downloadDir}/{zipFileName}";
                var temp = HttpContext.Current.Server.MapPath("~/SaveExcel/" + filePath); // 要组成zip文件的文件夹路径
                if (!Directory.Exists(downloadDir))
                {
                    Directory.CreateDirectory(downloadDir);
                }
                // 清空zip文件夹中的所有临时文件
                ClearDownloadDirectory(downloadDir, ""); // 保证每次导出时zip文件都是最新的
                Thread.Sleep(500);
                using (var zip = new ZipFile())
                {
                    // Make zip file
                    zip.AddDirectory(temp); // 组成zip文件
                    zip.Save(archive); // zip 文件保存
                }
                response.Content = new StreamContent(new FileStream(archive, FileMode.Open, FileAccess.Read));
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = zipFileName };
                response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            }
            catch (Exception ex)
            {
                response.StatusCode = HttpStatusCode.InternalServerError;
                response.Content = new StringContent(ex.ToString());
            }
            return response;
        }
        #endregion

 前端代码:

 this.$axios({
            method: 'POST',
            url: url, // 你对应后台的url
            responseType: 'blob',
            data: JSON.stringify({ id: this.selectedId, selectedModel: this.ruleForm.selectedModel })
          }).then((response) => {
            console.log(response)
            if (response.data.size === 22) {
              _this.errorTip('找不到模板文件')
            } else if (response.data.size === 0) {
              _this.errorTip('无数据')
            } else {
              var blob = new Blob([response.data])
              var downloadElement = document.createElement('a')
              var href = window.URL.createObjectURL(blob) // 创建下载的链接
              downloadElement.href = href
              downloadElement.download = '导出模板文件.zip' // 下载后文件名
              document.body.appendChild(downloadElement)
              downloadElement.click() // 点击下载
              document.body.removeChild(downloadElement) // 下载完成移除元素
              window.URL.revokeObjectURL(href) // 释放掉blob对象
            }
            _this.loading = false
          })

 效果图:

 aspose.cells 带模板导出excel_第2张图片

只是测试,数据里只有姓名年龄

你可能感兴趣的:(Asp.net)