本文使用net6框架,aspose.word破解激活并兼容net6,导出word模板并兼容识别html并给其设置字体,前端直接浏览器下载,后端保存文件并返回文件流,还有批量导出并压缩zip功能
1、安装Aspose.Words的nuget包选择21.8.0 版本(此版本可用于net6)。本文破解这个版本免费无水印,可适用21.8.0以下至18.x以上。
2、代码:
using Aspose.Words;
using Aspose.Words.Saving;
/// <summary>
/// 导出word
/// </summary>
/// <returns></returns>
[HttpPost("export")]
public IActionResult ExportWrod(string userid){
//载入模板
Document doc = new Document();
// 创建DocumentBuilder对象,用于在文档中添加内容
DocumentBuilder builder = new DocumentBuilder(doc);// 创建一个新的段落
Paragraph para = builder.InsertParagraph();para.ParagraphFormat.Alignment = ParagraphAlignment.Center; //段落居中
para.ParagraphFormat.LineSpacingRule = LineSpacingRule.Exactly; //行距固定值
para.ParagraphFormat.LineSpacing = 22; //行距-固定值
para.ParagraphFormat.SpaceBefore = 12; //段前
para.ParagraphFormat.SpaceAfter = 12; //段后
// 在段落中添加文本
Run header = new Run(doc, "文本");
header.Font.Size = 22;
header.Font.Bold = true; //加粗
header.Font.Name = "创艺简标宋"; //字体
para.AppendChild(header);//处理含html文本的数据到word中
builder.Font.Size = 12;
builder.Font.Name = "创艺简楷体";
builder.InsertHtml("<p>含html的文本</p>", true); //(true可设置builder的格式)//目前激活码只找到Aspose.Word 21.8版本,找不到更高的版本了。
//激活之后可去除水印等等,添加下面代码即可
//原文https://www.cnblogs.com/cqpanda/p/16475319.htmlnew Aspose.Words.License().SetLicense(new MemoryStream(Convert.FromBase64String(asposeKey)));
const string saveFold = "../word/";
string outputPath = saveFold;
if (!Directory.Exists(outputPath))
{
Directory.CreateDirectory(outputPath);
}doc.Save(outputPath);
//如有需求转pdf则添加以下代码
String genWrod= "/自己的目录/刚才生成的word.docx";
Document doc1 = new Document(genWrod);
// 设置 PDF 转换选项
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions
{
SaveFormat = SaveFormat.Pdf,
EmbedFullFonts = true,
};
//保存为 PDF 文件
doc1.Save(saveFold + "/pdfs.pdf", pdfSaveOptions);#region 文件下载
//修改utf8编码,不然可能汉字会乱码
string encodedFileName = System.Web.HttpUtility.UrlEncode(fileName.Replace("/", ""), System.Text.Encoding.UTF8);
byte[] fileBytes = memoryStream.ToArray();
// 设置响应头,指定文件类型和文件名
var contentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = encodedFileName
};
Response.Headers.Add("Content-Disposition", contentDisposition.ToString());
// 设置Content-Type,这里是根据文件类型设置
var contentType = "application/octet-stream";
Response.Headers.Add("Content-Type", contentType);
#endregionreturn File(fileBytes, contentType); //返回文件流,可以直接在浏览器直接下载
}
//aspose.words的key激活码,破解这个版本免费无水印,可适用21.8.0以下至18.x以上。
private const string asposeKey = "DQo8TGljZW5zZT4NCjxEYXRhPg0KPExpY2Vuc2VkVG8+VGhlIFdvcmxkIEJhbms8L0xpY2Vuc2VkVG8+DQo8RW1haWxUbz5ra3VtYXIzQHdvcmxkYmFua2dyb3VwLm9yZzwvRW1haWxUbz4NCjxMaWNlbnNlVHlwZT5EZXZlbG9wZXIgU21hbGwgQnVzaW5lc3M8L0xpY2Vuc2VUeXBlPg0KPExpY2Vuc2VOb3RlPjEgRGV2ZWxvcGVyIEFuZCAxIERlcGxveW1lbnQgTG9jYXRpb248L0xpY2Vuc2VOb3RlPg0KPE9yZGVySUQ+MjEwMzE2MTg1OTU3PC9PcmRlcklEPg0KPFVzZXJJRD43NDQ5MTY8L1VzZXJJRD4NCjxPRU0+VGhpcyBpcyBub3QgYSByZWRpc3RyaWJ1dGFibGUgbGljZW5zZTwvT0VNPg0KPFByb2R1Y3RzPg0KPFByb2R1Y3Q+QXNwb3NlLlRvdGFsIGZvciAuTkVUPC9Qcm9kdWN0Pg0KPC9Qcm9kdWN0cz4NCjxFZGl0aW9uVHlwZT5Qcm9mZXNzaW9uYWw8L0VkaXRpb25UeXBlPg0KPFNlcmlhbE51bWJlcj4wM2ZiMTk5YS01YzhhLTQ4ZGItOTkyZS1kMDg0ZmYwNjZkMGM8L1NlcmlhbE51bWJlcj4NCjxTdWJzY3JpcHRpb25FeHBpcnk+MjAyMjA1MTY8L1N1YnNjcmlwdGlvbkV4cGlyeT4NCjxMaWNlbnNlVmVyc2lvbj4zLjA8L0xpY2Vuc2VWZXJzaW9uPg0KPExpY2Vuc2VJbnN0cnVjdGlvbnM+aHR0cHM6Ly9wdXJjaGFzZS5hc3Bvc2UuY29tL3BvbGljaWVzL3VzZS1saWNlbnNlPC9MaWNlbnNlSW5zdHJ1Y3Rpb25zPg0KPC9EYXRhPg0KPFNpZ25hdHVyZT5XbkJYNnJOdHpCclNMV3pBdFlqOEtkdDFLSUI5MlFrL2xEbFNmMlM1TFRIWGdkcS9QQ2NqWHVORmp0NEJuRmZwNFZLc3VsSjhWeFExakIwbmM0R1lWcWZLek14SFFkaXFuZU03NTJaMjlPbmdyVW40Yk0rc1l6WWVSTE9UOEpxbE9RN05rRFU0bUk2Z1VyQ3dxcjdnUVYxbDJJWkJxNXMzTEFHMFRjQ1ZncEE9PC9TaWduYXR1cmU+DQo8L0xpY2Vuc2U+DQo=";
前端代码:
//下载报告,直接在浏览器下载
function downloadMyReport() {
var cellData = {
"userid": userId
};
$.ajax({
url: prefix + "new/api/Export/export?userid=" + userId, // 替换为你的API地址
type: 'POST',
data: {
userid: userId // 用户ID
},
xhrFields: {
responseType: 'blob' //设置二进制
},
success: function (data, status, xhr) {
//获取header中的内容
var contentDispositionHeader = xhr.getResponseHeader('Content-Disposition');
var fileName = contentDispositionHeader ? contentDispositionHeader.split('filename=')[1] : 'default_filename.docx';
//需要对汉字编码否则会可能会路阿妈
var decodedFileName = decodeURIComponent(fileName);
// 创建Blob对象
var blob = new Blob([data], { type: 'application/octet-stream' });
// 创建临时URL并分配给一个链接
var url = window.URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = decodedFileName;
document.body.appendChild(a);
a.click();
}
});
}
3、如需要批量导出并压缩zip看下面代码思路
List<BatchExportWord> batchExportWordList = new List<BatchExportWord>();
//此处循环上第2步骤的思路即可foreach (var process in processList)
{
#region此处写第2部分绘画word的代码即可
Document doc = new Document();
// 创建DocumentBuilder对象,用于在文档中添加内容
DocumentBuilder builder = new DocumentBuilder(doc);......................
#endregion
//下面填充batchExportWordList集合存放批量word字节集合
using (MemoryStream stream = new MemoryStream())
{
doc.Save(stream, SaveFormat.Docx);
batchExportWordList.Add(new BatchExportWord()
{
Byte = stream.ToArray(),
Name = wordname
}); ;
}} //foreach结尾
#region 批量压缩word到zip中
// 使用GZipStream进行压缩并写入文件
Guid guid = Guid.NewGuid();
string file_name = DateTime.Now.ToString("yyyyMMddhhmmss") + guid + ".zip";
using (FileStream zipStream = new FileStream(outputPath + "/" + file_name, FileMode.Create))
using (ZipArchive zipArchive = new ZipArchive(zipStream, ZipArchiveMode.Create))
{
// 遍历字word节流集合并将每个字节流写入 ZIP 文件的一个条目
foreach (var item in batchExportWordList)
{
var entry = zipArchive.CreateEntry(item.Name.Replace("/", "") + ".docx"); // 注意此处名字里如果有"/"的话会自动根据杠压缩多层层文件夹
using (var entryStream = entry.Open())
{
entryStream.Write(item.Byte, 0, item.Byte.Length); //把字节写入生成
}
}
}
#endregion
以上代码从接口中摘抄出来,可能需要自己摘抄小部分修改。