using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using GridToExcel.Data;
using GridToExcel.Helper;
using System.IO;
namespace AMC_Main.Reports
{
public partial class GridXml : System.Web.UI.Page
{
DataGrid grdvTest = new DataGrid();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnExport_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
AMC.Business.StudioMain objStudio = new StudioMain();
DataTable dtsearch = new DataTable();
dtsearch = objStudio.SearchStudioTemp();
if (dtsearch.Rows.Count > 0)
{
grdvTest.DataSource = dtsearch;
ViewState["file"] = dtsearch;
grdvTest.DataBind();
}
string file = new ExcelHelper().ExportToExcel(dtsearch);
string rootPath = HttpContext.Current.Server.MapPath("~").ToString();
string localCopy = Guid.NewGuid().ToString() + ".xlsx";
File.Copy(file, rootPath + localCopy);
Response.Redirect(localCopy);
}
}
}
In ExcelHelper.cs class
internal string ExportToExcel(DataTable table)
{
string excelfile = Path.GetTempPath() + Guid.NewGuid().ToString() + ".xlsx";
using (SpreadsheetDocument excelDoc = SpreadsheetDocument.Create(excelfile, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
CreateExcelParts(excelDoc, table);
}
return excelfile;
}
private void CreateExcelParts(SpreadsheetDocument spreadsheetDoc, DataTable data)
{
WorkbookPart workbookPart = spreadsheetDoc.AddWorkbookPart();
CreateWorkbookPart(workbookPart);
int workBookPartCount = 1;
WorkbookStylesPart workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>("rId" + (workBookPartCount++).ToString());
CreateWorkbookStylesPart(workbookStylesPart);
WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>("rId" + (101).ToString());
CreateWorksheetPart(workbookPart.WorksheetParts.ElementAt(0), data);
SharedStringTablePart sharedStringTablePart = workbookPart.AddNewPart<SharedStringTablePart>("rId" + (workBookPartCount++).ToString());
CreateSharedStringTablePart(sharedStringTablePart, data);
workbookPart.Workbook.Save();
}