【发布时间】:2019-09-25 08:02:37
【问题描述】:
我使用 C# 制作了一个 API,并使用 is 作为我的 Angular 项目的后端。我的任务是通过一个以角度制作的按钮将数据保存为我的页面中的 excel 文件。逻辑在后端。我已经尝试了一切来实现这一点,但似乎没有任何效果。我现在正在使用 EPPlus,使用 SaveAs 方法,将 excel 包转换为字节数组。
这是我在 C# 中的功能
public IHttpActionResult CreateExcelDocument()
{
//Creates a blank workbook. Using statement disposes the package.
using (var p = new ExcelPackage())
{
var result = new MemoryStream();
List<Hero> heroes = new List<Hero>();
var documents = collection.Find(new BsonDocument()).ToList();
foreach (BsonDocument docum in documents)
{
heroes.Add(BsonSerializer.Deserialize<Hero>(docum));
}
//Adding worksheet
var ws = p.Workbook.Worksheets.Add("Heroes");
//To set values in the spreadsheet use the Cells indexer.
ws.Cells["A1"].Value = "ID";
ws.Cells["B1"].Value = "Name";
for(var row = 1; row <= heroes.Count(); row++)
{
ws.Cells[row, 1].LoadFromCollection(heroes[row].Id);
ws.Cells[row, 2].LoadFromCollection(heroes[row].Name);
}
var stream = new MemoryStream(p.GetAsByteArray());
//string filePath = @"c:\workbooks\myworkbook.xlsx";
//FileInfo template = new FileInfo(filePath);
//MemoryStream outputStream = new MemoryStream();
p.SaveAs(stream);
return Ok(stream);
}
}
这是如何获得它的角度
saveDocument(): Observable<any> {
return this.http.get<any>(this.heroesUrl)
.pipe(
tap(p => this.log('saved excel document' + p)),
catchError(this.handleError<any>('saveDocument', []))
);
}
我创建了一个消息组件来显示我的 API 请求的状态,因此使用 saveDocument 我得到了这个: HeroService: saved excel document[object Object],[object Object],[object Object],[object Object] ,[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象]
我正在使用 MongoDB、Angular 8 和 ASP.NET Web API 2 (C#)
编辑:这里是角度按钮
<button (click)="saveDocument()"> Save heroes </button>
【问题讨论】:
标签: c# excel angular mongodb asp.net-web-api