Js读取接口返回的文件流+WebApi

发布时间 2023-06-01 14:57:30作者: 何必花心

做个记录

前端

// 获取时间戳
let timestamp = new Date().getTime();
// 获取XMLHttpRequest
let xmlResquest = new XMLHttpRequest();

var IsOnB = $("#IsOnB option:selected").val();
var url = EvaluateUrl + "Theme/ExportThemeProcessStatisticsList?FlowId=" + FlowId;
if (IsOnB) {
url += "&IsOnB=" + IsOnB;
}
// 发起请求
xmlResquest.open("GET", url, true);
// 设置请求头类型
xmlResquest.setRequestHeader("Content-type", "application/json");
xmlResquest.responseType = "blob";

xmlResquest.onloadstart = function (oEvent) {
this.layerIndex = layui.layer.load(1, {
shade: [0.1, '#d6d6d6']
});
}
// 返回
xmlResquest.onload = function (oEvent) {

let content = xmlResquest.response;
// 组装a标签
let elink = document.createElement("a");
// 设置下载文件名
elink.download = timestamp + ".xls";
elink.style.display = "none";
let blob = new Blob([content]);
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
document.body.removeChild(elink);

layui.layer.close(this.layerIndex);
};

xmlResquest.upload.onprogress = function (e) {

if (e.lengthComputable) { //lengthComputable 是 progress 的一个属性,表示资源是否可计算字节流
let pross = (e.loaded / e.total) * 100;

}
}
xmlResquest.send();

 

后端

