这是网上的一个在Vb.net中将数据库中的数据导出到Excel的例子,经过了小小的修改,这种方法的好处是不需要另外的引用,代码如下:
ASP/Visual Basic Code
复制内容到剪贴板
- DimMytableAsDataTable=myDataSet("select*fromJL").Tables(0) '红色的是自定函数,可见最下面代码
- IfMytableIsNothingThen
- MessageBox.Show("没有记录不能导出数据","导出提示",MessageBoxButtons.OK,MessageBoxIcon.Information)
- ExitSub
- EndIf
- DimSaveFileDialogAsFileDialog=NewSaveFileDialog
- IfMytable.Rows.Count>0Then
- DimMyFileNameAsString
- DimFileNameAsString=""
- WithSaveFileDialog
- .AddExtension=True'如果用户忘记添加扩展名,将自动加上
- .DefaultExt="xls"'默认扩展名
- .Filter="Excel文件(*.xls)|*.xls"
- .Title="文件保存到"
- If.ShowDialog=Windows.Forms.DialogResult.OKThen
- FileName=.FileName
- EndIf
- EndWith
- MyFileName=Microsoft.VisualBasic.Right(FileName,4)
- IfMyFileName=""Then
- ExitSub
- EndIf
- IfMyFileName=".xls"OrMyFileName=".XLS"Then
- DimfsAsFileStream=NewFileStream(FileName,FileMode.Create)
- DimswAsStreamWriter=NewStreamWriter(fs,System.Text.Encoding.Default)
- sw.WriteLine(vbTab&FileName&vbTab&Date.Now)
- Dimi,jAsInteger
- DimstrAsString=""
- Fori=0ToMytable.Columns.Count-1
- str=Mytable.Columns(i).Caption
- sw.Write(str&vbTab)
- Next
- sw.Write(vbCrLf)
- Forj=0ToMytable.Rows.Count-1
- Fori=0ToMytable.Columns.Count-1
- DimstrRowAsString
- strRow=IIf(Mytable.Rows(j).Item(i)IsDBNull.Value,"",Mytable.Rows(j).Item(i))
- sw.Write(strRow&vbTab)
- Next
- sw.Write(vbCrLf)
- Next
- sw.Close()
- fs.Close()
- MessageBox.Show("数据导出成功!",MessageBoxIcon.Information)
- Else
- ExitSub
- EndIf
- Else
- MessageBox.Show("没有记录不能导出数据",MessageBoxIcon.Information)
- EndIf
- PublicFunctionmyDataSet(ByValsqlStrAsString)AsDataSet
- dbName=My.Settings.dbNamer
- Try
- ConnStr="Provider=Microsoft.Jet.OLEDB.4.0;DataSource="&Application.StartupPath&"\"&dbName&".mdb"
- Conn=NewOleDbConnection(ConnStr)
- Conn.Open()
- DimdaAsOleDbDataAdapter=NewOleDbDataAdapter(sqlStr,Conn)
- DimdsAsDataSet=NewDataSet
- da.Fill(ds)
- Returnds
- CatchexAsException
- MsgBox(ex.Message.ToString,MsgBoxStyle.Information,"提示")
- 'MsgBox("请检查数据库名称是否正确!!","找不到数据库")
- 'frmSet.txtDbName.Text="data2003"
- dbName=My.Settings.dbNamer="site"
- 'frmMain.toolReReadData.PerformClick()
- 'frmSet.Show()
- Finally
- Conn.Close()
- EndTry
- ReturnNothing'为去无返回警告
- EndFunction