经过各方面的资源查询和不懈的研究,困扰本人一个多星期的问题终于解决。
先上效果图
添加一些文本和图片
点击确认提交,将内容添加到word并下载
打开
提示、警告:
一开始找到使用 Aspose.Word 来实现,就是这个
别去用,我研究了三四天,不知道是个人问题还是,最后个人觉得两字:rubbish!
来吧,上代码:
我使用的是wangEditor 这个富文本编辑器,强烈推荐。
https://www.wangeditor.com/doc/
官方网站,进去之后。开始使用-基本使用。点击地址,另存为下载。
将 wangEditor.min.js 添加到content文件夹下
视图代码:
@using (Html.BeginForm("ExportWord", "WangEditor", FormMethod.Post))
{
欢迎使用 wangEditor 富文本编辑器
}
控制器代码:
自己添加好相应的引用
public class WangEditorController : Controller
{
public ActionResult Index()
{
return View();
}
///
/// 获取Html字符串中指定标签的指定属性的值
///
/// Html字符
/// 指定标签名
/// 指定属性名
///
private List GetHtmlAttr(string html, string tag, string attr)
{
Regex re = new Regex(@"(<" + tag + @"[wW].+?>)");
MatchCollection imgreg = re.Matches(html);
List m_Attributes = new List();
Regex attrReg = new Regex(@"([a-zA-Z1-9_-]+)s*=s*(x27|x22)([^x27x22]*)(x27|x22)", RegexOptions.IgnoreCase);
for (int i = 0; i < imgreg.Count; i++)
{
MatchCollection matchs = attrReg.Matches(imgreg[i].ToString());
for (int j = 0; j < matchs.Count; j++)
{
GroupCollection groups = matchs[j].Groups;
if (attr.ToUpper() == groups[1].Value.ToUpper())
{
m_Attributes.Add(groups[3].Value);
break;
}
}
}
return m_Attributes;
}
[ValidateInput(false)]
[HttpPost]
public FileResult ExportWord(string text1)
{
StringBuilder sb = new StringBuilder();
sb.Append("");
sb.Append("");
//将text1中的img转换为图片绝对地址 之前为 base64 存储。如果直接输出到word,会是一个大红叉。
//需要将base64 存储的格式解析,存储到本地,然后将text1中的图片格式替换为本地。
List result = GetHtmlAttr(text1, "img", "src");
int j = 1;
foreach (var item in result)
{
string temp = item;
int index = item.IndexOf("base64");
string value = item.Substring(index + 7);
string address = Injpg(string.Format("text{0}", j), value);
text1 = text1.Replace(temp, address);
j++;
}
//
sb.Append(text1);
sb.Append("");
var byteArray = System.Text.Encoding.Default.GetBytes(sb.ToString());
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
return File(byteArray, "application/ms-word", "wordtest" + ".doc");
}
public string Injpg(string name, string base64str)
{
string data = base64str;
byte[] arr = Convert.FromBase64String(data);
using (MemoryStream ms = new MemoryStream(arr))
{
Bitmap bmp = new Bitmap(ms);
string p = string.Format("/temp_img/{0}.jpg", name);//temp_img为自己在根目录下新建的一个文件夹
var w = Server.MapPath(p);
bmp.Save(w, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Close();
return w;
}
}
}
图片路径未替换前:
这种一长串的
替换后:
就是这么强大,烦恼!



