所用环境VS2010;WPF应用程序模板;在界面上添加一个Button控件
话不多说,直接上全部代码和注释
Imports Microsoft.Office.Interop
Imports Microsoft.Win32
Class MainWindow
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
Dim CrateFile, YearPath '定义变量
CrateFile = CreateObject("Scripting.FileSystemObject") '微软注册的库,用来调用系统盘的路径
YearPath = AppDomain.CurrentDomain.BaseDirectory & "\" & Year(Now) & "年" & "数据" '在Debug下设置年份路径,
If CrateFile.FolderExists(YearPath) Then '判断年份路径下是否存在
Dim MonthPath '如果存在设置月份路径
MonthPath = AppDomain.CurrentDomain.BaseDirectory & "\" & Year(Now) & "年" & "数据" & "\" & Month(Now) & "月" & "数据" & "\"
If CrateFile.FolderExists(MonthPath) Then '判断月份路径是否存在
Dim Sdlg As SaveFileDialog = New SaveFileDialog '定义一个保存对话框
Dim dp '定义保存EXCEL名称
dp = Format(Now, "yyyy-MM-dd") '设置名称为当前年月日
Sdlg.FileName = dp & ".xls" '保存对话框的默认文件名
Sdlg.Filter = "EXCEL档案(*.Xls)|*.Xls" '过滤器设置
'
'创建日期Excel记录数据
'
If Boo_FileExist(MonthPath & Sdlg.FileName) = False Then
Dim Xls As Excel.Application = New Excel.Application '定义excel应用程序
Dim Xlsbook As Excel.Workbook '定义工作簿
Dim Xlssheet As Excel.Worksheet '定义工作表
Xls.Visible = False '显示excel 程序
Xlsbook = Xls.Application.Workbooks.Add '添加新工作簿或exbook=exapp.workbooks.open("路径\文件名")'打开已存在工作薄
Xlssheet = Xlsbook.Sheets(1) '第1个工作表的控制句柄
' MsgBox("EXCEL档案创建完毕!")
'Xlssheet.Cells(1, 1) = "这是一个创建EXCEL的示例" '向单元格(1,1)写入
Xlsbook.SaveAs(MonthPath & Sdlg.FileName) '保存文件
Xlssheet = Nothing '释放资源
Xlsbook.Close() '关闭工作簿
Xlsbook = Nothing '释放资源
Xls.Quit() '退出excel应用程序
Xls = Nothing
Else
'
'填入你需要写的数据
'
End If
Else
CrateFile.CreateFolder(MonthPath) '如果月份路径不存在,则以当前月创建一个月份文件夹
End If
Else
CrateFile.CreateFolder(YearPath) '如果年份路径不存在,则以当前月创建一个年份文件夹
End If
End Sub
Private Function Boo_FileExist(ByVal Str_File As String) As Boolean
Boo_FileExist = System.IO.File.Exists(Str_File) '判断文件是否存在的函数 传入String值 返回Boolean值
End Function