Export data to PDF in MVC4 - asp.net-mvc

I am trying to export a list to PDF in MVC4.
Recently saw this code which exports list to Excel.
public ActionResult ExportDataExcel()
{
var y= TempData["List"]; //list
GridView gv = new GridView();
gv.DataSource = y;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Exam_Email_Report.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return RedirectToAction("TestReport", "Test");
}
I was wondering how to export list to PDF. Please give me some pointers that could help me.
Thanks

Related

Export IEnumerable object To Docx File (MVC)

We are using Kendo Grid for listing and needs to export record with filter to doc/Docx file.
Does Any one has idea about how to export IEumarable object to Doc/Docx file.
Here Code Snippet:
public FileResult ExportToWord([DataSourceRequest]DataSourceRequest request)
{
IEnumerable rows = dtView.ToDataSourceResult(request).Data;
MemoryStream output = new MemoryStream();
workbook.Write(output);
return File(output.ToArray(), "application/vnd.ms-word", "GridExcelExport.doc");
}
Any Help ?
You can try below code
public ActionResult ExportData()
{
GridView gv = new GridView();
gv.DataSource = db.Studentrecord.ToList();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Marklist.doc");
Response.ContentType = "application/vnd.ms-word ";
Response.Charset = string.Empty;
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return RedirectToAction("StudentDetails");
}

How to export to pdf, word, excel file

I use ASP.net MVC 3.
I have these two requirement.
Frist one is creating invoice in my application. I want to export the datas to pdf , word , excel file. I downloaded itextsharp dll, can anyone tel me is there anyother alternative to datas in the ui to pdf, word and excel document?
Second is I need print the document after clicking the print button. How to connect printer with the print button in the exported document ?
You can use a snippet.
This one is great. Take a look on it.
This is an example of usage:
HTML
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green" AllowPaging ="true"
OnPageIndexChanging = "OnPaging" >
<Columns>
<asp:BoundField ItemStyle-Width = "150px" DataField = "CustomerID"
HeaderText = "CustomerID" />
<asp:BoundField ItemStyle-Width = "150px" DataField = "City"
HeaderText = "City"/>
<asp:BoundField ItemStyle-Width = "150px" DataField = "Country"
HeaderText = "Country"/>
<asp:BoundField ItemStyle-Width = "150px" DataField = "PostalCode"
HeaderText = "PostalCode"/>
</Columns>
</asp:GridView>
C# for pdf example
protected void btnExportPDF_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f,10f,10f,0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
C# for excel example
protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Apply style to Individual Cells
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");
for (int i = 0; i < GridView1.Rows.Count;i++ )
{
GridViewRow row = GridView1.Rows[i];
//Change Color back to white
row.BackColor = System.Drawing.Color.White;
//Apply text style to each Row
row.Attributes.Add("class", "textmode");
//Apply style to Individual Cells of Alternating Row
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
row.Cells[3].Style.Add("background-color", "#C2D69B");
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}

Export data to Excel file with ASP.NET MVC 4 C# is rendering into view

