Kendo Grid print all data to excel, not just visible data - c#

Let´s say I have grid with 80 items and pagesize is 10, when printing from the controller I want to print all the data, not just the visible data on the first page.
I have good "Export Grid to Excel" test project from Telerik, and I´ve got the export feature all covered and working like a charm. Basically just including the NPOI file and start using it.
Is there a way for me to iterate all the product-data from the DataSourceRequest?
My code sample:
public FileResult Export([DataSourceRequest]DataSourceRequest request)
{
//Get the data representing the current grid state - page, sort and filter
IEnumerable products = db.Products.ToDataSourceResult(request).Data;
//TODO: Get all data but not just the data from the visible page as above!!!
//Create new Excel workbook
var workbook = new HSSFWorkbook();
//Create new Excel sheet
var sheet = workbook.CreateSheet();
//(Optional) set the width of the columns
sheet.SetColumnWidth(0, 10 * 256);
sheet.SetColumnWidth(1, 50 * 256);
sheet.SetColumnWidth(2, 50 * 256);
sheet.SetColumnWidth(3, 50 * 256);
//Create a header row
var headerRow = sheet.CreateRow(0);
//Set the column names in the header row
headerRow.CreateCell(0).SetCellValue("Product ID");
headerRow.CreateCell(1).SetCellValue("Product Name");
headerRow.CreateCell(2).SetCellValue("Unit Price");
headerRow.CreateCell(3).SetCellValue("Quantity Per Unit");
//(Optional) freeze the header row so it is not scrolled
sheet.CreateFreezePane(0, 1, 0, 1);
int rowNumber = 1;
//Populate the sheet with values from the grid data
foreach (Product product in products)
{
//Create a new row
var row = sheet.CreateRow(rowNumber++);
//Set values for the cells
row.CreateCell(0).SetCellValue(product.ProductID);
row.CreateCell(1).SetCellValue(product.ProductName);
row.CreateCell(2).SetCellValue(product.UnitPrice.ToString());
row.CreateCell(3).SetCellValue(product.QuantityPerUnit.ToString());
}
//Write the workbook to a memory stream
MemoryStream output = new MemoryStream();
workbook.Write(output);
//Return the result to the end user
return File(output.ToArray(), //The binary data of the XLS file
"application/vnd.ms-excel", //MIME type of Excel files
"GridExcelExport.xls"); //Suggested file name in the "Save as" dialog which will be displayed to the end user
}

