0

我有一个 Excel 文件。

我需要打开它,从中选择特定的工作表,然后将这些工作表转换为 PDF 格式。我能够转换整个 excel 文件,我只是不知道如何只转换特定的工作表。

我的想法是将特定工作表从现有文件复制到新的临时文件,然后将整个新的临时文件转换为 PDF。

也许有更简单的方法?

到目前为止我的代码是 =>

using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;

    public static void ExportExcel(string infile, string outfile, int[] worksheets)
    {
        Excel.Application excelApp = null;
        Excel.Application newExcelApp = null;
        try
        {
            excelApp = new Excel.Application();
            excelApp.Workbooks.Open(infile);
            //((Microsoft.Office.Interop.Excel._Worksheet)excelApp.ActiveSheet).PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape;  

            excelApp.ActiveWorkbook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, outfile);
        }
        finally
        {
            if (excelApp != null)
            {
                excelApp.DisplayAlerts = false;
                excelApp.SaveWorkspace();
                excelApp.Quit();
            }
         }
    }

也许该ExportAsFixedFormat方法可以设置为在转换时仅考虑特定页面(工作表)?

如果没有,我如何将工作表从一个文件复制到另一个文件?

谢谢!

4

2 回答 2

0

您可以简单地将文件复制到新目标,打开目标,删除不需要的工作表并导出。这是我的想法的一个例子(经过测试)。

// infile is the excel file, outfile is the pdf to build, sheetToExport is the name of the sheet
public static void ExportExcel(string infile, string outfile, string sheetToExport) 
{ 
    Microsoft.Office.Interop.Excel.Application excelApp = new     
                        Microsoft.Office.Interop.Excel.Application();
    try  
    {  
        string tempFile = Path.ChangeExtension(outfile, "XLS"); 
        File.Copy(infile, tempFile, true); 
        Microsoft.Office.Interop.Excel._Workbook excelWorkbook = 
                                excelApp.Workbooks.Open(tempFile);  

        for(int x = excelApp.Sheets.Count; x > 0; x--) 
        { 
            _Worksheet sheet = (_Worksheet)excelApp.Sheets[x];
            if(sheet != null && sheet.Name != sheetToExport) 
                sheet.Delete(); 
        }  
        excelApp.ActiveWorkbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, outfile);  
    }  
    finally  
    {  
        if (excelApp != null)  
        {  
             excelApp.DisplayAlerts = false;  
             excelApp.SaveWorkspace();  
             excelApp.Quit();  
         }  
     }      
 } 
于 2012-08-11T10:30:01.793 回答
0

您也许可以从原始文件中打印您想要的工作表。我启动了宏记录器,选择了几张纸,然后另存为 PDF。这是代码:

Sheets(Array("Sheet1", "Sheet2")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
    "C:\Users\doug\Documents\Book1.pdf", Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True

当我更改选定的工作表并再次运行时,它按预期工作。

奇怪的是,在实际的“另存为”对话框中,您可以转到“选项”并选中“选定的工作表”。这不能作为 ExportAsFixedFormat 的参数,但它是在对话框中自动选择的,并且在调用时也可能是默认值。

于 2012-08-11T15:57:23.080 回答