using System;
using System.Collections.Generic;
namespace Barcelo.API.FileGenerator.Models
{
public class ExcelStructure
{
public List<String> header { get; set; }
public List<string[]> body { get; set; }
}
}
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Net.Http.Headers;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
namespace Barcelo.API.FileGenerator.Controllers
{
public class ExcelController : ApiController
{
private const string FILENAME = "document";
private const string FILEEXTENSION = "xlsx";
[HttpPost]
[Route("api/excel")]
public HttpResponseMessage Post([FromBody]Models.ExcelStructure json)
{
string tempFileName = Guid.NewGuid().ToString();
string path = String.Format("{0}\\{1}.{2}", Path.GetTempPath(), tempFileName, FILEEXTENSION);
try
{
IWorkbook workbook = new XSSFWorkbook();
ISheet sheet1 = workbook.CreateSheet("Sheet1");
IRow rowHeader = sheet1.CreateRow(0);
IFont font = (XSSFFont)workbook.CreateFont();
font.IsBold = true;
ICellStyle style = (XSSFCellStyle)workbook.CreateCellStyle();
style.SetFont(font);
for (int i = 0; i < json.header.Count; i++)
{
ICell cell = rowHeader.CreateCell(i);
cell.CellStyle = style;
cell.SetCellValue(json.header[i]);
}
for (int i = 0; i < json.body.Count; i++)
{
IRow row = sheet1.CreateRow(1 + i);
for (int j = 0; j < json.body[i].Length; j++)
{
ICell cell = row.CreateCell(j);
cell.SetCellValue(json.body[i][j].ToString());
}
}
FileStream fs = File.Create(path);
workbook.Write(fs);
HttpResponseMessage result = Request.CreateResponse(HttpStatusCode.OK);
using (fs = File.OpenRead(path))
{
MemoryStream ms = new MemoryStream();
ms.SetLength(fs.Length);
fs.Read(ms.GetBuffer(), 0, (int)fs.Length);
result.Content = new StreamContent(ms);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = $"{FILENAME}.{FILEEXTENSION}"
};
}
fs.Close();
File.Delete(path);
return result;
}
catch (Exception e)
{
throw;
}
}
}
}