I want to export a list to CSV file using MVC, Jquery. I want to write to a file to the response stream but doesn't do anything. No Download appear.
Below is my code in .cshtml
<button id="btnGenerateCSV">Generate CSV</button>
in .js
$('#btnGenerateCSV').click(function () {
$.post(root + "ClaimInternal/DownloadCsv");
});
In myController
private string GetCsvString(IList<Area> Area)
{
StringBuilder csv = new StringBuilder();
csv.AppendLine("AreaID,AliasName,Description,BankName");
foreach (Area area in Area)
{
csv.Append(area.AreaID + ",");
csv.Append(area.AliasName + ",");
csv.Append(area.Description + ",");
csv.Append(area.BankName + ",");
csv.AppendLine();
}
return csv.ToString();
}
public void DownloadCsv()
{
using (Database db = new Database(_ConnectionString))
{
AreaDAC dacArea = new AreaDAC(db);
List<Area> data = dacArea.Search("", "", "");
string facsCsv = GetCsvString(data);
// Return the file content with response body.
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=Area.csv");
Response.Write(facsCsv);
Response.End();
}
}
I try to make like this also
public FileContentResult DownloadCsv()
{
using (Database db = new Database(_ConnectionString))
{
AreaDAC dacArea = new AreaDAC(db);
List<Area> data = dacArea.Search("", "", "");
JsonResult result = new JsonResult();
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
result.Data = data;
string facsCsv = GetCsvString(data);
return File(new System.Text.UTF8Encoding().GetBytes(facsCsv), "text/csv", "Area.csv");
}
}
I make also like this
public void DownloadCsv()
{
using (Database db = new Database(_ConnectionString))
{
AreaDAC dacArea = new AreaDAC(db);
List<Area> data = dacArea.Search("", "", "");
string facsCsv = GetCsvString(data);
// Return the file content with response body.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Area.csv");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(facsCsv);
Response.Flush();
Response.End();
}
}
But still not work.. No download CSV appear.. While When I got it all working, no error.
Now I already got the answer. I change the script like this and it's work..
var cd = new System.Net.Mime.ContentDisposition
{
FileName = "Area.csv",
Inline = true,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(new System.Text.UTF8Encoding().GetBytes(facsCsv), "text/csv");
It's work by adding new System.Net.Mime.ContentDisposition. But I'm still not understand why.
I was able to do using
window.location = "/urlPath?filename=" + filename;
and in my controller
filename = filename.ToString();
byte[] fileBytes = System.IO.File.ReadAllBytes(filename);
var response = new FileContentResult(fileBytes, "application/octet-stream");
response.FileDownloadName = "Filename.csv";
return response;
Related
The pdf downloads fine but with a random name - 9619012021194536.pdf
I'm trying to set a custom name but it is not working.
The downloaded file still has a random name instead of the custom name being set in code.
public ActionResult Appointment(int id)
{
Stream stream = null;
string fileName = "";
try
{
stream = GenerateAppointmentReport(id);
fileName = id + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".pdf";
}
catch (Exception ex)
{
}
return new FileStreamResult(stream, MimeMapping.GetMimeMapping(fileName))
{ FileDownloadName = fileName };
}
You can use this code:
public ActionResult Appointment(int id)
{
Stream stream = null;
string fileName = "";
try
{
stream = GenerateAppointmentReport(id);
fileName = id + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".pdf";
}
catch (Exception ex)
{
}
return new FileStreamResult(stream, "binary") { FileDownloadName = fileName };
}
I used this code and the file was downloaded with the specific name I mentioned.
You can bind the data in a temporary object of type GridView and then write the object to the output stream like this:
public ActionResult Appointment(int id)
{
GridView gridview = new GridView();
gridview.DataSource = fileData; //fileData is an object with all the properties
gridview.DataBind();
Response.ClearContent();
Response.Buffer = true;
tmpfileName = id + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".pdf";
Response.AddHeader("content-disposition", "attachment; filename = " + tmpfileName);
Response.ContentType = "application/pdf";
Response.Charset = "";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
gridview.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
return RedirectToAction("Appointment"); // To another/same action
}
How to download an excel in a chrome browser having options as Open, Save and Cancel as I used closed Xml in C#?
public FileResult ExportToExcel(List<MyStudentList_Result> StudentList)
{
List<string[]> titles = new List<string[]> { new string[] { "name", "Number", "Type", "syllabus", "Title", "Added" } };
byte[] fileStream = ExportToExcel(StudentList, "StudentList", titles);
string mimeType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AppendHeader("Content-Disposition", "inline; filename=" + "StudentList.xlsx");
return File(fileStream, mimeType);
}
public byte[] ExportToExcel(List<MystudentList_Result> StudentList, string worksheetTitle, List<string[]> titles)
{
var wb = new XLWorkbook(); //create workbook
var ws = wb.Worksheets.Add(worksheetTitle); //add worksheet to workbook
var rangeTitle = ws.Cell(1, 1).InsertData(titles); //insert titles to first row
rangeTitle.AddToNamed("Titles");
var titlesStyle = wb.Style;
titlesStyle.Font.Bold = true; //font must be bold
// titlesStyle.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; //align text to center
wb.NamedRanges.NamedRange("Titles").Ranges.Style = titlesStyle; //attach style to the range
if (StudentList!= null && StudentList.Count() > 0)
{
//insert data to from second row on
ws.Cell(2, 1).InsertData(StudentList);
ws.Columns().AdjustToContents();
}
//save file to memory stream and return it as byte array
using (var ms = new MemoryStream())
{
wb.SaveAs(ms);
return ms.ToArray();
}
}
You can guide what the browser does with the Content-Disposition header. For saving the file you should use attachment:
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Using a LINQ query I need to export to Excel when a WebApi method is called. I have built the LINQ query that will return the correct data, now I need it to export to .csv or Excel file format.
I have tried using MemoryStream and StreamWriter but I think I am just chasing my tail now.
[HttpGet]
[Route("Download")]
public Task<IActionResult> Download(int memberId)
{
var results = (from violations in _db.tblMappViolations
where violations.MemberID == memberId
select new IncomingViolations
{
Contact = violations.ContactName,
Address = violations.str_Address,
City = violations.str_City,
State = violations.str_State,
Zip = violations.str_Zipcode,
Country = violations.str_Country,
Phone = violations.str_Phone,
Email = violations.str_Email,
Website = violations.str_WebSite,
}).FirstOrDefault();
MemoryStream stream = new MemoryStream(results);
StreamWriter writer = new StreamWriter(stream);
writer.Flush();
stream.Position = 0;
FileStreamResult response = File(stream, "application/octet-stream");
response.FileDownloadName = "violations.csv";
return response;
}
Here is how you can send CSV file to the user from server.
string attachment = "attachment; filename=MyCsvLol.csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.AddHeader("Pragma", "public");
var sb = new StringBuilder();
// Add your data into stringbuilder
sb.Append(results.Contact);
sb.Append(results.Address);
sb.Append(results.City);
// and so on
HttpContext.Current.Response.Write(sb.ToString());
For Sending it from API
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
// Write Your data here in writer
writer.Write("Hello, World!");
writer.Flush();
stream.Position = 0;
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };
return result;
Update:-
public HttpResponseMessage Download()
{
var results = (from violations in _db.tblMappViolations
where violations.MemberID == memberId
select new IncomingViolations
{
Contact = violations.ContactName,
Address = violations.str_Address,
City = violations.str_City,
State = violations.str_State,
Zip = violations.str_Zipcode,
Country = violations.str_Country,
Phone = violations.str_Phone,
Email = violations.str_Email,
Website = violations.str_WebSite,
});
var sb = new StringBuilder();
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
foreach(var tempResult in results)
{
sb.Append(tempResult.Contact+",");
sb.Append(tempResult.Address+",");
sb.Append(tempResult.City+",");
sb.Append(tempResult.State+",");
sb.Append(tempResult.Zip+",");
sb.Append(tempResult.Country+",");
sb.Append(tempResult.Phone+",");
sb.Append(tempResult.Email+",");
sb.Append(tempResult.Website+",");
sb.Append(Enviroment.NewLine);
}
writer.Write(sb.ToString());
writer.Flush();
stream.Position = 0;
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };
return result;
}
First, to reuse the code in other areas, always create helper classes.
I adopted this method of converting list into a stream with headers as property names, if you want a file from this, essentially, I would just add another step to this:
STEP 1:
public static Stream ConvertToCSVStream<T>(IEnumerable<T> objects)
{
Type itemType = typeof(T);
var properties = itemType.GetProperties();
var mStream = new MemoryStream();
StreamWriter sWriter = new StreamWriter(mStream);
var values = objects.Select(o =>
{
return string.Join(",", properties.Select(p =>
{
var value = p.GetValue(o).ToString();
if (!Regex.IsMatch(value, "[,\"\\r\\n]"))
{
return value;
}
value = value.Replace("\"", "\"\"");
return string.Format("\"{0}\"", value);
})) + sWriter.NewLine;
});
var valuesInStrings = values.Aggregate((current, next) => current + next);
try
{
sWriter.Write(string.Join(",", properties.Select(x => x.Name.Replace("_", " "))) + sWriter.NewLine);
sWriter.Write(valuesInStrings);
}
catch (Exception e)
{
mStream.Close();
throw e;
}
sWriter.Flush();
mStream.Position = 0;
return mStream;
}
if your data is text, just convert it directly to a file result but if not, you must convert it to binary array and write it to stream, refer to this article for converting it to binary data, in our case, for csv, you could just use the FileStream result that you've implemented in a separate method:
STEP 2:
public FileStreamResult CreateFile(MemoryStream mStream, string path, string name)
{
//set values, names, content type, etc
//return filestream
}
or any other method you find better.
Save your result in a DataTable and then just use this
XLWorkbook workbook = new XLWorkbook();
DataTable table = GetYourTable();
workbook.Worksheets.Add(table);
And you should definitely use stream writer for this if you know which file its going to write to from the start, else stream reader and then stream writer.
I am trying to download Excel file using web API but I am unable to download file in postman where as I am able to download Excel file when I enter URL in browser though while opening file I get warning message like below :
When i hit endpoint using POSTMAN then file get corrupted and it is showing junk characters.
Code :
protected virtual byte[] ExportToXlsx<T>(IEnumerable<T> itemsToExport)
{
using (var stream = new MemoryStream())
{
using (var xlPackage = new ExcelPackage())
{
// get handles to the worksheets
var worksheet = xlPackage.Workbook.Worksheets.Add(typeof(T).Name);
//create Headers and format them
var manager = new PropertyManager<T>(itemsToExport.First());
manager.WriteCaption(worksheet, SetCaptionStyle);
var row = 2;
foreach (var items in itemsToExport)
{
manager.CurrentObject = items;
manager.WriteToXlsx(worksheet, row++, false);
}
xlPackage.Save();
}
return stream.ToArray();
}
}
private readonly IServiceContext ctx;
public void Download(string guid)
{
var bytes = ExportToXlsx(list);
ctx.reqobj.HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=\"demo.xlsx\"");
ctx.reqobj.HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
ctx.reqobj.HttpContext.Response.Body.Write(bytes, 0, bytes.Length);
}
Note : I am using OfficeOpenXml for Excel file creation.
I will appreciate any help.
Update :
Try using "Send and download" instead of "Send"
https://www.getpostman.com/docs/v6/postman/sending_api_requests/responses
Postman doesn't download any file just return you the data that the server or your service provides. i have a project that download an excel to with the OpenXML here is an example with which you can guide with some styles to.
[HttpGet]
public void DownloadTable(int id)
{
List<Employee> all = db.Employees.Where(x => x.ManagerId == id).ToList();
String file = "Example.xlsx";
String path = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"), file);
List<string[]> headerRow = new List<string[]>() { new string[] { "EmployeeId", "Name", "Shift", "Timestamp" } };
string headerRange = "A2:" + Char.ConvertFromUtf32(headerRow[0].Length + 64) + "2";
ExcelPackage excel = new ExcelPackage();
excel.Workbook.Worksheets.Add("Employees");
var page = excel.Workbook.Worksheets["Employees"];
page.Cells["A1:D1"].Merge = true;
page.Cells["A1:D1"].Value = "Supervisor: " + all.FirstOrDefault().Manager + " - " + id;
page.Cells["A1:D1"].Style.Font.Bold = true;
page.Cells[headerRange].LoadFromArrays(headerRow);
int z = 3;
foreach (Reporte r in all)
{
page.Cells["A" + z].Value = r.Id;
page.Cells["B" + z].Value = r.Name;
page.Cells["C" + z].Value = r.Shift;
page.Cells["D" + z].Value = r.Timestamp;
z++;
}
page.Cells["D3:D" + z].Style.Numberformat.Format = "dddd dd MMMM YYYY";
page.Cells["A2:D2"].AutoFilter = true;
page.Cells["A1:D" + z].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
page.Cells["A1:D" + z].Style.VerticalAlignment = ExcelVerticalAlignment.Center;
page.Cells["A2:D" + z].AutoFitColumns();
page.Cells["A1:D1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
page.Cells["A1:D1"].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(1, 183, 222, 232));
FileInfo excelFile = new FileInfo(path);
excel.SaveAs(excelFile);
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition",
"attachment; filename=" + file + ";");
response.TransmitFile(path);
response.Flush();
response.End();
File.Delete(path);
}
The stream needs to be passed to the package.
Right now nothing is being given to the package,
//...
using (var xlPackage = new ExcelPackage())
//...
So nothing is being saved to the stream, which is why the error is shown when trying to open the file.
There is no need to convert the memory stream to an array. Return the stream and pass that along for the response.
protected virtual Stream ExportToXlsx<T>(IEnumerable<T> itemsToExport) {
var stream = new MemoryStream();
using (var xlPackage = new ExcelPackage(stream)) { //<<< pass stream
// get handles to the worksheets
var worksheet = xlPackage.Workbook.Worksheets.Add(typeof(T).Name);
//create Headers and format them
var manager = new PropertyManager<T>(itemsToExport.First());
manager.WriteCaption(worksheet, SetCaptionStyle);
var row = 2;
foreach (var items in itemsToExport) {
manager.CurrentObject = items;
manager.WriteToXlsx(worksheet, row++, false);
}
xlPackage.Save();
}
return stream;
}
A controller action to return the file would look like this
public IActionResult Download(string guid) {
//...get list
var file = ExportToXlsx(list);
var contentType = "application/vnd.openxmlformats";
var fileName = "demo.xlsx";
return File(file, contentType, fileName); //returns a FileStreamResult
}
It was indicated in comments that the above is done in a support method.
Using the same approach
private readonly IServiceContext ctx;
//...
public void Download(string guid) {
//...get list
using(var fileStream = ExportToXlsx(list)) {
if (fileStream.CanSeek && fileStream.Position != 0) {
fileStream.Seek(0, SeekOrigin.Begin);
}
var contentType = "application/vnd.openxmlformats";
var fileName = "demo.xlsx";
var response = ctx.reqobj.HttpContext.Response;
response.Headers.Add("Content-Disposition", $"attachment; filename=\"{fileName}\"");
response.Headers.Add("Content-Length", fileStream.Length.ToString());
response.ContentType = contentType;
fileStream.CopyTo(response.Body);
}
}
the generated file is copied over to the body of the response.
As for postman, the tool is simply showing the content return in the response. It does not try to download the actual file as an attachment.
I am getting the following error:
, value hexadecimal 0x02, caracter not valid.
using this code:
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt1);
Response.Clear();
Response.Buffer = true;
Response.Charset ="";
Response.ContentType = "application/vnd.openxmlformats- officedocument.spreadsheetml.sheet";
//Response.AddHeader("content-disposition", "attachment;filename=GridView.xlsx");
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
I have tried different ways, but I still get the same error. "dt1" is filled from stored procedure.
to use ClosedXML I am currently doing the following and I call this method to open the Excel from a web page.
to call the ExportToExcel_SomeReport you would do it like this I create a public static class called Extensions
Extensions.ExportToXcel_SomeReport(dt1, fileName, this.Page);//Call the method on your button click
//this will be in the static public class you create
internal static void ExportToXcel_SomeReport(DataTable dt, string fileName, Page page)
{
var recCount = dt.Rows.Count;
fileName = string.Format(fileName, DateTime.Now.ToString("MMddyyyy_hhmmss"));
var xlsx = new XLWorkbook();
var ws = xlsx.Worksheets.Add("Some Custom Report");
ws.Style.Font.Bold = true;
ws.Cell("C5").Value = "Some Custom Header Report";
ws.Cell("C5").Style.Font.FontColor = XLColor.Black;
ws.Cell("C5").Style.Font.SetFontSize(16.0);
ws.Cell("E5").Value = DateTime.Now.ToString("MM/dd/yyyy HH:mm");
ws.Range("C5:E5").Style.Font.SetFontSize(16.0);
ws.Cell("A7").Value = string.Format("{0} Records", recCount);
ws.Style.Font.Bold = false;
ws.Cell(9, 1).InsertTable(dt.AsEnumerable());
ws.Row(9).InsertRowsBelow(1);
// ws.Style.Font.FontColor = XLColor.Gray;
ws.Columns("1-8").AdjustToContents();
ws.Tables.Table(0).ShowAutoFilter = true;
ws.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
DynaGenExcelFile(fileName, page, xlsx);
}
private static void DynaGenExcelFile(string fileName, Page page, XLWorkbook xlsx)
{
page.Response.ClearContent();
page.Response.ClearHeaders();
page.Response.ContentType = "application/vnd.ms-excel";
page.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.xls", fileName));
using (MemoryStream memoryStream = new MemoryStream())
{
xlsx.SaveAs(memoryStream);
memoryStream.WriteTo(page.Response.OutputStream);
memoryStream.Close();
}
page.Response.Flush();
page.Response.End();
}