Export large data to excel into multiple sheets using C# - excel

I need to export datatable of 6'00'000+ records into excel. I tried with the code as below, but I am getting the OutOfMemory exception. Now I thought to export all these records into multiple sheets instead of single sheet to overcome with this error.
Here is the my code to export data into excel.
private void ExportDataToExcel(DataTable Tbl)
{
Response.Clear();
Response.ClearContent();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=PeriodicJobEvents.xls");
GridView excel = new GridView();
excel.DataSource = Tbl;
excel.DataBind();
excel.RenderControl(new HtmlTextWriter(Response.Output));
Response.Flush();
Response.End();
}
Kindly help me understand how to export 6'00'000+ records into multiple sheets.

Related

Create excel file through Microsoft Graph API

Does anyone know how to create excel and ppt files through the MS Graph API? We're trying to leverage the MS Graph API to create word/excel/ppt files on a button click and while we found how to create word files, the excel and powerpoint files created are corrupted even with a success response from the api. The end point below works for the word files. We've been just working with the graph api explorer (https://developer.microsoft.com/en-us/graph/graph-explorer#) for now. Any help would be appreciated!
POST https://graph.microsoft.com/v1.0/drives/{Drive ID}/root/children/
Request Body:
{
"name": "FileTest6.docx",
"file":{
}
}
PowerPoint files
PowerPoint files could be created via DriveItem upload endpoint, for example:
PUT https://graph.microsoft.com/v1.0/me/drive/root:/sample.pptx:/content
or
POST https://graph.microsoft.com/v1.0/me/drive/root/children
{
"name": "Sample.pptx",
"file":{ }
}
Excel files
With excel files the situation is a bit different since the content of the excel file to be uploaded needs to be provided explicitly.
For ASP.NET Core application the following solution could be considered:
create empty Excel document via Open XML SDK (see CreateWorkbook example below)
upload it via DriveItem upload endpoint
C# example
using (var stream = new MemoryStream())
{
CreateWorkbook(stream);
stream.Seek(0, SeekOrigin.Begin);
var driveItem = await graphClient.Me
.Drive
.Root
.ItemWithPath("SampleWorkbook1.xlsx")
.Content
.Request()
.PutAsync<DriveItem>(stream);
}
where
public static void CreateWorkbook(Stream stream)
{
// By default, AutoSave = true, Editable = true, and Type = xlsx.
var spreadsheetDocument =
SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook);
// Add a WorkbookPart to the document.
var workbookpart = spreadsheetDocument.AddWorkbookPart();
workbookpart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
// Add a WorksheetPart to the WorkbookPart.
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet(new SheetData());
// Add Sheets to the Workbook.
var sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
// Append a new worksheet and associate it with the workbook.
var sheet = new Sheet()
{Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet"};
sheets.Append(sheet);
workbookpart.Workbook.Save();
// Close the document.
spreadsheetDocument.Close();
}

Export WebGrid data to Excel in MVC4

I want to export WebGrid data to excel with formatting.
I have written below code which export WebGrid data to Excel.
WebGrid grid = new WebGrid(source: listReport, canPage: false, canSort: false);
string gridData = grid.GetHtml(
columns: grid.Columns(
grid.Column("ID", "ID"),
grid.Column("Name", "Name"),
grid.Column("Summary", "Summary"),
grid.Column("Detail", "Detail"),
grid.Column("ProjectName", "Project Name")
)
).ToString();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=CustomerInfo.xls");
Response.ContentType = "application/excel";
Response.Write(gridData);
Response.End();
I want to do formatting in excel.
Is it possible to export data with formatting?
Also it gives me below error when i open the generated excel
You haven't actually created an Excel file. You've created an HTML file masquerading as an Excel 2003 file, which is a bad idea. I explain why and cover some alternatives on my blog.
Styling will be difficult, because of the way you're creating the source HTML. You could parse it with a library, then add basic styling via each elements style attribute. Or instead of using WebGrid you can manually build your HTML.
string html = "<table style='color:red'><tr><td>Hello, world!</td></tr></table>";
But really, the best thing to do is generate real Excel files. Here's a quick excerpt from my blog using EPPlus. It's shown in Web Forms. In MVC you'd actually want to return a FileResult rather than writing directly to the response.
protected void ExportBtn_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=myexcelfile.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var package = new ExcelPackage(); //create a new package, this is the equivalent of an XLSX file.
var sheet = package.Workbook.Worksheets.Add("My Data"); //Add a new sheet to the workbook
var dt = GetDataTable(); //This retrieves a System.Data.DataTable, you'd likely get it from your database.
sheet.Cells["A1"].LoadFromDataTable(dt, true); //EPPlus contains helper function to load data from a DataTable, though you could manually fill in rows/column values yourself if you want
var range = sheet.Cells[1, 1, dt.Rows.Count + 1, 2]; //We're getting a reference to all the cells that contain data
var table = sheet.Tables.Add(range, "My Data Table"); //Creating an Excel table
table.TableStyle = TableStyles.Medium8; //Setting the table style to something that looks nice
range.AutoFitColumns(); //Auto fitting the column widths.
Response.BinaryWrite(package.GetAsByteArray());
Response.End();
}

