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