C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > c#无插件打印导出

C# 前端无插件打印导出实现方式详解

作者:鱼是一只鱼啊

本文讲述了使用C#实现前端无插件的打印和导出功能,介绍了相关技术和方法,适合需要在项目中实现相应功能的开发者参考

打印

打印导出分布页

@model List<界面的数据模型类>
@using WingSoft;
@using Newtonsoft.Json;
<style type="text/css">
    .modal-content {
        width: 800px;
    }
    .modal-body {
        height: 400px;
    }
</style>
<script type="text/javascript">
    $(function () {
        if (@ViewBag.pe== 0) {//打印
            let content = ''
            for (var i = 0; i < $(".boxDiv").length; i++) {
                content += $(".boxDiv").eq(i).html() + '<div style="page-break-after: always;"></div>'
            }
            printFunc(content);
        } else {//导出(将所有数据导出到一个excel,多个工作表的形式)
            let contentArray = [];
            for (var i = 0; i < $(".boxDiv").length; i++) {
                contentArray.push({
                    html: $(".boxDiv").eq(i).html(),
                    name: "xx记录表" + (i + 1)
                });
            }
            exportToExcelBatch('xx记录表',contentArray)
        }
    });
</script>
<div class="modal fade" id="modal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                    <img src="~/Images/icon_closed.png" />
                </button>
            </div>
            <div class="modal-body">
                @for (var i = 0; i < Model.Count; i++)
                {
                        <div class="boxDiv">
                            <style>
                                .boxDiv table {
                                    width: 100%;
                                    display: flex;
                                    flex-direction: column;
                                    align-items: center;
                                }
                                .printTable {
                                    width: 100%;
                                    font-family: "宋体";
                                    border: 0px;
                                    color: #333;
                                    font-size: 12px;
                                }
                                    .printTable th {
                                        font-weight: 600;
                                        font-size: 14px;
                                    }
                                    .printTable td, .printTable th {
                                        text-align: center;
                                        padding: 3px 3px;
                                    }
                                .content td {
                                    border: 1px solid #4a4a4a;
                                }
                                .tabletitle1 {
                                    font-size: 20px;
                                    font-weight: bold;
                                }
                                .tabletitle2 {
                                    font-size: 18px;
                                    font-weight: bold;
                                    position: relative;
                                }
                                .contenleft {
                                    text-align: left !important;
                                }
                                .contenright {
                                    text-align: right !important;
                                }
                                .boxcontent {
                                    height: 30px;
                                    font-size: 14px;
                                }
                                .footertext {
                                    font-size: 14px;
                                }
                                .printTable td, .printTable th {
                                    border: 1px solid #E5E5E5;
                                    padding:3px;
                                    font-size:14px;
                                }
                                .printTable thead th{
                                    text-align:center;
                                }
                            </style>
                            <div class="modal-title" style="font-size:18px;text-align:center;">@Model[i].SchoolName 经营成本</div>
                            <div style="margin:10px 0">
                                <span>食堂名称:@Model[i].CanteenName</span>
                                <span style="margin-left:30%">登记时间:@Model[i].ForDate</span>
                            </div>
                            <table class="printTable" border=0 cellspacing=0 cellpadding=0 style="border-collapse:collapse;width:100%;">
                                <thead>
                                    <tr>
                                        <th>序号</th>
                                        <th>成本名称</th>
                                        <th>成本金额(元)</th>
                                        <th>备注</th>
                                    </tr>
                                </thead>
                                <tbody style="width:100%;">
                                    @{
                                        int index = 1;
                                    }
                                    @foreach (var item in Model[i].CostItemList)
                                    {
                                        <tr>
                                            <td>@(index++)</td>
                                            <td>@item.Name</td>
                                            <td>@item.TotalMoney</td>
                                            <td>@item.Remark</td>
                                        </tr>
                                    }
                                </tbody>
                            </table>
                        </div>
                }
            </div>
            <div class="modal-footer">
                <button type="button" class="btn2 btn_90_28" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

