导出Excel到PDF排除隐藏标签

时间:2017-07-31 15:19:03

标签: c# excel pdf

我正在尝试将Excel文件导出为PDF。我使用Microsoft.Office.Interop命名空间取得了成功。我现在正在尝试找出如何排除标记为隐藏的标签,以便它们不在PDF>范围内。任何人都这样做或知道如何做到这一点?我的代码如下所示,我目前正在使用。

 string inFile = @"C:\Users\casey.pharr\Desktop\testPDF\3364850336.xls";
        string outFile = @"C:\Users\casey.pharr\Desktop\testPDF\3364850336_noHidden_out.pdf";
        string tempFile = @"C:\Users\casey.pharr\Desktop\testPDF\temp.xls";

        try
        {
            //first copy original file to temp file to work with
            File.Copy(inFile,tempFile, true);

            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            app.Visible = false;
            app.DisplayAlerts = false;
            Microsoft.Office.Interop.Excel.Workbook wkb = app.Workbooks.Open(tempFile);

            for(int x = app.Sheets.Count-1; x-1 > 1; x--) 
            { 
                Excel._Worksheet sheet = (Excel._Worksheet)app.Sheets[x];
                //now delete hidden worksheets from work book. This is why we are using tempFile
                if (sheet.Visible == Microsoft.Office.Interop.Excel.XlSheetVisibility.xlSheetHidden || sheet.Visible ==  Microsoft.Office.Interop.Excel.XlSheetVisibility.xlSheetVeryHidden && sheet != null)
                {
                    //is sheet hidden. If so remove it so not part of converted file                        
                    sheet.Delete();
                }
            }



            wkb.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outFile);

            wkb.Close(false);
            app.Quit();

            //return outputLocation;

调用.Delete()时发生的错误如下:

Exception from HRESULT: 0x800A03EC
enter code here

因此,我们可以转换pdf,但不能删除或排除隐藏的工作表。我走了路线试图删除它们然后转换整个文件,但没有工作。

0 个答案:

没有答案