因项目需要PDF测试报告,一直以来都是WORD转PDF,网上搜索类似资料也没找到好的方法。于是百度了一波C#的excel转PDF,一大堆信息啊,因为使用的LabWindows/cvi 9.0比较老的版本没法使用vs生成的lib库。没办法只能使用直接调用exe模式了。
先贴上网上看来的一个接口,这个谁是原创也不知道,我一搜索一堆。
using Microsoft.Office.Interop.Excel;
public static 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;
}
那么如何与cvi进行数据交互呢?我这边采用的是ini文件,将需要转换的源文件、目标文件信息填入ini文件。然后
static void Main(string[] args)
{
string excelfilePath = ReadIni(@"c:\\file_important\\inicfg.ini", "INFO_R", "epath", "DefaultName");
string pdffilePath = ReadIni(@"c:\\file_important\\inicfg.ini", "INFO_R", "ppath", "DefaultName");
// bool result = Program.Convert("C:\\report.xls", "C:\\测试报告", XlFixedFormatType.xlTypePDF);
bool result = Program.Convert(excelfilePath, pdffilePath, XlFixedFormatType.xlTypePDF);
//如果转换成功
if (result)
{
}
}
生成的exe在cvi中使用system(“”*.exe“”);即可