c# Excel转PDF

发布时间:2019-09-27编辑:admin阅读(2291)

/// <summary>
/// 将excel文档转换成PDF格式
/// </summary>
/// <param name="sourcePath">Excel文件路径</param>
/// <param name="targetPath">PDF文件路径</param>
/// <returns>转换结果</returns>
private bool Convert(string sourcePath, string targetPath)
{
    bool result=false;
    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;
        Microsoft.Office.Interop.Excel.XlFixedFormatType type = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF;
        workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
                missing, missing, missing, missing, missing, missing, missing, missing, missing);
        Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets["工作簿名称或索引"];
        worksheet.ExportAsFixedFormat(type, target, Microsoft.Office.Interop.Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);//将Excel中某个工作簿另存为PDF文件
       
        //workBook.ExportAsFixedFormat(type, target, Microsoft.Office.Interop.Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);//将整个Excel另存为PDF文件
        result = true;
    }
    catch (Exception ex)
    {
                
        result = false;
    }
    finally
    {
                
        if (workBook != null)
        {
            workBook.Close(false, missing, missing);
            workBook = null;
        }
                
        if (application != null)
        {
            application.Quit();
            application = null;
        }
        GC.Collect();
                
        GC.WaitForPendingFinalizers();
    }
            
    return result;
}


  关键字:c#Excel转PDF


鼓掌

0

正能量

0

0

呵呵

0


评论区
  • 游客

    大佬运行的时候提示未保存什么情况?

    worksheet.ExportAsFixedFormat(type, target, Microsoft.Office.Interop.Excel.XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);//将Excel中某个工作簿

    指向这一步

    • 管理员

      我试的时候没问题,我用的是office2016,具体原因要网上查一下。