[HttpGet("ExportThemeProcessStatisticsList")]
public ActionResult<object> ExportThemeProcessStatisticsList(int FlowId, string ThemeName, Guid? UnitId, string UnitName, int? IsOnB)
{


var list = _themeService.ExportThemeProcessStatisticsList(FlowId, ThemeName, UnitId, UnitName, IsOnB);

List<ColumnEntity> olumnEntity = new List<ColumnEntity>();
olumnEntity.Add(new ColumnEntity { Column = "unitName", ExcelColumn = "学校名称", Width = 50 });
olumnEntity.Add(new ColumnEntity { Column = "userName", ExcelColumn = "教师姓名", Width = 20 });
olumnEntity.Add(new ColumnEntity { Column = "sex", ExcelColumn = "性别", Width = 10 });
olumnEntity.Add(new ColumnEntity { Column = "idCard", ExcelColumn = "身份证号", Width = 20 });
olumnEntity.Add(new ColumnEntity { Column = "isOnB", ExcelColumn = "是否在编", Width = 10 });
olumnEntity.Add(new ColumnEntity { Column = "educUnitName", ExcelColumn = "毕业学校名称", Width = 50 });
olumnEntity.Add(new ColumnEntity { Column = "eduction", ExcelColumn = "最高学位层次", Width = 10 });
olumnEntity.Add(new ColumnEntity { Column = "certNo", ExcelColumn = "证书编码", Width = 10 });
olumnEntity.Add(new ColumnEntity { Column = "certType", ExcelColumn = "证书类型", Width = 10 });
olumnEntity.Add(new ColumnEntity { Column = "isOnG", ExcelColumn = "是否在岗", Width = 10 });
olumnEntity.Add(new ColumnEntity { Column = "postName", ExcelColumn = "所在岗位", Width = 10 });
olumnEntity.Add(new ColumnEntity { Column = "postMonthNum", ExcelColumn = "在岗月份数", Width = 10 });
olumnEntity.Add(new ColumnEntity { Column = "outMonthNum", ExcelColumn = "退休月份数", Width = 20 });
olumnEntity.Add(new ColumnEntity { Column = "postRemark", ExcelColumn = "情况说明", Width = 20 });
olumnEntity.Add(new ColumnEntity { Column = "contractDate", ExcelColumn = "合同起止时间", Width = 20 });
string date = DateTime.Now.ToString("yyyyMMddhhmmss");
var dt = ExcelHelper.ToDataTable(list);
var stream = ExportHelper.ExportMemoryStream(dt, new ExcelConfig
{
Title = "信息采集导出列表",
FileName = $"{date}.xls",
ColumnEntity = olumnEntity
}); ;
return new FileStreamResult(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

}

 

ColumnEntity类

public class ColumnEntity
{
/// <summary>
/// 列名
/// </summary>
public string Column { get; set; }
/// <summary>
/// Excel列名
/// </summary>
public string ExcelColumn { get; set; }
/// <summary>
/// 宽度
/// </summary>
public int Width { get; set; }
/// <summary>
/// 前景色
/// </summary>
public Color ForeColor { get; set; }
/// <summary>
/// 背景色
/// </summary>
public Color Background { get; set; }
/// <summary>
/// 字体
/// </summary>
public string Font { get; set; }
/// <summary>
/// 字号
/// </summary>
public short Point { get; set; }
/// <summary>
/// 对齐方式
///left 左
///center 中间
///right 右
///fill 填充
///justify 两端对齐
///centerselection 跨行居中
///distributed
/// </summary>
public string Alignment { get; set; }

/// <summary>
/// 格式化
/// </summary>
public string Format { get; set; }
}

TemplateMode类

public class TemplateMode
{

/// <summary>
/// 行号
/// </summary>
public int row { get; set; }
/// <summary>
/// 列号
/// </summary>
public int cell { get; set; }
/// <summary>
/// 数据值
/// </summary>
public string value { get; set; }
}

ExcelConfig类

public class ExcelConfig
{

/// <summary>
/// 文件名
/// </summary>
public string FileName { get; set; }
/// <summary>
/// 标题
/// </summary>
public string Title { get; set; }
/// <summary>
/// 前景色
/// </summary>
public Color ForeColor { get; set; }
/// <summary>
/// 背景色
/// </summary>
public Color Background { get; set; }
private short _titlepoint;
/// <summary>
/// 标题字号
/// </summary>
public short TitlePoint
{
get
{
if (_titlepoint == 0)
{
return 20;
}
else
{
return _titlepoint;
}
}
set { _titlepoint = value; }
}
private short _headpoint;
/// <summary>
/// 列头字号
/// </summary>
public short HeadPoint
{
get
{
if (_headpoint == 0)
{
return 10;
}
else
{
return _headpoint;
}
}
set { _headpoint = value; }
}
/// <summary>
/// 标题高度
/// </summary>
public short TitleHeight { get; set; }
/// <summary>
/// 列标题高度
/// </summary>
public short HeadHeight { get; set; }
private string _titlefont;
/// <summary>
/// 标题字体
/// </summary>
public string TitleFont
{
get
{
if (_titlefont == null)
{
return "微软雅黑";
}
else
{
return _titlefont;
}
}
set { _titlefont = value; }
}
private string _headfont;
/// <summary>
/// 列头字体
/// </summary>
public string HeadFont
{
get
{
if (_headfont == null)
{
return "微软雅黑";
}
else
{
return _headfont;
}
}
set { _headfont = value; }
}
/// <summary>
/// 是否按内容长度来适应表格宽度
/// </summary>
public bool IsAllSizeColumn { get; set; }
/// <summary>
/// 列设置
/// </summary>
public List<ColumnEntity> ColumnEntity { get; set; }
}

ExportHelper类

public class ExportHelper
{


#region DataTable导出到Excel文件excelConfig中FileName设置为全路径

/// <summary>
/// DataTable导出到Excel文件 Export()
/// </summary>
/// <param name="dtSource">DataTable数据源</param>
/// <param name="excelConfig">导出设置包含文件名、标题、列设置</param>
public static void ExcelExport(DataTable dtSource, ExcelConfig excelConfig)
{
using (MemoryStream ms = ExportMemoryStream(dtSource, excelConfig))
{
using (FileStream fs = new FileStream(excelConfig.FileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
}
}
}

#endregion DataTable导出到Excel文件excelConfig中FileName设置为全路径

#region DataTable导出到Excel的MemoryStream

/// <summary>
/// DataTable导出到Excel的MemoryStream Export()
/// </summary>
/// <param name="dtSource">DataTable数据源</param>
/// <param name="excelConfig">导出设置包含文件名、标题、列设置</param>
public static MemoryStream ExportMemoryStream(DataTable dtSource, ExcelConfig excelConfig)
{
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

int colint = 0;
for (int i = 0; i < dtSource.Columns.Count;)
{
DataColumn column = dtSource.Columns[i];
if (excelConfig.ColumnEntity.Any(t => string.Compare(t.Column, column.ColumnName, true) == 0))
{
i++;
colint++;
}
else
{
dtSource.Columns.Remove(column.ColumnName);
}
}

HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Sheet1");

#region 右击文件 属性信息

{
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI";
workbook.DocumentSummaryInformation = dsi;

SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Author = ""; //填加xls文件作者信息
si.ApplicationName = ""; //填加xls文件创建程序信息
si.LastAuthor = ""; //填加xls文件最后保存者信息
si.Comments = ""; //填加xls文件作者信息
si.Title = "标题信息"; //填加xls文件标题信息
si.Subject = "主题信息";//填加文件主题信息
si.CreateDateTime = System.DateTime.Now;
workbook.SummaryInformation = si;
}

#endregion 右击文件 属性信息

#region 设置标题样式

ICellStyle headStyle = workbook.CreateCellStyle();
int[] arrColWidth = new int[dtSource.Columns.Count];
string[] arrColName = new string[dtSource.Columns.Count];//列名
ICellStyle[] arryColumStyle = new ICellStyle[dtSource.Columns.Count];//样式表
headStyle.Alignment = HorizontalAlignment.Center; // ------------------
if (excelConfig.Background != new Color())
{
if (excelConfig.Background != new Color())
{
headStyle.FillPattern = FillPattern.SolidForeground;
headStyle.FillForegroundColor = GetXLColour(workbook, excelConfig.Background);
}
}
IFont font = workbook.CreateFont();
font.FontHeightInPoints = excelConfig.TitlePoint;
if (excelConfig.ForeColor != new Color())
{
font.Color = GetXLColour(workbook, excelConfig.ForeColor);
}
font.Boldweight = 700;
headStyle.SetFont(font);

#endregion 设置标题样式

#region 列头及样式

ICellStyle cHeadStyle = workbook.CreateCellStyle();
cHeadStyle.Alignment = HorizontalAlignment.Center; // ------------------
IFont cfont = workbook.CreateFont();
cfont.FontHeightInPoints = excelConfig.HeadPoint;
cHeadStyle.SetFont(cfont);

#endregion 列头及样式

#region 设置内容单元格样式

IDataFormat dataformat = workbook.CreateDataFormat();

foreach (DataColumn item in dtSource.Columns)
{
ICellStyle columnStyle = workbook.CreateCellStyle();
columnStyle.Alignment = HorizontalAlignment.Center;
arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;
arrColName[item.Ordinal] = item.ColumnName.ToString();
if (excelConfig.ColumnEntity != null)
{
ColumnEntity columnentity = excelConfig.ColumnEntity.Find(t => string.Compare(t.Column, item.ColumnName, true) == 0);
if (columnentity != null)
{
if (item.DataType == typeof(decimal) || item.DataType == typeof(double) || item.DataType == typeof(int))
{
columnStyle.DataFormat = dataformat.GetFormat("#,##0.00;[Red](#,##0.00)");
}

if (!string.IsNullOrWhiteSpace(columnentity.Format))
{
columnStyle.DataFormat = dataformat.GetFormat(columnentity.Format);
}

arrColName[item.Ordinal] = columnentity.ExcelColumn;
if (columnentity.Width != 0)
{
arrColWidth[item.Ordinal] = columnentity.Width;
}
if (columnentity.Background != new Color())
{
if (columnentity.Background != new Color())
{
columnStyle.FillPattern = FillPattern.SolidForeground;
columnStyle.FillForegroundColor = GetXLColour(workbook, columnentity.Background);
}
}
if (columnentity.Font != null || columnentity.Point != 0 || columnentity.ForeColor != new Color())
{
IFont columnFont = workbook.CreateFont();
columnFont.FontHeightInPoints = 10;
if (columnentity.Font != null)
{
columnFont.FontName = columnentity.Font;
}
if (columnentity.Point != 0)
{
columnFont.FontHeightInPoints = columnentity.Point;
}
if (columnentity.ForeColor != new Color())
{
columnFont.Color = GetXLColour(workbook, columnentity.ForeColor);
}
columnStyle.SetFont(font);
}
columnStyle.Alignment = GetAlignment(columnentity.Alignment);
}
}
arryColumStyle[item.Ordinal] = columnStyle;
}
if (excelConfig.IsAllSizeColumn)
{
#region 根据列中最长列的长度取得列宽

for (int i = 0; i < dtSource.Rows.Count; i++)
{
for (int j = 0; j < dtSource.Columns.Count; j++)
{
if (arrColWidth[j] != 0)
{
int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
if (intTemp > arrColWidth[j])
{
arrColWidth[j] = intTemp;
}
}
}
}

#endregion 根据列中最长列的长度取得列宽
}

#endregion 设置内容单元格样式

ICellStyle dateStyle = workbook.CreateCellStyle();
IDataFormat format = workbook.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
int rowIndex = 0;
foreach (DataRow row in dtSource.Rows)
{
#region 新建表,填充表头,填充列头,样式

if (rowIndex == 65535 || rowIndex == 0)
{
if (rowIndex != 0)
{
sheet = workbook.CreateSheet("Sheet1");
}

#region 表头及样式

{
if (excelConfig.Title != null)
{
IRow headerRow = sheet.CreateRow(0);
if (excelConfig.TitleHeight != 0)
{
headerRow.Height = (short)(excelConfig.TitleHeight * 20);
}
headerRow.HeightInPoints = 25;
headerRow.CreateCell(0).SetCellValue(excelConfig.Title);
headerRow.GetCell(0).CellStyle = headStyle;
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1)); // ------------------
}
}

#endregion 表头及样式

#region 列头及样式

{
IRow headerRow = sheet.CreateRow(1);

#region 如果设置了列标题就按列标题定义列头,没定义直接按字段名输出

foreach (DataColumn column in dtSource.Columns)
{
headerRow.CreateCell(column.Ordinal).SetCellValue(arrColName[column.Ordinal]);
headerRow.GetCell(column.Ordinal).CellStyle = cHeadStyle;
//设置列宽
sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
}

#endregion 如果设置了列标题就按列标题定义列头,没定义直接按字段名输出
}

#endregion 列头及样式

rowIndex = 2;
}

#endregion 新建表,填充表头,填充列头,样式

#region 填充内容

IRow dataRow = sheet.CreateRow(rowIndex);
foreach (DataColumn column in dtSource.Columns)
{
ICell newCell = dataRow.CreateCell(column.Ordinal);
newCell.CellStyle = arryColumStyle[column.Ordinal];
string drValue = row[column].ToString();
SetCell(newCell, dateStyle, column.DataType, drValue);
}

#endregion 填充内容

rowIndex++;
}
using (var ms = new NpoiMemoryStream())
{
ms.AllowClose = false;
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
ms.Seek(0, SeekOrigin.Begin);
return ms;
}
}

#endregion DataTable导出到Excel的MemoryStream

#region ListExcel导出(加载模板)

/// <summary>
/// List根据模板导出ExcelMemoryStream
/// </summary>
/// <param name="list"></param>
/// <param name="templdateName"></param>
public static MemoryStream ExportListByTempale(List<TemplateMode> list, string templdateName)
{
try
{
string templatePath = AppDomain.CurrentDomain.BaseDirectory + "/Resource/ExcelTemplate/";
string templdateName1 = string.Format("{0}{1}", templatePath, templdateName);

FileStream fileStream = new FileStream(templdateName1, FileMode.Open, FileAccess.Read);
ISheet sheet = null;
if (templdateName.IndexOf(".xlsx") == -1)//2003
{
HSSFWorkbook hssfworkbook = new HSSFWorkbook(fileStream);
sheet = hssfworkbook.GetSheetAt(0);
SetPurchaseOrder(sheet, list);
sheet.ForceFormulaRecalculation = true;
using (MemoryStream ms = new MemoryStream())
{
hssfworkbook.Write(ms);
ms.Flush();
return ms;
}
}
else//2007
{
XSSFWorkbook xssfworkbook = new XSSFWorkbook(fileStream);
sheet = xssfworkbook.GetSheetAt(0);
SetPurchaseOrder(sheet, list);
sheet.ForceFormulaRecalculation = true;
using (MemoryStream ms = new MemoryStream())
{
xssfworkbook.Write(ms);
ms.Flush();
return ms;
}
}
}
catch (Exception)
{
throw;
}
}

/// <summary>
/// 赋值单元格
/// </summary>
/// <param name="sheet"></param>
/// <param name="list"></param>
private static void SetPurchaseOrder(ISheet sheet, List<TemplateMode> list)
{
try
{
foreach (TemplateMode item in list)
{
IRow row = null;
ICell cell = null;
row = sheet.GetRow(item.row);
if (row == null)
{
row = sheet.CreateRow(item.row);
}
cell = row.GetCell(item.cell);
if (cell == null)
{
cell = row.CreateCell(item.cell);
}
cell.SetCellValue(item.value);
}
}
catch (Exception)
{
throw;
}
}

#endregion ListExcel导出(加载模板)

#region 设置表格内容

private static void SetCell(ICell newCell, ICellStyle dateStyle, Type dataType, string drValue)
{
switch (dataType.ToString())
{
case "System.String"://字符串类型
newCell.SetCellValue(drValue);
break;

case "System.DateTime"://日期类型
System.DateTime dateV;
if (System.DateTime.TryParse(drValue, out dateV))
{
newCell.SetCellValue(dateV);
}
else
{
newCell.SetCellValue("");
}
newCell.CellStyle = dateStyle;//格式化显示
break;

case "System.Boolean"://布尔型
bool boolV = false;
bool.TryParse(drValue, out boolV);
newCell.SetCellValue(boolV);
break;

case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = 0;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
break;

case "System.Decimal"://浮点型
case "System.Double":
double doubV = 0;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
break;

case "System.DBNull"://空值处理
newCell.SetCellValue("");
break;

default:
newCell.SetCellValue("");
break;
}
}

#endregion 设置表格内容

#region 从Excel导入

/// <summary>
/// 读取excel ,默认第一行为标头
/// </summary>
/// <param name="strFileName">excel文档路径</param>
/// <returns></returns>
public static DataTable ExcelImport(string strFileName)
{
DataTable dt = new DataTable();

ISheet sheet = null;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
if (strFileName.IndexOf(".xlsx") == -1)//2003
{
HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
sheet = hssfworkbook.GetSheetAt(0);
}
else//2007
{
XSSFWorkbook xssfworkbook = new XSSFWorkbook(file);
sheet = xssfworkbook.GetSheetAt(0);
}
}

System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

IRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;

for (int j = 0; j < cellCount; j++)
{
ICell cell = headerRow.GetCell(j);
dt.Columns.Add(cell.ToString());
}

for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = dt.NewRow();

for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
{
dataRow[j] = row.GetCell(j).ToString();
}
}

