2012-08-11 50 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的参数可用的,但它在对话框中自动选中,也可能在调用时也是默认值。

相关问题