Thursday 4 February 2010

Export Excel sheet to PDF document using Aspose

Last month I stumbled upon a business issue, which would allow an application to extract a single worksheet out of an excel document and save it as a PDF document.

Using Aspose, this can be done easily!

public class XlsToPdf
    {
        public void ExportSheet()
        {

            ///lets say we have an xls document containing 6 sheets
            ///each strongly named like sheet1 => sheet6
            ///suppose that you need to save sheet5 as a pdf document.

            string sourceWorkBook = "source.xls";
            string destinationDocument = "Destination.pdf";

            Aspose.Cells.Workbook sourceWb = new Aspose.Cells.Workbook();
            sourceWb.Open(sourceWorkBook);

            foreach (Aspose.Cells.Worksheet workSheet in sourceWb.Worksheets)
            {
                if (!workSheet.Name.ToUpper().Contains("sheet5"))
                    workSheet.IsVisible = false;
            }


            ///First thing to do is to save the xls in xml format, 
            ///but the formattype used already refers to PDF
            string destinationDocumentXml = "destination.xml";
            sourceWb.Save(destinationDocumentXml, 
                Aspose.Cells.FileFormatType.AsposePdf);


            Aspose.Pdf.Pdf pdfDocument = new Aspose.Pdf.Pdf();
            //bind the created xml to the PDFDoc you intialized.
            pdfDocument.BindXML(destinationDocumentXml, null);
            //Save...
            pdfDocument.Save(destinationDocument);

            ///If necessary, you can cleanup and remove 
            ///the intermediate files created
            ///using DirectoryInfo and files delet techniques from the System.IO
            ///...code goes here
        }
    }
You can find the Aspose help here: Cells and PDF

Have fun