word模板格式,将需要替换的位置用&xx&占位符填上,在后台找到跟数据相同的名称时替换
#region 带模板导出
public HttpResponseMessage ExportWordModel(dynamic obj)
{
long formId = obj.id;
string selectedModel = obj.selectedModel;
string tempFile = HttpContext.Current.Server.MapPath("~/ExcelModel/" + selectedModel).ToString();//获取模板路径
string filePath = "导出模板文件的文件名"
string filePathId = filePath + formId * 4564;//文件名加上一个唯一id组成的文件名, 防止表单名称重复,加上表单的唯一值id
string saveFilePath = HttpContext.Current.Server.MapPath("~/SaveExcel/" + filePathId).ToString(); // 保存表格的路径
try // 为空的时候会提示找不到文件夹
{
ClearDownloadDirectory(saveFilePath, ""); //清空saveFilePath文件夹下的所有内容 保证每次导出时zip文件都是最新的
}
catch { }
var result = “你的数据” // 我这里result为json格式的所有后面需要序列号循环出来,具体看自己的数据格式
if (result.Count() != 0)
{
int num = 0; // 导出的时候给word文档命名
string fullPath = saveFilePath; //上传路径
if (!Directory.Exists(fullPath))
{
Directory.CreateDirectory(fullPath); //如果路径不存在则创建
}
for (int i = 0; i < result.Count(); i++) // 把所有要导出的内容循环出来保存为docx
{
var formData = result[i].formData;
JArray tempData = (JArray)JsonConvert.DeserializeObject(formData); //序列化(也可使用JToken代替JObject)
try
{
Document doc = new Document(tempFile);
int selectedNum = 0;// 循环的次数,第一次不要逗号
var dic = new Dictionary<string, string>();
dic = CommonFun.JsonToDir(tempData); // 将查到的json转换成dictionary
DocumentBuilder builder = new DocumentBuilder(doc);
foreach (var key in dic.Keys)//关键点 当模板里面找到和数据相同的字段,将数据写到模板对应的位置
{
var repStr = string.Format("&{0}&", key);
doc.Range.Replace(repStr, dic[key], false, false); // 循环出json 中的label 字段和模板里面进行比较 如果相等则替换成对应的value值
}
string fileName = filePathId + num++;
doc.Save(saveFilePath + "/" + fileName + ".docx");//也可以保存为1.doc 兼容03-07
}
catch
{
}
}
}
else
{
var response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
return response;
}
var respose = DownloadZip(filePathId); //将某个文件夹的所有内容导出成zip格式
return respose;
}
}
#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
})
效果图: