使用JavaScript将Excel转换为PDF [英] Convert Excel to PDF using JavaScript

查看:1938
本文介绍了使用JavaScript将Excel转换为PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将Excel文档(文件)以自动方式转换为PDF? 我正在尝试将在此处找到的解决方案调整为Excel.到目前为止,我有这个:

How can I convert Excel documents (files) to PDF in an automated fashion? I am trying to adapt the solution found here to Excel. So far I have this:

var fso = new ActiveXObject("Scripting.FileSystemObject");
var docPath = WScript.Arguments(0);
docPath = fso.GetAbsolutePathName(docPath);

var pdfPath = docPath.replace(/\.xls[^.]*$/, ".pdf");
var objExcel = null;

try
{
    WScript.Echo("Saving '" + docPath + "' as '" + pdfPath + "'...");

    objExcel = new ActiveXObject("Excel.Application");
    objExcel.Visible = false;

    var objExcel = objExcel.Workbooks.Open(docPath);

    var wdFormatPdf = 17;
    objExcel.SaveAs(pdfPath, wdFormatPdf);
    objExcel.Close();

    WScript.Echo("Done.");
}
finally
{
    if (objExcel != null)
    {
        objExcel.Quit();
    }
}

我得到以下输出:

Saving 'somefile.xlsx' as 'somefile.pdf'...
Done.
..\SaveXLSXAsPDF.js(27, 9) (null): The object invoked has disconnected from its clients.

已创建PDF文件,但该文件无效,无法在阅读器中打开.我认为格式17不适用于Excel.有谁知道正确的电话号码或如何使它正常工作?

A PDF file is created but it is invalid and won't open in a reader. I'm thinking that perhaps format 17 isn't the right one for Excel. Does anyone know the right number or how to get this working?

我发现提到了正确的号码

I found mention of the correct number here (57) but now I get this error:

r:\Web\Roman\SaveXLSXAsPDF.js(27, 13) Microsoft JScript runtime error: Class doesn't support Automation

推荐答案

您正在破坏第15行的objExcel:

You're clobbering objExcel on line 15:

var objExcel = objExcel.Workbooks.Open(docPath);

这些代码行需要使用其他变量,例如:

Those lines of code need to use a different variable, e.g.:

var objWorkbook = objExcel.Workbooks.Open(docPath);

var wdFormatPdf = 57;
objWorkbook.SaveAs(pdfPath, wdFormatPdf);
objWorkbook.Close();

这篇关于使用JavaScript将Excel转换为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