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
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");
}
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"
);
}
In my application am allowing the user to create PDF file. Also the user can add shapes(like rectangle, line),, form fields (textarea, checkbox..) in the PDF file. when user clicks on save button PDF gets created successfully but the shapes and form fields that user has included in his document doesn't appear.
function create_PDF(box) {
var filename = $("#filename").val();
if (filename == "") {
alert("Enter filename");
return false;
}
var content = CKEDITOR.instances["message"].getData();
if (content == "") {
alert("Enter Content in The Editor");
return false;
}
content = content.trim();
dhtmlx.modalbox.hide(box);
dhtmlx.message("Saving file...");
$.post("/FileUpload/CreateNewPDFile",
{
filename: '' + filename + '', content: '' + content + ''
}, function (data) {
alert("PDF File created succesfully");
CKEDITOR.instances["message"].setData("");
CKEDITOR.instances["editor1"].setData("");
});
}
[AcceptVerbs(HttpVerbs.Post)]
[ValidateInput(false)]
public ActionResult CreateNewPDFile(FormCollection data)
{
var filename = data["filename"];
var htmlContent = data["content"];
string sFilePath = Server.MapPath(_createdPDF + filename + ".pdf");
htmlContent = htmlContent.Trim();
htmlContent = htmlContent.Replace("<p>", "\n").Replace("</p>", "\n");
Regex reg = new Regex("<[^>]+>", RegexOptions.IgnoreCase);
if (!System.IO.File.Exists(sFilePath))
{
Document doc = new Document(PageSize.A4, 10, 10, 10, 10);
doc.SetMargins(50, 50, 50, 50);
doc.SetPageSize(new iTextSharp.text.Rectangle(iTextSharp.text.PageSize.LETTER.Width, iTextSharp.text.PageSize.LETTER.Height));
PdfWriter.GetInstance(doc, new System.IO.FileStream(sFilePath, System.IO.FileMode.Create));
iTextSharp.text.Font fnt = FontFactory.GetFont("Times New Roman", 14);
doc.Open();
PdfPTable pdfTab = new PdfPTable(1);
PdfPCell pdfCell = null;
pdfCell = new PdfPCell(new Phrase(new Chunk(htmlContent)));
pdfTab.AddCell(pdfCell);
doc.Add(pdfTab);
doc.Close();
Response.ContentType = "application/pdf";
System.Web.HttpContext.Current.Response.Write(doc);
Response.Flush();
Response.End();
}
return View();
}
If use includes textarea , rectangle and checkmark in the newly created PDF instead of textarea, rectangle and checkmark the following thing appears how can i avoid this code and can display on the respective images in the document
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..