private void TransformToPDFButton_Click(object sender, EventArgs e)
 {
     try
     {
         Microsoft.Office.Interop.Excel.Application xlApp       = new Microsoft.Office.Interop.Excel.Application();
         Microsoft.Office.Interop.Excel.Workbook    xlWorkbook  = xlApp.Workbooks.Open(UbicationTextBox.Text);
         Microsoft.Office.Interop.Excel._Worksheet  xlWorksheet = xlWorkbook.Sheets[1];
         Microsoft.Office.Interop.Excel.Range       xlRange     = xlWorksheet.UsedRange;
         xlApp.DisplayAlerts = false;
         xlWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, filePath);
         xlWorkbook.Close();
         GetExcelProcess(xlApp).Kill();
         xlApp.Quit();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Ejemplo n.º 2
0
        /// <summary>
        /// XLS 2 PDF
        /// </summary>
        /// <param name="sourcePath">源路径</param>
        /// <param name="targetPath">目标路径</param>
        /// <returns></returns>
        public bool XLSToPDF(string sourcePath, string targetPath)
        {
            bool result = false;

            Microsoft.Office.Interop.Excel.XlFixedFormatType targetType = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF;
            object missing = Type.Missing;

            Microsoft.Office.Interop.Excel.ApplicationClass application = null;
            Microsoft.Office.Interop.Excel.Workbook         workBook    = null;
            try
            {
                application = new Microsoft.Office.Interop.Excel.ApplicationClass();
                object target = targetPath;
                object type   = targetType;
                workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
                                                      missing, missing, missing, missing, missing, missing, missing, missing, missing);

                workBook.ExportAsFixedFormat(targetType, target, Microsoft.Office.Interop.Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (workBook != null)
                {
                    workBook.Close(true, missing, missing);
                    workBook = null;
                }
                if (application != null)
                {
                    application.Quit();
                    application = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return(result);
        }