以编程方式在Excel中设置页面设​​置选项

时间:2009-03-09 10:49:16

标签: c# asp.net

我有一个ASP.NET Web App,它通过创建HTML表并复制内容将报表复制到Excel表。  我想在激活打印选项之前将excel报告放入1页。当我生成Excel工作簿时,这需要以编程方式完成。 请尽快提供解决方案。

1 个答案:

答案 0 :(得分:4)

以下是我用来打开Excel工作簿并使用自定义打印机设置打印的代码:

Dim xl As New Excel.Application
    xl.DisplayAlerts = False
    xl.Workbooks.Open("<FilePath>", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, _
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)
    Dim sheet As Excel.Worksheet

    Dim ws
    Try
        For Each ws In xl.ActiveWorkbook.Worksheets
            ws.Select(Type.Missing)
            With ws.PageSetup
                .PaperSize = Excel.XlPaperSize.xlPaperA4
                .Orientation = Excel.XlPageOrientation.xlLandscape
                .Zoom = 80
                .BottomMargin = 0.25
                .LeftMargin = 0.25
                .RightMargin = 0.25
                .TopMargin = 0.25
                .FitToPagesWide = 1
            End With
            ws.PrintOut(Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)
        Next

    Catch exp As Exception
        MsgBox("Unable to setup printing properties for the sheet." & Chr(13) & "Check if you have printer installed on your machine.", MsgBoxStyle.OKOnly)

    Finally
        xl.Workbooks.Close()
        xl.Quit()
        While (System.Runtime.InteropServices.Marshal.ReleaseComObject(xl) > 0)
            ''do nothing
        End While
        xl = Nothing
    End Try