导航

Microsoft.Office.Interop.Excel,将xlsx换为pdf

Posted on 2024-01-08 15:46  WinChance  阅读(101)  评论(0编辑  收藏  举报

利用Microsoft.Office.Interop.Excel,将xlsx换为pdf(保留源格式)

public void ConvertExcelToPdf2(string inputFilePath, string outputFilePath)
{
    Application excelApp = new Application();
    Workbook workbook = excelApp.Workbooks.Open(inputFilePath);

    try
    {
        foreach (Worksheet worksheet in workbook.Worksheets)
        {
            worksheet.PageSetup.Orientation = XlPageOrientation.xlLandscape;
            worksheet.PageSetup.Zoom = false;
            worksheet.PageSetup.FitToPagesWide = 1;
            worksheet.PageSetup.FitToPagesTall = false;
        }

        workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, outputFilePath);
    }
    finally
    {
        workbook.Close(false);
        excelApp.Quit();

        ReleaseCOMObject(workbook);
        ReleaseCOMObject(excelApp);
    }
}

private void ReleaseCOMObject(object obj)
{
    try
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        obj = null;
    }
    catch (Exception ex)
    {
        obj = null;
        Console.WriteLine("Exception occurred while releasing COM object: " + ex.ToString());
    }
    finally
    {
        GC.Collect();
    }
}