Wiki

Clone wiki

Aspose for OpenXML / Exporting Data to Excel

Exporting Data to Excel

using OpenXML SDK

First of all you will need DocumentFormat.OpenXml.dll which you can get by installing openXML SDK. You can copy DLL to your bin folder and add DLL reference in your project. Namespaces which you will be required to include are:

#!c#

using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
You can have control over the template by using a template file at runtime.

#!c#

File.Copy(SourcetemplateFilePath, DestinationFilePath, true);
Once you have created template excel file save it in your project folder. Then we can start by creating a function that will accept two parameters, 1. DataTable 2. DestinationFileName and create desired excel output.

#!c#

public void generateExcel(DataTable YoutdTName, string YourExcelfileName)
        {
            // Create cell reference array 
            string[] CellReferenceArray = new string[] { "A", "B", "C", "D", "E" };
            //Open your saved excel file that you have created using template file.
            using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open(YourExcelfileName, true))
            {
                // Create reference of main Workbook part, which contains all reference.
                WorkbookPart objworkbook = myDoc.WorkbookPart;

                // Create style sheet object that will be used for applying styling.
                Stylesheet objstyleSheet = objworkbook.WorkbookStylesPart.Stylesheet;

                // pick up first worksheet
                WorksheetPart objworksheet = objworkbook.WorksheetParts.First();

                // will be used in end while creating sheet data
                string objorigninalSheetId = objworkbook.GetIdOfPart(objworksheet);
                WorksheetPart objreplacementPart = objworkbook.AddNewPart<WorksheetPart>();
                string objreplacementPartId = objworkbook.GetIdOfPart(objreplacementPart);

                // Create object reader to read from excel file.
                OpenXmlReader objreader = OpenXmlReader.Create(objworksheet);

                // create writer object to write in excel sheet.
                OpenXmlWriter objOpenXmwriter = OpenXmlWriter.Create(objreplacementPart);

                int i = 1;
                Row r = new Row();
                Cell c = new Cell();
                Columns col1 = new Columns();
                UInt32 index;

                while (objreader.Read())
                {
                    if (objreader.ElementType == typeof(SheetData))
                    {
                        if (objreader.IsEndElement)
                            continue;

                        objOpenXmwriter.WriteStartElement(new SheetData());
                        objOpenXmwriter.WriteStartElement(r);

                        // Loop to insert header
                        foreach (DataColumn colHead in YoutdTName.Columns)
                        {
                            c = new Cell
                            {
                                DataType = CellValues.String,
                                CellReference = CellReferenceArray[i] + Convert.ToString(index)
                            };
                            CellValue v1 = new CellValue(colHead.ColumnName.ToString());                         
                            c.Append(v1);
                            objOpenXmwriter.WriteElement(c);
                            i += 1;
                        }
                        objOpenXmwriter.WriteEndElement();
                        index += 1;

                        //Loop to insert datatable row in excel    
                        foreach (DataRow dr in YoutdTName.Rows)
                        {
                            objOpenXmwriter.WriteStartElement(r);
                            i = 1;
                            foreach (DataColumn col in YoutdTName.Columns)
                            {
                                c = new Cell
                                {
                                    DataType = CellValues.String,
                                    CellReference = CellReferenceArray[i] + Convert.ToString(index)
                                };
                                CellValue v1 = new CellValue(dr[col].ToString());
                                c.AppendChild(v1);
                                objOpenXmwriter.WriteElement(c);
                                i += 1;
                            }
                            objOpenXmwriter.WriteEndElement();
                            index += 1;
                        }
                        objOpenXmwriter.WriteEndElement();
                    }
                }
                //close all objects
                objreader.Close();
                objOpenXmwriter.Close();

                Sheet sheet = objworkbook.Workbook.Descendants<Sheet>().Where(s => s.Id.Value.Equals(objorigninalSheetId)).First();
                sheet.Id.Value = objreplacementPartId;
                objworkbook.DeletePart(objworksheet);

            }
            //download created excel sheet.
            Response.AddHeader("Content-Disposition", "inline;filename=YourExcelfileName.xlxs");
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.WriteFile("YourExcelfileName.xlxs");
            Response.End();
        }
Above code will create simple excel sheet from Datatable in .xlsx format.

using Aspose SDK

#!c#

string projectFiles = Path.GetFullPath("../../Files/");

            //Instantiating a Workbook object
            Workbook workbook = new Workbook();

            //Adding a new worksheet to the Workbook object
            int i = workbook.Worksheets.Add();

            //Obtaining the reference of the newly added worksheet by passing its sheet index
            Worksheet worksheet = workbook.Worksheets[i];

            //Creating an array containing names as string values
            string[] names = new string[] { "laurence chen", "roman korchagin", "kyle huang" };

            //Importing the array of names to 1st row and first column vertically
            worksheet.Cells.ImportArray(names, 0, 0, true);

            //Save FIle
            workbook.Save(projectFiles + "Output.xlsx");
Source: https://bitbucket.org/asposemarketplace/aspose-for-openxml/src/ffec3cde9d87/Aspose.Cells/ImportDataInWorksheet/?at=master

Updated