The source from the DataSourceRequest class can be found here.
Probably if you disable the paging properties, you'll get all filtered + sorted data:
public FileResult Export([DataSourceRequest]DataSourceRequest request)
{
request.Take = 9999999;
request.Skip = 0;
// Get the data representing the current grid state : sort and filter
IEnumerable products = db.Products.ToDataSourceResult(request).Data;

After some time I stumbled upon an answer that works. #Stef answer got me on the right track although I didn´t actually use his answer, I will therefore up his answer for the help. I found a way to count the number of pages, and then simply edited the DataSourceRequest for each page. This way ensures me all the pages from the database. I hope this helps others in the future :)
public FileResult Export([DataSourceRequest]DataSourceRequest request)
{
//Count pages to use as iterator when adding to list
var pages = db.Products.ToDataSourceResult(request).Total/request.PageSize;
//Get the data representing the current grid state - page, sort and filter
//IEnumerable products = db.Products.ToDataSourceResult(request).Data;
//Get the data representing the current grid state - page, sort and filter
var products = new List<Product>();
//To ensure all pages get fetched from db
for (int i = 1; i < pages + 1; i++)
{
request.Page = i;
IEnumerable prod = db.Products.ToDataSourceResult(request).Data;
products.AddRange(prod.Cast<Product>().ToList());
}
//Create new Excel workbook
var workbook = new HSSFWorkbook();
//Create new Excel sheet
var sheet = workbook.CreateSheet();
//(Optional) set the width of the columns
sheet.SetColumnWidth(0, 10 * 256);
sheet.SetColumnWidth(1, 50 * 256);
sheet.SetColumnWidth(2, 50 * 256);
sheet.SetColumnWidth(3, 50 * 256);
//Create a header row
var headerRow = sheet.CreateRow(0);
//Set the column names in the header row
headerRow.CreateCell(0).SetCellValue("Product ID");
headerRow.CreateCell(1).SetCellValue("Product Name");
headerRow.CreateCell(2).SetCellValue("Unit Price");
headerRow.CreateCell(3).SetCellValue("Quantity Per Unit");
//(Optional) freeze the header row so it is not scrolled
sheet.CreateFreezePane(0, 1, 0, 1);
int rowNumber = 1;
//Populate the sheet with values from the grid data
foreach (Product product in products)
{
//Create a new row
var row = sheet.CreateRow(rowNumber++);
//Set values for the cells
row.CreateCell(0).SetCellValue(product.ProductID);
row.CreateCell(1).SetCellValue(product.ProductName);
row.CreateCell(2).SetCellValue(product.UnitPrice.ToString());
row.CreateCell(3).SetCellValue(product.QuantityPerUnit.ToString());
}
//Write the workbook to a memory stream
MemoryStream output = new MemoryStream();
workbook.Write(output);
//Return the result to the end user
return File(output.ToArray(), //The binary data of the XLS file
"application/vnd.ms-excel", //MIME type of Excel files
"GridExcelExport.xls"); //Suggested file name in the "Save as" dialog which will be displayed to the end user
}

you may use javascript to print all data to excel, like below
function ExportToCSV() {
var dataSource = $("#grid").data("kendoGrid").dataSource;
var filteredDataSource = new kendo.data.DataSource({
data: dataSource.data(),
filter: dataSource.filter()
});
filteredDataSource.read();
var data = filteredDataSource.view();
var result = "data:application/vnd.ms-excel,";
result += "<table><tr><th>ProductID</th><th>ProductName</th><th>UnitPrice</th><th>Discontinued</th><th>UnitsInStock</th><th>Category</th></tr>";
for (var i = 0; i < data.length; i++) {
result += "<tr>";
result += "<td>";
result += data[i].ProductID;
result += "</td>";
result += "<td>";
result += data[i].ProductName;
result += "</td>";
..
result += "</tr>";
}
result += "</table>";
if (window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(new Blob([result]), 'export.xls');
} else {
window.open(result);
}
e.preventDefault();
}
hope this may help

Related

Preserve empty Excel cells when reading data from clipboard into DataTable

I am using the following code to read Excel data from the clipboard into a C# data table. The code is relatively unchanged as found from this answer to this question. I then add the data table as a data source to a DataGridView control for manipulation.
However, in my Excel data, I have blank/empty cells that I need to preserve, which this code does not do (blank cells are skipped over, effectively compressing each row leaving no empty space; the empty cells are missing from the Excel XML). How could I preserve empty cells when transferring to the data table?
Method:
private DataTable ParseClipboardData(bool blnFirstRowHasHeader)
{
var clipboard = Clipboard.GetDataObject();
if (!clipboard.GetDataPresent("XML Spreadsheet")) return null;
StreamReader streamReader = new StreamReader((MemoryStream)clipboard.GetData("XML Spreadsheet"));
streamReader.BaseStream.SetLength(streamReader.BaseStream.Length - 1);
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(streamReader.ReadToEnd());
XNamespace ssNs = "urn:schemas-microsoft-com:office:spreadsheet";
DataTable dt = new DataTable();
var linqRows = xmlDocument.fwToXDocument().Descendants(ssNs + "Row").ToList<XElement>();
for (int x = 0; x < linqRows.Max(a => a.Descendants(ssNs + "Cell").Count()); x++)
dt.Columns.Add("Column " + x.ToString());
int intCol = 0;
DataRow currentRow;
linqRows.ForEach(rowElement =>
{
intCol = 0;
currentRow = dt.Rows.Add();
rowElement.Descendants(ssNs + "Cell")
.ToList<XElement>()
.ForEach(cell => currentRow[intCol++] = cell.Value);
});
if (blnFirstRowHasHeader)
{
int x = 0;
foreach (DataColumn dcCurrent in dt.Columns)
dcCurrent.ColumnName = dt.Rows[0][x++].ToString();
dt.Rows.RemoveAt(0);
}
return dt;
}
Extension method:
public static XDocument fwToXDocument(this XmlDocument xmlDocument)
{
using (XmlNodeReader xmlNodeReader = new XmlNodeReader(xmlDocument))
{
xmlNodeReader.MoveToContent();
var doc = XDocument.Load(xmlNodeReader);
return doc;
}
}
Contrived example to illustrate: (Excel 2015)
Range in Excel, copied to clipboard
DataGridView on Winform, with data table as data source
The cell's xml will have an Index attribute if the previous cell was missing (had an empty value). You can update your code to check if the column index has changed before copying it to your data table row.
linqRows.ForEach(rowElement =>
{
intCol = 0;
currentRow = dt.Rows.Add();
rowElement.Descendants(ssNs + "Cell")
.ToList<XElement>()
.ForEach(cell =>
{
int cellIndex = 0;
XAttribute indexAttribute = cell.Attribute(ssNs + "Index");
if (indexAttribute != null)
{
Int32.TryParse(indexAttribute.Value, out cellIndex);
intCol = cellIndex - 1;
}
currentRow[intCol] = cell.Value;
intCol++;
});
});

User input to change column header text in DataGrid

I am creating a DataGrid by importing an excel file. I want users manually to be able to change column names from the application.
Edit: Workaround at the bottom
My desktop app will have below logic:
Load excel file and display table in DataGrid
Manually change Column names to match fixed text. (e.x. Column "PricesZZZ" renamed to "Prices", "LeadTimeXXX to "LeadTime")
Export DataGrid to new excel template with only relevant columns that are matched by fixed text (thus the need to have correct
names).
Excel file can have multiple columns and only several of those columns have relevant information and the only way to identify them is to match header name or some other way have user "tell" program which column holds which information.
I need to find a way to change Column name based on user input as I think it's most straightforward. I'm new to c# so sorry if my thinking is a little backwards.
Below is the code snippet I have so far. Might not be relevant for this specific problem, but may help visualize. I use EPPlus library
Import excel
private void btnOpenXL_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".xls";
dlg.Filter = "Excel Files|*.xlsx;*.xls;*.xlsm;*.csv";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name
if (result == true)
{
// Open document
string filename = dlg.FileName;
//call another class to draw the table
dataGrid.ItemsSource = GetDataTableFromExcel(filename).DefaultView;
MessageBox.Show("import done");
}
}
public static DataTable GetDataTableFromExcel(string path, bool hasHeader = true)
{
using (var pck = new OfficeOpenXml.ExcelPackage())
{
using (var stream = File.OpenRead(path))
{
pck.Load(stream);
}
var ws = pck.Workbook.Worksheets.First();
DataTable tbl = new DataTable();
foreach (var firstRowCell in ws.Cells[1, 1, 1, ws.Dimension.End.Column])
{
tbl.Columns.Add(hasHeader ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column));
}
var startRow = hasHeader ? 2 : 1;
for (int rowNum = startRow; rowNum <= ws.Dimension.End.Row; rowNum++)
{
var wsRow = ws.Cells[rowNum, 1, rowNum, ws.Dimension.End.Column];
DataRow row = tbl.Rows.Add();
foreach (var cell in wsRow)
{
row[cell.Start.Column - 1] = cell.Text;
}
}
return tbl;
}
}
Export excel
private void btnExportToXL_Click(object sender, RoutedEventArgs e)
{
DataTable dataTable = new DataTable();
dataTable = ((DataView)dataGrid.ItemsSource).ToTable();
ExportDataTableToExcel(dataTable);
MessageBox.Show("export done");
}
public void ExportDataTableToExcel(DataTable dataTable)
{
string path = "C:\\test";
var newFile = new FileInfo(path + "\\" +
DateTime.Now.Ticks + ".xlsx");
using (ExcelPackage pck = new ExcelPackage(newFile))
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
ws.Cells["A1"].LoadFromDataTable(dataTable, true);
pck.Save();
System.Diagnostics.Process.Start(newFile.ToString());
}
}
EDIT:
Workaround by double clicking on any cell in datagrid:
private void dataGrid_MouseDoubleClick(object sender, RoutedEventArgs e)
{
if (dataGrid.SelectedIndex == -1) //if column selected, cant use .CurrentColumn property
{
MessageBox.Show("Please double click on a row");
}
else
{
DataGridColumn columnHeader = dataGrid.CurrentColumn;
if (columnHeader != null)
{
string input = Interaction.InputBox("Title", "Prompt", "Default", 0, 0);
columnHeader.Header = input;
}
}
}
You can change the column names of the datagridview. But note, that this change is limited only to the grid and not it's data source. So in a nutshell, for simple representational purposes, you can use the following code:
dataGrid.Columns[i].HeaderText = "New Column Name"; //i is the index of the column
You can call this code form a Button click event of a Text change event of the input where the user provides the header name. Additionally, if you have the column names beforehand, you can replace then column headers with new values right after the data source has been bound to the grid. Change the headers after this line:
dataGrid.ItemsSource = GetDataTableFromExcel(filename).DefaultView;
//Set new column names here

EPPlus with a template is not working as expected

I am currently using EPPlus project in order to manipulate some .xlsx files. The basic idea is that I have to create a new file from a given template.
But when I create the new file from a template, all calculated columns in the tables are messed up.
The code I am using is the following:
static void Main(string[] args)
{
const string templatePath = "template_worksheet.xlsx"; // the path of the template
const string resultPath = "result.xlsx"; // the path of our result
using (var pck = new ExcelPackage(new FileInfo(resultPath), new FileInfo(templatePath))) // creating a package with the given template, and our result as the new stream
{
// note that I am not doing any work ...
pck.Save(); // savin our work
}
}
For example for a .xlsx file (that have a table with 3 columns, the last one is just the sum of the others) the program creates a .xlsx file where the last column have the same value (which is correct only for the first row) in all rows.
The following images shows the result:
Now the questions are:
What is going on here ? Is my code wrong ?
How can I accomplish this task without that unexpected behavior ?
That definitely on to something there. I was able to reproduce it myself. It has to do with the Table you created. if you open your file and remove it using the "Convert To Range" option in the Table Tools tab the problem goes away.
I looked at the source code and it extracts the xml files at the zip level and didnt see any indication that it was actually messing with them - seemed to be a straight copy.
Very strange because if we create and save the xlsx file including a table from EPPlus the problem is not there. This works just fine:
[TestMethod]
public void Template_Copy_Test()
{
//http://stackoverflow.com/questions/28722945/epplus-with-a-template-is-not-working-as-expected
const string templatePath = "c:\\temp\\testtemplate.xlsx"; // the path of the template
const string resultPath = "c:\\temp\\result.xlsx"; // the path of our result
//Throw in some data
var dtdata = new DataTable("tblData");
dtdata.Columns.Add(new DataColumn("Col1", typeof(string)));
dtdata.Columns.Add(new DataColumn("Col2", typeof(int)));
dtdata.Columns.Add(new DataColumn("Col3", typeof(int)));
for (var i = 0; i < 20; i++)
{
var row = dtdata.NewRow();
row["Col1"] = "String Data " + i;
row["Col2"] = i * 10;
row["Col3"] = i * 100;
dtdata.Rows.Add(row);
}
var templateFile = new FileInfo(templatePath);
if (templateFile.Exists)
templateFile.Delete();
using (var pck = new ExcelPackage(templateFile))
{
var ws = pck.Workbook.Worksheets.Add("Data");
ws.Cells["A1"].LoadFromDataTable(dtdata, true);
for (var i = 2; i <= dtdata.Rows.Count + 1; i++)
ws.Cells[i, 4].Formula = String.Format("{0}*{1}", ExcelCellBase.GetAddress(i, 2), ExcelCellBase.GetAddress(i, 3));
ws.Tables.Add(ws.Cells[1, 1, dtdata.Rows.Count + 1, 4], "TestTable");
pck.Save();
}
using (var pck = new ExcelPackage(new FileInfo(resultPath), templateFile)) // creating a package with the given template, and our result as the new stream
{
// note that I am not doing any work ...
pck.Save(); // savin our work
}
}
BUT.....
If we open testtemplate.xlsx, remove the table, save/close the file, reopen, and reinsert the exact same table the problem shows up when you run this:
[TestMethod]
public void Template_Copy_Test2()
{
//http://stackoverflow.com/questions/28722945/epplus-with-a-template-is-not-working-as-expected
const string templatePath = "c:\\temp\\testtemplate.xlsx"; // the path of the template
const string resultPath = "c:\\temp\\result.xlsx"; // the path of our result
var templateFile = new FileInfo(templatePath);
using (var pck = new ExcelPackage(new FileInfo(resultPath), templateFile)) // creating a package with the given template, and our result as the new stream
{
// note that I am not doing any work ...
pck.Save(); // savin our work
}
}
It has to be something burried in their zip copy methods but I nothing jumped out at me.
But at least you can see about working around it.
Ernie
Try to use the following code. This code takes the formatting and other rules and add them as xml node to another file. Ernie described it really well here Importing excel file with all the conditional formatting rules to epplus The best part of the solution is that you can also import formatting along with your other rules. It should take you close to what you need.
//File with your rules, can be your template
var existingFile = new FileInfo(#"c:\temp\temp.xlsx");
//Other file where you want the rules
var existingFile2 = new FileInfo(#"c:\temp\temp2.xlsx");
using (var package = new ExcelPackage(existingFile))
using (var package2 = new ExcelPackage(existingFile2))
{
//Make sure there are document element for the source
var worksheet = package.Workbook.Worksheets.First();
var xdoc = worksheet.WorksheetXml;
if (xdoc.DocumentElement == null)
return;
//Make sure there are document element for the destination
var worksheet2 = package2.Workbook.Worksheets.First();
var xdoc2 = worksheet2.WorksheetXml;
if (xdoc2.DocumentElement == null)
return;
//get the extension list node 'extLst' from the ws with the formatting
var extensionlistnode = xdoc
.DocumentElement
.GetElementsByTagName("extLst")[0];
//Create the import node and append it to the end of the xml document
var newnode = xdoc2.ImportNode(extensionlistnode, true);
xdoc2.LastChild.AppendChild(newnode);
package2.Save();
}
}
Try this
var package = new ExcelPackage(excelFile)
var excelSheet = package.Workbook.Worksheets[1];
for (var i = 1; i < 5; i++){
excelWorkSheet.InsertRow(i, 1, 1); // Use value of i or whatever is suitable for you
}
package.Workbook.Calculate();
Inserting new row copies previous row format and its formula if last prm is set to 1

Saving 2 copies of PDF template, 2nd file corrupt - iTextSharp

I have a PDF template file for 60 labels per page. My goal was to make copies of the template as needed, fill in the form data and then merge the files into a single PDF (or provide links to individual files...either works)
The problem is that the 2nd PDF copy comes out corrupt regardless of date.
The workflow is user selects a date. The lunch orders for that day are gathered into a generic list that in turn is used to fill in the form fields on the template. At 60, the file is saved as a temp file and a new copy of the template is used for the next 60 names, etc...
09/23/2013 through 09/25 have data. On the 25th there are only 38 orders, so this works as intended. On 09/24/2013 there are over 60 orders, the first page works, but the 2nd page is corrupt.
private List<string> CreateLabels(DateTime orderDate)
{
// create file name to save
string fName = ConvertDateToStringName(orderDate) + ".pdf"; // example 09242013.pdf
// to hold Temp File Names
List<string> tempFNames = new List<string>();
// Get path to template/save directory
string path = Server.MapPath("~/admin/labels/");
string pdfPath = path + "8195a.pdf"; // template file
// Get the students and their lunch orders
List<StudentLabel> labels = DalStudentLabel.GetStudentLabels(orderDate);
// Get number of template pages needed
decimal recCount = Convert.ToDecimal(labels.Count);
decimal pages = Decimal.Divide(recCount, 60);
int pagesNeeded = Convert.ToInt32(Math.Ceiling(pages));
// Make the temp names
for (int c = 0; c < pagesNeeded; c++)
{
tempFNames.Add(c.ToString() + fName); //just prepend a digit to the date string
}
//Create copies of the empty templates
foreach (string tName in tempFNames)
{
try
{ File.Delete(path + tName); }
catch { }
File.Copy(pdfPath, path + tName);
}
// we know we need X pages and there is 60 per page
int x = 0;
// foreach page needed
for (int pCount = 0; pCount < pagesNeeded; pCount++)
{
// Make a new page
PdfReader newReader = new PdfReader(pdfPath);
// pCount.ToString replicates temp names
using (FileStream stream = new FileStream(path + pCount.ToString() + fName, FileMode.Open))
{
PdfStamper stamper = new PdfStamper(newReader, stream);
var form = stamper.AcroFields;
var fieldKeys = form.Fields.Keys;
StudentLabel lbl = null;
string lblInfo = "";
// fill in acro fields with lunch data
foreach (string fieldKey in fieldKeys)
{
try
{
lbl = labels[x];
}
catch
{
break;
} // if we're out of labels, then we're done
lblInfo = lbl.StudentName + "\n";
lblInfo += lbl.Teacher + "\n";
lblInfo += lbl.MenuItem;
form.SetField(fieldKey, lblInfo);
x++;
if (x % 60 == 0) // reached 60, time for new page
{
break;
}
}
stamper.Writer.CloseStream = false;
stamper.FormFlattening = true;
stamper.Close();
newReader.Close();
stream.Flush();
stream.Close();
}
}
return tempFNames;
}
Why are you pre-allocating your files? My guess is that's your problem. You're binding a PdfStamper to a PdfReader for input and an exact copy of the same pdf to a FileStream object for output. The PdfStamper will generate your output file for you, you don't need to help it. You're trying to append new data to an existing file and I'm not quite sure what happens in that case (as I've never actually seen anyone do it.)
So drop your whole File.Copy pre-allocation and change your FileStream declaration to:
using (FileStream stream = new FileStream(path + pCount.ToString() + fName, FileMode.Create, FileAccess.Write, FileShare.None))
You'll obviously also need to adjust how your return array gets populated, too.

export data to excel file in an asp.net application

Can someone provide a link with a tutorial about exporting data to an excel file using c# in an asp.net web application.I searched the internet but I didn't find any tutorials that will explain how they do it.
You can use Interop http://www.c-sharpcorner.com/UploadFile/Globalking/datasettoexcel02272006232336PM/datasettoexcel.aspx
Or if you don't want to install Microsoft Office on a webserver
I recommend using CarlosAg.ExcelXmlWriter which can be found here: http://www.carlosag.net/tools/excelxmlwriter/
code sample for ExcelXmlWriter:
using CarlosAg.ExcelXmlWriter;
class TestApp {
static void Main(string[] args) {
Workbook book = new Workbook();
Worksheet sheet = book.Worksheets.Add("Sample");
WorksheetRow row = sheet.Table.Rows.Add();
row.Cells.Add("Hello World");
book.Save(#"c:\test.xls");
}
}
There is a easy way to use npoi.mapper with just below 2 lines
var mapper = new Mapper();
mapper.Save("test.xlsx", objects, "newSheet");
Pass List to below method, that will convert the list to buffer and then return buffer, a file will be downloaded.
List<T> resultList = New List<T>();
byte[] buffer = Write(resultList, true, "AttendenceSummary");
return File(buffer, "application/excel", reportTitle + ".xlsx");
public static byte[] Write<T>(IEnumerable<T> list, bool xlsxExtension = true, string sheetName = "ExportData")
{
if (list == null)
{
throw new ArgumentNullException("list");
}
XSSFWorkbook hssfworkbook = new XSSFWorkbook();
int Rowspersheet = 15000;
int TotalRows = list.Count();
int TotalSheets = TotalRows / Rowspersheet;
for (int i = 0; i <= TotalSheets; i++)
{
ISheet sheet1 = hssfworkbook.CreateSheet(sheetName + "_" + i);
IRow row = sheet1.CreateRow(0);
int index = 0;
foreach (PropertyInfo property in typeof(T).GetProperties())
{
ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
IFont cellFont = hssfworkbook.CreateFont();
cellFont.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
cellStyle.SetFont(cellFont);
ICell cell = row.CreateCell(index++);
cell.CellStyle = cellStyle;
cell.SetCellValue(property.Name);
}
int rowIndex = 1;
// int rowIndex2 = 1;
foreach (T obj in list.Skip(Rowspersheet * i).Take(Rowspersheet))
{
row = sheet1.CreateRow(rowIndex++);
index = 0;
foreach (PropertyInfo property in typeof(T).GetProperties())
{
ICell cell = row.CreateCell(index++);
cell.SetCellValue(Convert.ToString(property.GetValue(obj)));
}
}
}
MemoryStream file = new MemoryStream();
hssfworkbook.Write(file);
return file.ToArray();
}
You can try the following links :
http://www.codeproject.com/Articles/164582/8-Solutions-to-Export-Data-to-Excel-for-ASP-NET
Export data as Excel file from ASP.NET
http://codeissue.com/issues/i14e20993075634/how-to-export-gridview-control-data-to-excel-file-using-asp-net
I've written a C# class, which lets you write your DataSet, DataTable or List<> data directly into a Excel .xlsx file using the OpenXML libraries.
http://mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm
It's completely free to download, and very ASP.Net friendly.
Just pass my C# function the data to be written, the name of the file you want to create, and your page's "Response" variable, and it'll create the Excel file for you, and write it straight to the Page, ready for the user to Save/Open.
class Employee;
List<Employee> listOfEmployees = new List<Employee>();
// The following ASP.Net code gets run when I click on my "Export to Excel" button.
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
// It doesn't get much easier than this...
CreateExcelFile.CreateExcelDocument(listOfEmployees, "Employees.xlsx", Response);
}
(I work for a finanical company, and we'd be lost without this functionality in every one of our apps !!)

Categories

Resources