Read Excel 2007 Workbook Custom Properties without opening or running macros

I'm writing a program (in C#) that will be able to replace a local workbook from a server if the server version is higher, and then open it. To this end I'm trying to read Custom Property "Revision Number" of both local and server copies. The issue is that the workbook contains macros that launch on open, and I don't want to run any macros just to check the Revision Code. So is there a way to read the Revision Number of an excel 2007 xlsm file without actually opening it? If not, is there a way to open a workbook in C# and not execute it's macros?
Actually I tried the tkacprow's suggestion to use OpenXML and it worked. It just took me a while to produce a working code and I just got it working yesterday. Fratyx, your tip also looks interesting - i'll keep that in mind. Here's a working code:
public string GetVersion(string fileName)
{
string propertyValue = string.Empty;
try
{
using (var wb = SpreadsheetDocument.Open(fileName, false))
{
const string corePropertiesSchema = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
const string dcPropertiesSchema = "http://purl.org/dc/elements/1.1/";
const string dcTermsPropertiesSchema = "http://purl.org/dc/terms/";
// Get the core properties part (core.xml).
CoreFilePropertiesPart xCoreFilePropertiesPart;
xCoreFilePropertiesPart = wb.CoreFilePropertiesPart;
// Manage namespaces to perform XML XPath queries.
NameTable nt = new NameTable();
XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
nsManager.AddNamespace("cp", corePropertiesSchema);
nsManager.AddNamespace("dc", dcPropertiesSchema);
nsManager.AddNamespace("dcterms", dcTermsPropertiesSchema);
// Get the properties from the package.
XmlDocument xdoc = new XmlDocument(nt);
// Load the XML in the part into an XmlDocument instance.
xdoc.Load(xCoreFilePropertiesPart.GetStream());
string searchString = string.Format("//cp:coreProperties/{0}", "cp:version");
XmlNode xNode = xdoc.SelectSingleNode(searchString, nsManager);
if (!(xNode == null))
{
//Console.WriteLine(" version is " + xNode.InnerText);
propertyValue = xNode.InnerText;
}
}
}
catch (OpenXmlPackageException e)
{
throw new ApplicationException(String.Format("Incorrect Format detected in a file: {0}" , fileName),e.GetBaseException());
}
return propertyValue;
}

Exception when open excel: File contains corrupted data

I am trying to read an excel with OpenXML.
What I did is simply as following:
private WorkbookPart wbPart = null;
private SpreadsheetDocument document = null;
public byte[] GetExcelReport()
{
byte[] original = File.ReadAllBytes(this.originalFilename);
using (MemoryStream stream = new MemoryStream())
{
stream.Write(original, 0, original.Length);
using (SpreadsheetDocument excel = SpreadsheetDocument.Open(stream, true))
{
this.document = excel;
this.wbPart = document.WorkbookPart;
UpdateValue();
}
stream.Seek(0, SeekOrigin.Begin);
byte[] data = stream.ToArray();
return data;
}
}
I initialized this.originalFilename in the constructor. It is the filename ended with '.xlsx' which i created with excel 2010.
But this line of code
using (SpreadsheetDocument excel = SpreadsheetDocument.Open(stream, true))
gives the exception: Message: System.IO.FileFormatException: File contains corrupted data.
The StackTrace:
Does anyone know how to solve this problem? At the beginning, I didn't use the Stream, I just use SpreadsheetDocument.Open(filename, true). However, it turns out to be exactly the same exception.
I've tried to create a new .xlsx file, but it's still the same.
There is a MSDN page which describes the process of reading and writing Excel file using stream and open xml SDK.
http://msdn.microsoft.com/en-us/library/office/ff478410.aspx
Try extracting the document contents through zip application and check whether you are getting the standard folders inside like xl,docProps and _rels etc.,
This is a method to find whether the package is properly packaged as archive or not.
Hope this helps.

How do I save an Excel workbook to disk?

I am dynamically creating a Excel File that is displayed to the users upon creation, however I now need to also save the file onto the server.
How would I save it to a specific folder?
I have the following code
public void ExportMembers()
{
Microsoft.Office.Interop.Excel.Application xla = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = xla.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)xla.ActiveSheet;
ws.Cells[1, 1] = "Site Id";
//I create the rest of the cells here
xla.Visible = true; //this displays the excel spreadsheet to the user
//client id code is here
if (!System.IO.Directory.Exists("/Files/" + clientId + "/Excel"))
{ //if doesn't exist make folder
System.IO.Directory.CreateDirectory("/Files/" + clientId);
System.IO.Directory.CreateDirectory("/Files/" + clientId + "/Excel");
}
//save the xla as a file Here
}
How do I save the spreadsheet on the server?
Any help is appreciated.
Thanks
see the Save method for Microsoft.Office.Interop.Excel.Application
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel._application.save

Resources