在VB.NET中如何用格式化或模板写入Excel文件

mzsu5hc0  于 2023-02-25  发布在  .NET
关注(0)|答案(1)|浏览(227)

我想使用一个模板来格式化在vb.net中创建的输出excel文件。我也可以使用粗体格式来代替模板。在哪里可以找到解决方案?请提供一个示例。
我找不到解决办法

flseospp

flseospp1#

这是一个(非常基本的)代码示例,用于使用Microsoft.Office.InteropnameSpace打开、写入和保存Excel文件。单元格格式设置在写入时进行。
您也可以预先格式化excel文件(绘制标题行和列,粗体等),并使用它作为模板。不要忘记保存在另一个文件名,以保留您的模板文件。

Imports Microsoft.Office.Interop

Public Class ExcelApp

    Public Shared xlapp As Excel.Application
    Public Shared xlbook As Excel.Workbook
    Public Shared xlsheet As Excel.Worksheet

    'open excel file
    Public Function OpenSheet(ByVal FileName As String, password As String) As Boolean

        Try
            xlapp = New Excel.Application
            'open file and sheet
            xlapp.Visible = False
            xlapp.DisplayAlerts = False
            xlbook = xlapp.Workbooks.Open(Filename:=FileName, Password:=password)
            xlsheet = xlapp.Sheets(1)
        Catch ex As Exception
            Return False
        End Try
        Return True
    End Function

    'write value in cell with some formating
    Public Sub WriteCell(ByVal SheetName As String, ByVal line As Integer, ByVal col As Integer, ByVal txt As String)

        Try
            xlapp.Sheets(SheetName).Select()
            xlapp.ActiveSheet.Cells(line, col).Value = txt
            xlapp.ActiveSheet.Cells(line, col).font.bold = True
            xlapp.ActiveSheet.Cells(line, col).Orientation = 60
            xlapp.ActiveSheet.Cells(line, col).interior.color = Color.Beige
        Catch ex As Exception
        End Try
    End Sub

    Public Function saveAndCloseExcelFile(ByVal FileName As String) As Boolean
        xlapp.DisplayAlerts = False
        Try
            xlapp.ActiveWorkbook.SaveAs(FileName)
        Catch ex As Exception
            Return False
        End Try

        xlbook.Close()
        xlapp.Quit()
        xlapp = Nothing
        GC.Collect()
        Return True
    End Function

End Class

相关问题