dt.Rows.Add(dataRow);
}
return dt;
}

#endregion 从Excel导入

#region RGB颜色转NPOI颜色

private static short GetXLColour(HSSFWorkbook workbook, Color SystemColour)
{
short s = 0;
HSSFPalette XlPalette = workbook.GetCustomPalette();
NPOI.HSSF.Util.HSSFColor XlColour = XlPalette.FindColor(SystemColour.R, SystemColour.G, SystemColour.B);
if (XlColour == null)
{
if (NPOI.HSSF.Record.PaletteRecord.STANDARD_PALETTE_SIZE < 255)
{
XlColour = XlPalette.FindSimilarColor(SystemColour.R, SystemColour.G, SystemColour.B);
s = XlColour.Indexed;
}
}
else
{
s = XlColour.Indexed;
}

return s;
}

#endregion RGB颜色转NPOI颜色

#region 设置列的对齐方式

/// <summary>
/// 设置对齐方式
/// </summary>
/// <param name="style"></param>
/// <returns></returns>
private static HorizontalAlignment GetAlignment(string style)
{
switch (style)
{
case "center":
return HorizontalAlignment.Center;

case "left":
return HorizontalAlignment.Left;

case "right":
return HorizontalAlignment.Right;

case "fill":
return HorizontalAlignment.Fill;

case "justify":
return HorizontalAlignment.Justify;

case "centerselection":
return HorizontalAlignment.CenterSelection;

case "distributed":
return HorizontalAlignment.Distributed;
}
return NPOI.SS.UserModel.HorizontalAlignment.General;
}

#endregion 设置列的对齐方式
}