2012-08-11 115 views
0

我有一個Excel文件。將特定的工作表複製到新的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方法可以被設置爲考慮而僅轉換特定頁面(張)?

如果不是,我該如何將表單從一個文件複製到另一個文件?

謝謝!

回答

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(); 
     } 
    }  
} 
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的參數可用的,但它在對話框中自動選中,也可能在調用時也是默認值。

相關問題