使用 JavaScript 将 Excel 转换为 PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15673628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Excel to PDF using JavaScript
提问by neverfox
How can I convert Excel documents (files) to PDF in an automated fashion? I am trying to adapt the solution found hereto Excel. So far I have this:
如何以自动方式将 Excel 文档(文件)转换为 PDF?我正在尝试将此处找到的解决方案应用于 Excel。到目前为止,我有这个:
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();
}
}
I get this output:
我得到这个输出:
Saving 'somefile.xlsx' as 'somefile.pdf'...
Done.
..\SaveXLSXAsPDF.js(27, 9) (null): The object invoked has disconnected from its clients.
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?
已创建 PDF 文件,但该文件无效且无法在阅读器中打开。我在想也许格式 17 不适合 Excel。有谁知道正确的数字或如何使其工作?
Edit: I found mention of the correct number here(57) but now I get this error:
编辑:我发现这里提到了正确的数字(57) 但现在我收到了这个错误:
r:\Web\Roman\SaveXLSXAsPDF.js(27, 13) Microsoft JScript runtime error: Class doesn't support Automation
回答by Kazimierz Jawor
Try to use .ExportAsFixedFormat
property instead of .SaveAs
. First one is suitable for creating PDF files in Excel but not SaveAs which doesn't support PDF format.
尝试使用.ExportAsFixedFormat
property 而不是.SaveAs
. 第一个适用于在 Excel 中创建 PDF 文件,但不适用于不支持 PDF 格式的 SaveAs。
I guess you would need something like this:
我想你会需要这样的东西:
objExcel.ExportAsFixedFormat(0, pdfPath)
回答by ernie
You're clobbering objExcel on line 15:
你在第 15 行破坏了 objExcel:
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();