I am having trouble exporting data to Excel. The following seems to render the gridview into my View, instead of prompting the user to open with Excel, which I have installed on my machine.
Public ActionResult ExportToExcel()
{
var products = this.Repository.Products.ToList();
var grid = new GridView();
grid.DataSource = from p in products
select new
{
Id = p.Id,
Name = p.Name
};
grid.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return View("MyView");
}
What am I doing wrong?
I have tried your code and it works just fine.
The file is being created without any problem, this is the code I used (it's your code, I just changed the datasource for testing):
public ActionResult ExportToExcel()
{
var products = new System.Data.DataTable("teste");
products.Columns.Add("col1", typeof(int));
products.Columns.Add("col2", typeof(string));
products.Rows.Add(1, "product 1");
products.Rows.Add(2, "product 2");
products.Rows.Add(3, "product 3");
products.Rows.Add(4, "product 4");
products.Rows.Add(5, "product 5");
products.Rows.Add(6, "product 6");
products.Rows.Add(7, "product 7");
var grid = new GridView();
grid.DataSource = products;
grid.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return View("MyView");
}
You can call helper class in any controller
//view
#Html.ActionLink("Export to Excel", "Excel")
//controller Action
public void Excel()
{
var model = db.GetModel()
Export export = new Export();
export.ToExcel(Response, model);
}
//helper class
public class Export
{ public void ToExcel(HttpResponseBase Response, object clientsList)
{
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = clientsList;
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
}
Step 1: View page code
<input type="button" id="btnExport" value="Export" class="btn btn-primary" />
<script>
$(document).ready(function () {
$('#btnExport').click(function () {
window.location = '/Inventory/ExportInventory';
});
});
</script>
Step 2: Controller Code
public ActionResult ExportInventory()
{
//Load Data
var dataInventory = _inventoryService.InventoryListByPharmacyId(pId);
string xml=String.Empty;
XmlDocument xmlDoc = new XmlDocument();
XmlSerializer xmlSerializer = new XmlSerializer(dataInventory.GetType());
using (MemoryStream xmlStream = new MemoryStream())
{
xmlSerializer.Serialize(xmlStream, dataInventory);
xmlStream.Position = 0;
xmlDoc.Load(xmlStream);
xml = xmlDoc.InnerXml;
}
var fName = string.Format("Inventory-{0}", DateTime.Now.ToString("s"));
byte[] fileContents = Encoding.UTF8.GetBytes(xml);
return File(fileContents, "application/vnd.ms-excel", fName);
}
using (MemoryStream mem = new MemoryStream())
{
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(mem, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new Workbook();
// Add a WorksheetPart to the WorkbookPart.
WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();
// Add a row to the cell table.
Row row;
row = new Row() { RowIndex = 1 };
sheetData.Append(row);
// In the new row, find the column location to insert a cell in A1.
Cell refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
if (string.Compare(cell.CellReference.Value, "A1", true) > 0)
{
refCell = cell;
break;
}
}
// Add the cell to the cell table at A1.
Cell newCell = new Cell() { CellReference = "A1" };
row.InsertBefore(newCell, refCell);
// Set the cell value to be a numeric value of 100.
newCell.CellValue = new CellValue("100");
newCell.DataType = new EnumValue<CellValues>(CellValues.Number);
// Append a new worksheet and associate it with the workbook.
Sheet sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "mySheet"
};
sheets.Append(sheet);
workbookpart.Workbook.Save();
spreadsheetDocument.Close();
return File(mem.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, "text.xlsx");
}
I have done this before, I think you need to remove the ActionResult. Make it a void and remove the return View(MyView). this is the solution
I used a list in my controller class to set data into grid view. The code works fine for me:
public ActionResult ExpExcl()
{
List<PersonModel> person= new List<PersonModel>
{
new PersonModel() {FirstName= "Jenny", LastName="Mathew", Age= 23},
new PersonModel() {FirstName= "Paul", LastName="Meehan", Age=25}
};
var grid= new GridView();
grid.DataSource= person;
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition","attachement; filename=data.xls");
Response.ContentType="application/excel";
StringWriter sw= new StringWriter();
HtmlTextWriter htw= new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return View();
}
The modest way to export excel in MVC is using Microsoft CloseXml. I wrote a simple function for exporting my query result as excel sheet:
using ClosedXML.Excel;
...
public ActionResult ToExcel(List<Dictionary<string, string>> data, Dictionary<string, string> columnMap, string fileName, string sheetName)
{
var dtDataBuffer = new System.Data.DataTable("buffer");
foreach (string col in columnMap.Values)
{
dtDataBuffer.Columns.Add(col, typeof(string));
}
foreach (var row in data)
{
List<string> rowData = new List<string> { };
foreach (string col in columnMap.Keys)
{
rowData.Add(row[col]);
}
dtDataBuffer.Rows.Add(rowData.ToArray());
}
var memoryStream = new MemoryStream();
using (var workbook = new XLWorkbook())
{
var worksheet = workbook.Worksheets.Add(dtDataBuffer, sheetName);
worksheet.Rows().Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
worksheet.Rows().Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
worksheet.Columns().AdjustToContents();
workbook.SaveAs(memoryStream);
}
return File(memoryStream.ToArray(), "application/vnd.ms-excel", fileName);
}
And this is a usage example (in practice I use my own class to run query and generate data. You can find it here for Oracle and SQL Server):
public ActionResult myReportExport(){
var data=List<Dictionary<string, string>>(){
{{"Column1_Index","Column1_Value"},{"Column2_Index","Column2_Value"},...}
...
};
return ToExcel(data, new Dictionary<string, string> {
{ "Column1_Index", "Column1 Title" } ,
{ "Column2_Index", "Column2 Title" } ,
...
},
"myFileName.xlsx",
"my sheet name"
);
}

Caption property not working for gridview in asp.net

I was trying to export pdf file from database in asp.net. Here, I followed this link: http://www.aspsnippets.com/Articles/Export-DataSet-or-DataTable-to-Word-Excel-PDF-and-CSV-Formats.aspx
For Export .doc file:
string strQuery = "select CustomerID, ContactName, City, PostalCode" +
" from customers";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=DataTable.doc");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-word ";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
GridView1.Caption = "<br><br><br>" + "<h3>" + "Register Users Table" + "</h3>" + "<br>";
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
Here Caption was displayed the top of the GridView in the .doc file
For Export .pdf file:
string strQuery = "select CustomerID, ContactName, City, PostalCode" +
" from customers";
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition",
"attachment;filename=DataTable.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
GridView1.Caption = "<br><br><br>" + "<h3>" + "Register Users Table" + "</h3>" + "<br>";
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
Here the Caption of the GridView not displayed... How to display the caption of the Gridview in Exporting the pdf file in C# asp.net
How to do this.. Is there any wrong in my code??
Thanks in advance..

damaged pdf using ITextSharp and mvc

I am trying to generate a pdf out of an MVC3 webpage. I've viewed all the usual tutorials, but as is often the case when one is in a hurry and doesn't really know what one is doing, I'm making a dog's breakfast of it.
When I click the action link on the view to generate the pdf, the file appears to be created, but when I try to open it, I get the ever so helpful message from Adobe Reader that "... the file is damaged and cannot be repaired".
Where have I gone wrong?
public FileStreamResult PDFGenerator()
{
Stream fileStream = GeneratePDF();
HttpContext.Response.AddHeader("content-disposition", "attachment; filename=form.pdf");
return new FileStreamResult(fileStream, "application/pdf");
}
private Stream GeneratePDF()
{
MemoryStream ms = new MemoryStream();
Document doc = new Document();
PdfWriter writer = PdfWriter.GetInstance(doc, ms);
doc.Open();
doc.Add(new Paragraph("Hello"));
ms.Position = 0;
ms.Flush();
writer.Flush();
return ms;
}
You must close the document. Try like this:
public ActionResult PDFGenerator()
{
var doc = new Document();
using (var stream = new MemoryStream())
{
var writer = PdfWriter.GetInstance(doc, stream);
doc.Open();
doc.Add(new Paragraph("Hello"));
doc.Close();
return File(stream.ToArray(), "application/pdf", "test.pdf");
}
}
But that's ugly. I would recommend you a more MVCish approach which consists in writing a custom ActionResult. As an additional advantage of this is that your controller actions will be more easier to unit test in isolation:
public class PdfResult : FileResult
{
public PdfResult(): base("application/pdf")
{ }
public PdfResult(string contentType): base(contentType)
{ }
protected override void WriteFile(HttpResponseBase response)
{
var cd = new ContentDisposition
{
Inline = false,
FileName = "test.pdf"
};
response.AppendHeader("Content-Disposition", cd.ToString());
var doc = new Document();
var writer = PdfWriter.GetInstance(doc, response.OutputStream);
doc.Open();
doc.Add(new Paragraph("Hello"));
doc.Close();
}
}
and then in your controller action:
public ActionResult PDFGenerator()
{
return new PdfResult();
}
Of course this can be taken a step further and have this PdfResult take a view model as constructor argument and generate the PDF based on some properties on this view model:
public ActionResult PDFGenerator()
{
MyViewModel model = ...
return new PdfResult(model);
}
Now things are beginning to look nice.

Resources