C#Excle轉換pdf格式
一:excle轉換pdf
首先引入using Microsoft.Office.Interop.Excel,如果沒有引用裡沒有,需要從VS裡的NuGet程式包裡進行下載
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SwitchType
{
public class SwitchPDFType
{
/// <summary>
/// 將excel文件轉換成PDF格式
/// </summary>
/// <param name="sourcePath">原檔案路徑</param>
/// <param name="targetPath">檔案轉換為PDF儲存的路徑</param>
/// <param name="targetType">列舉型別引數</param>
/// <returns></returns>
public bool Convert(string sourcePath, string targetPath, XlFixedFormatType targetType)
{
bool result;
object missing = Type.Missing;
Microsoft.Office.Interop.Excel.Application application = null;
Workbook workBook = null;
try
{
application = new Microsoft.Office.Interop.Excel.Application();
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, 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;
}
}
}
呼叫Excle轉換PDF方法:
Microsoft.Office.Interop.Excel.XlFixedFormatType targetType = (Microsoft.Office.Interop.Excel.XlFixedFormatType)excle;
bool result = switchPDF.Convert(sourcePath, targetPath, targetType);
//如果轉換成功
if (result)
{
///if語句裡面寫自己想做的業務
}