淘先锋技术网

首页 1 2 3 4 5 6 7

NPOI Excel

服务端导出

// 1. WebApi
public virtual async Task<FileResult> DownLoad([FromQuery] XXXDto inputDto)
{
    byte[] content;
    string fileName;
    using(FileStream fs = new FileStream("xxx.xlsx", FileMode.Open, FileAccess.Read))
    {
        IWorkbook hssfworkbook = new XSSFWorkbook(fs);//打开 xlsx 若为xls则 new HSSFWorkbook(fs);
        ISheet sheet = hssfworkbook.GetSheetAt(0);
        IRow rowMainTitle = sheet.GetRow(0);
        IRow rowTitle = sheet.GetRow(1);
        //IRow rowCells = sheet.GetRow(2);
        //IRow rowCellsValue = sheet.GetRow(3);
        //IRow rowLast = sheet.GetRow(5);

        int startRowInx = 3;//开始写入行
        int tableIndex = 0;
        List<CellRangeAddress> cellRangeAddresses = new List<CellRangeAddress>();//需要合并单元格的集合
        foreach (var table in dataTables)
        {
            if (startRowInx != 3)
            {
                sheet.ShiftRows(startRowInx, sheet.LastRowNum, 1);//插入行
                sheet.CopyRow(1, startRowInx++);//赋值行样式
            }
            sheet.GetRow(startRowInx - 2).GetCell(0).SetCellValue(table[tableIndex].DisplayName + "应承担装卸费");
            foreach (var it in table)
            {
                row.GetCell(0).SetCellValue(it.XXXX);
                row.GetCell(1).SetCellValue(it.XXXX);
            }
            // 合并列
            cellRangeAddresses.Add(new CellRangeAddress(_currentStartRowInx, startRowInx - 2, 0, 0));
        }
        // 应用合并单元格
        cellRangeAddresses.ForEach(it =>
        {
            sheet.AddMergedRegion(it);
        });
        using (MemoryStream ms = new MemoryStream())
        {
            hssfworkbook.Write(ms);//保存
            content = ms.ToArray();
        }
    }
    return File(content, "application/octet-stream", "export.xlsx");
    //return FileContentStream(stream, "application/octet-stream"){FileDownName:"export.xlsx"};//Mvc
}

前端下载

// Js

// 1.ajax(Jquery.ajax 不支持返回arraybuffer)+ a标签下载
var formfield = form.val('form_wllaborrecord');//layui form 取参数
$.extend(formfield, { StatisticType: 'year' });
// 封装ajax请求
ajaxmod.requestAuthorize({
    url: '/wllaborrecord/Salary/Statistic/Export',
    type: 'Get',
    data: formfield,
    responseType:'arraybuffer',
    success: function (response) {
        var blob = new Blob([response], { type: 'application/vnd.ms-excel' });//MIME 类型
        var a = document.createElement('a');
        a.download = '123.xlsx';
        a.href = URL.createObjectURL(blob);
        a.click();
    }
}); 

// 2.<form>提交
var formfield = form.val('form_wllaborrecord');//layui form 取参数
$.extend(formfield, { StatisticType: 'year' });
var url = '/api/v1/wllaborrecord/Salary/Statistic/Export';
var inputs = '';
for (var key in formfield) {
    inputs += '<input type="hidden" name="' + key + '" value="' + formfield[key] + '" />';
}
$('<form action="' + url + '" method=get">' + inputs + '</form>').appendTo('body').submit().remove();