打印js

// 打印
function printFunc(data) {
    loadStart();
    var iframeHtml = document.createElement("iframe");
    iframeHtml.id = "iframePrintBox";
    iframeHtml.style.width = "0";
    iframeHtml.style.height = "0";
    document.body.appendChild(iframeHtml);
    iframeHtml.srcdoc = '<!DOCTYPE html>' + data + "<script type='text\/javascript'>window.onload = function(){window.print();window.onafterprint = ()=>{window.parent.close();}}<\/script>";
    loadEnd()
}

导出

//多sheet导出
function exportToExcelBatch(sheetName, exportArr) {
    var fileName_g, sheetsName_g, mainHtml_g, sheetHtml_g
    // 导出函数
    sheetsName_g = getSheetsName()  //获取到每个sheet的名称集合
    fileName_g = sheetName + '.xlsx'  //外部导出名称
    sheetHtml_g = getSheetXml()     //得到每一个sheet的xml片段
    mainHtml_g = getMainXml()       //导出的主体xml片段
    let XLSData = 'data:application/vnd.ms-excelbase64,' + window.btoa(window.unescape(encodeURIComponent(mainHtml_g)))
    // 下载
    download(XLSData)
    // 下载
    function download(base64data) {
        let blob
        if (window.navigator.msSaveBlob) {
            blob = base64ToBlob(base64data)
            window.navigator.msSaveBlob(blob, sheetName + '.xlsx')
            return false
        }
        let a = document.createElement("a")
        if (window.URL.createObjectURL) {
            blob = base64ToBlob(base64data)
            a.href = window.URL.createObjectURL(blob)
            a.download = fileName_g
            a.click()
            return
        }
        a.href = base64data
        a.download = fileName_g
        a.click()
    }
    // 获取sheet名称
    function getSheetsName() {
        let sheetsName = []
        exportArr.forEach((item) => {
            sheetsName.push(item.name)
        })
        return sheetsName
    }
// 创建文件流
function base64ToBlob(base64Data) {
    let arr = base64Data.split(',')
    let mime = arr[0].match(/:(.*?)/)[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8ClampedArray(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new Blob([u8arr], { type: mime })
}
    /**
 * 文件下载
 * @param {any} url 文件路径
 * @param {any} fileName 文件名称
 */
    function downloadFile(url, fileName) {
        if (!url || !fileName) return false;
        let aUrl = url;
        const x = new XMLHttpRequest();
        x.open('GET', aUrl, true);
        x.responseType = 'blob';
        x.onload = function (e) {
            const url = window.URL.createObjectURL(x.response);
            const elink = document.createElement('a');
            elink.href = url;
            elink.target = '_self'; // 当前页 target打开新页面
            elink.download = `${fileName}`;
            elink.style.display = 'none';
            document.body.appendChild(elink);
            elink.click();
            document.body.removeChild(elink);
        };
        x.send();
    }
    // 获取所有xml代码
    function getMainXml() {
        let mainHtml = ''
        let sheets = ''
        if (sheetsName_g.length > 0) {
            for (let i = 0; i < sheetsName_g.length; i++) {
                let name = sheetsName_g[i]
                let sheetItem = `
    <x:ExcelWorksheet>
     <x:Name>${name}</x:Name>
     <x:WorksheetSource HRef=3D"export/sheet${name}.xml"/>
    </x:ExcelWorksheet>`
                sheets += sheetItem
            }
        }
        mainHtml = `MIME-Version: 1.0
X-Document-Type: Workbook
Content-Type: multipart/related; boundary="----memo----"
------memo----
Content-Location: file:///C:/0E8D990C/export.xml
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html; charset="us-ascii"
<html xmlns:o=3D"urn:schemas-microsoft-com:office:office"
xmlns:x=3D"urn:schemas-microsoft-com:office:excel"
xmlns=3D"http://www.w3.org/TR/REC-html40">
<head>
<xml>
 <o:DocumentProperties>
  <o:Author>ijovo</o:Author>
  <o:LastAuthor>ijovo</o:LastAuthor>
  <o:Company>ijovo</o:Company>
  <o:Version>1.0</o:Version>
 </o:DocumentProperties>
</xml>
<!--[if gte mso 9]>
<xml>
 <x:ExcelWorkbook>
  <x:ExcelWorksheets>${sheets}
  </x:ExcelWorksheets>
 </x:ExcelWorkbook>
</xml>
<![endif]-->
</head>
</html>` + sheetHtml_g + `
------memo------`
        return mainHtml
    }
    // 获取每个sheet的xml代码}
    function getSheetXml() {
        let sheetHtml = ''
        let sheets = ''
        for (let i = 0; i < exportArr.length; i++) {
            let name = exportArr[i].name
            // MIME要求格式必须顶格……所以这里排版比较乱……
            let sheetItem = `
------memo----
Content-Location: file:///C:/0E8D990C/export/sheet${name}.xml
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html; charset="us-ascii"
<html 
  xmlns:o="urn:schemas-microsoft-com:office:office"
  xmlns:x="urn:schemas-microsoft-com:office:excel"
  xmlns="http://www.w3.org/TR/REC-html40">
  <head>
    <xml>
      <x:WorksheetOptions>
        <x:ProtectContents>False</x:ProtectContents>
        <x:ProtectObjects>False</x:ProtectObjects>
        <x:ProtectScenarios>False</x:ProtectScenarios>
      </x:WorksheetOptions>
    </xml>
    <style>
      <!-- @page
        {mso-footer-data:"&C\\7B2C &P \\9875\\FF0C\\5171 &N \\9875";
        margin:0.748in 0.195in 0.748in 0.195in;
        mso-header-margin:0.51in;
        mso-footer-margin:0.51in;}
      -->
    </style>
  </head>
  <body>`
            let table = `<table border=0 cellspacing=0 cellpadding=0 width="100%" bordercolor="#000000" style="border-collapse:collapse">${exportArr[i].html}</table>`
            sheetItem += table + `
  </body>
</html>`
            sheets += sheetItem
        }
        sheetHtml = sheets
        return sheetHtml
    }
}

单表格导出

// 导出表格
function exportToExcel(sheetName, html) {
    var uri = 'data:application/vnd.ms-excel;base64,';
    var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel"' +
        'xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>'
        + '<x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets>'
        + '</x:ExcelWorkbook></xml><![endif]-->' +
        ' <style type="text/css">' +
        'table td {' +
        'border: 0.5px solid #000000;' +
        'width: auto;' +
        'height: 25px;' +
        'text-align: center;' +
        'mso-number-format:\@;' +
        'vnd.ms-excel.numberformat:\@;' +
        /* 'background-color: #4f891e;' +*/
        /* 'color: #ffffff;' +*/
        ' }' +
        'table th {' +
        'border: 0.5px solid #000000;' +
        /* 'width: auto;' +*/
        'height: 35px;' +
        'text-align: center;' +
        'font-size:20px' +
        'mso-number-format:\@;' +
        'vnd.ms-excel.numberformat:\@;' +
        ' }' +
        '</style>' +
        '</head><body ><table>{table}</table></body></html>';
    //if (!tableid.nodeType) tableid = document.getElementById(tableid);
    //var ctx = { worksheet: sheetName || 'Worksheet', table: tableid.innerHTML };
    var ctx = { worksheet: sheetName || 'Worksheet', table: html };
    var a = document.createElement("a");
    a.download = sheetName + ".xls";
    a.href = uri + this.excelBase64(this.excelFormat(template, ctx));
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}
// Excel格式
function excelFormat(s, c) {
    return s.replace(/{(\w+)}/g,
        function (m, p) {
            return c[p];
        });
}
// 纯js导出Excel
function excelBase64(excelFile) {
    return window.btoa(unescape(encodeURIComponent(excelFile)));
}

到此这篇关于C# 前端无插件打印导出实现方式的文章就介绍到这了,更多相关c#无插件打印导出内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文