asp.net core 如何将网页导出

 1.直接将Html转成Word。MVC自带FileResult很好用。Html中我们也可以嵌入自己的样式。

    html:

<div id="target">
    <style>
        table{border-collapse: collapse;border: 1px solid  black;}
        td{border: 1px royalblue solid}
    </style>
    <img src="../../Content/eman_sm.png" alt="" />
    <table>
        <tr>
            <td>姓名</td>
            <td>成绩</td>
        </tr>
        <tr>
            <td>张山</td>
            <td>80分</td>
        </tr>
        <tr>
            <td>李四</td>
            <td>90分</td>
        </tr>
    </table>
</div>
<div style="color: red"></div>
<a id="ea" href="#">导出word</a>
<a href="@Url.Action("ExportWords")">ExportWords</a>

 

<script>
    $("#ea").click(function () {
        var html = $("#target").html();
        window.open("/Home/ExportWord?html=" + html);
    })
</script>

get方法会受到url长度的影响,可以换成隐藏的form提交。

<form id="form1" action="/Home/ExportWord">
    <input type="hidden" value=""  name="html" id="cc" />
    <input type="submit" id="st" />
</form>
<div id="target">
    <style>
        table{border-collapse: collapse;border: 1px solid  black;}
        td{border: 1px royalblue solid}
    </style>
    <table>
        <tr>
            <td>姓名</td>
            <td>成绩</td>
        </tr>
        <tr>
            <td>张山</td>
            <td>80分</td>
        </tr>
        <tr>
            <td>李四</td>
            <td>90分</td>
        </tr>
    </table>
</div>
<div style="color: red"></div>
<a id="ea" href="#">导出word</a>
<a href="@Url.Action("ExportWords")">ExportWords</a>
<script>
    $("#ea").click(function () {
        var html = $("#target").html();
        $("#cc").val(html);
        $("#st").click();
    })
</script>

 

 

 action端

 1 [ValidateInput(false)]
 2         public FileResult ExportWord(string html)
 3         {
 4             StringBuilder sb = new StringBuilder();
 5             sb.Append("<!DOCTYPE html>");
 6             sb.Append("<body>");
 7             sb.Append(html);
 8             sb.Append("</body>");
 9             var byteArray = System.Text.Encoding.Default.GetBytes(sb.ToString());
10             Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
11             return File(byteArray, "application/ms-word", "wordtest" + ".doc");
12         }

 

posted on 2021-10-01 15:52  码农at突泉  阅读(114)  评论(0编辑  收藏  举报