vb.net输出数据 vbnet数据库编程例子
vb.net中从DataGridView里面把数据导出到excel中
以下是我以前百度找的资料 希望对你有用 你读取DataGridView到DataGrid然后直接调用函数即可
我们提供的服务有:成都网站建设、做网站、微信公众号开发、网站优化、网站认证、洛浦ssl等。为上千余家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的洛浦网站制作公司
Public Function ExportXLsD(ByVal datagrid As DataGrid) ', ByVal Title As String)
'Dim Mytable As New DataTable
'Mytable = CType(datagrid.DataSource, DataTable)
If mytable Is Nothing Then
MessageBox.Show("没有记录不能导出数据", "PurpleStar", MessageBoxButtons.OK, MessageBoxIcon.Information)
Exit Function
End If
If mytable.Rows.Count 0 Then
Dim MyFileName As String
Dim FileName As String
With SaveFileDialog1
.AddExtension = True '如果用户忘记添加扩展名,将自动家上
.DefaultExt = "xls" '默认扩展名
.Filter = "Excel文件(*.xls)|*.xls"
.Title = "文件保存到"
If .ShowDialog = DialogResult.OK Then
FileName = .FileName
End If
End With
MyFileName = Microsoft.VisualBasic.Right(FileName, 4)
If MyFileName = "" Then
Exit Function
End If
If MyFileName = ".xls" Or MyFileName = ".XLS" Then
Dim FS As FileStream = New FileStream(FileName, FileMode.Create)
Dim sw As StreamWriter = New StreamWriter(FS, System.Text.Encoding.Default)
sw.WriteLine(vbTab FileName vbTab Date.Now)
Dim i, j As Integer
Dim str As String = ""
For i = 0 To mytable.Columns.Count - 1
str = mytable.Columns(i).Caption
sw.Write(str vbTab)
Next
sw.Write(vbCrLf)
For j = 0 To mytable.Rows.Count - 1
For i = 0 To mytable.Columns.Count - 1
Dim strColName, strRow As String
strRow = IIf(mytable.Rows(j).Item(i) Is DBNull.Value, "", mytable.Rows(j).Item(i))
sw.Write(strRow vbTab)
Next
sw.Write(vbLf)
Next
sw.Close()
FS.Close()
MessageBox.Show("数据导出成功!", "PurpleStar", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
Exit Function
End If
Else
MessageBox.Show("没有记录不能导出数据", "PurpleStar", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Function
Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
Dim saveExcel As SaveFileDialog
saveExcel = New SaveFileDialog
saveExcel.Filter = "Excel文件(.xls)|*.xls"
Dim filename As String
If saveExcel.ShowDialog = Windows.Forms.DialogResult.Cancel Then Exit Sub
filename = saveExcel.FileName
Dim excel As Excel.Application
excel = New Excel.Application
excel.DisplayAlerts = False
excel.Workbooks.Add(True)
excel.Visible = False
Dim i As Integer
For i = 0 To DataGridView1.Columns.Count - 1
excel.Cells(1, i + 1) = DataGridView1.Columns(i).HeaderText
Next
'设置标题
Dim j As Integer
For i = 0 To DataGridView1.Rows.Count - 1 '填充数据
For j = 0 To DataGridView1.Columns.Count - 1
excel.Cells(i + 2, j + 1) = DataGridView1(j, i).Value
Next
Next
excel.Workbooks(1).SaveCopyAs(filename) '保存
Me.Close()
End Sub
利用VB.NET实现导出DataTable数据到excel中,各位大侠帮帮忙,最好有源码,谢谢,江湖救急
刚好写了个Helper类,你试验一下DataTable2Exce(这个方法代码如下:
Imports System.IO
Imports System.Data
Imports System.Data.OleDb
Public MustInherit Class ExcelHelper
Private Shared Function buildConnStr(excelFilePath As String) As String
Dim excelFileInfo As New System.IO.FileInfo(excelFilePath)
Dim constr As String
If excelFileInfo.Extension = ".xlsx" Then
constr = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1'", excelFilePath)
Else
constr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'", excelFilePath)
End If
Return constr
End Function
'将datatable导入到excel
Public Shared Function DataTable2Excel(dt As DataTable, excelFilePath As String) As Boolean
If File.Exists(excelFilePath) Then
Throw New Exception("该文件已经存在!")
End If
If dt.TableName.Trim.Length = 0 Or dt.TableName.ToLower = "table" Then
dt.TableName = "Sheet1"
End If
Dim colCount As Integer = dt.Columns.Count
Dim pa(colCount - 1) As OleDb.OleDbParameter
Dim tableStructStr As String = "Create Table " dt.TableName "("
Dim connString As String = buildConnStr(excelFilePath)
Dim objconn As New OleDbConnection(connString)
Dim objcmd As New OleDbCommand
objcmd.Connection = objconn
Dim dataTypeList As New ArrayList
dataTypeList.Add("System.Decimal")
dataTypeList.Add("System.Double")
dataTypeList.Add("System.Int16")
dataTypeList.Add("System.Int32")
dataTypeList.Add("System.Int64")
dataTypeList.Add("System.Single")
Dim i As Integer = 0
For Each col As DataColumn In dt.Columns
If dataTypeList.IndexOf(col.GetType.ToString) 0 Then
pa(i) = New OleDbParameter("@" col.ColumnName, OleDbType.Double)
objcmd.Parameters.Add(pa(i))
If i + 1 = colCount Then
tableStructStr += col.ColumnName + " double)"
Else
tableStructStr += col.ColumnName + " double,"
End If
Else
pa(i) = New OleDbParameter("@" col.ColumnName, OleDbType.VarChar)
objcmd.Parameters.Add(pa(i))
If i + 1 = colCount Then
tableStructStr += col.ColumnName + " VarChar)"
Else
tableStructStr += col.ColumnName + " VarChar,"
End If
End If
i += 1
Next
Try
objcmd.CommandText = tableStructStr
If objconn.State = ConnectionState.Closed Then objconn.Open()
objcmd.ExecuteNonQuery()
Catch ex As Exception
Throw ex
End Try
Dim InsertSql_1 As String = "Insert into " + dt.TableName + " ("
Dim InsertSql_2 As String = " Values ("
Dim InsertSql As String = ""
For colID As Integer = 0 To colCount - 1 Step 1
If colID + 1 = colCount Then
InsertSql_1 += dt.Columns(colID).ColumnName ")"
InsertSql_2 += "@" + dt.Columns(colID).ColumnName + ")"
Else
InsertSql_1 += dt.Columns(colID).ColumnName + ","
InsertSql_2 += "@" + dt.Columns(colID).ColumnName + ","
End If
Next
InsertSql = InsertSql_1 + InsertSql_2
For rowID As Integer = 0 To dt.Rows.Count - 1 Step 1
For colID = 0 To dt.Columns.Count - 1
If pa(colID).DbType = DbType.Double And dt.Rows(rowID)(colID).ToString.Trim = "" Then
pa(colID).Value = 0
Else
pa(colID).Value = dt.Rows(rowID)(colID).ToString.Trim
End If
Next
Try
objcmd.CommandText = InsertSql
objcmd.ExecuteNonQuery()
Catch ex As Exception
Throw ex
End Try
Next
Try
If objconn.State = ConnectionState.Open Then objconn.Close()
Catch exp As Exception
Throw exp
End Try
Return True
End Function
' 获取Excel文件数据表列表Sheets
Public Shared Function GetExcelTables(ExcelFileName As String) As ArrayList
'Dim sheets As New List(Of String)
'conn.Open()
'Dim dt As DataTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
'For Each r In dt.Rows
' sheets.Add(r("TABLE_NAME"))
'Next
'conn.Close()
'Return sheets
Dim dt As DataTable
If Not File.Exists(ExcelFileName) Then
Throw New Exception("指定的Excel文件不存在")
Return Nothing
End If
Dim tableList As New ArrayList
Using conn As OleDbConnection = New OleDbConnection(buildConnStr(ExcelFileName))
Try
conn.Open()
dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
Catch ex As Exception
Throw ex
End Try
For i As Integer = 0 To dt.Rows.Count - 1
Dim tableName As String = dt.Rows(i)(2).ToString.Trim.TrimEnd("$")
If tableList.IndexOf(tableName) 0 Then tableList.Add(tableName)
Next
End Using
Return tableList
End Function
'将Excel文件导出至DataTable(第一行作为表头)
Public Shared Function InputFromExcel(ExcelFileName As String, TableName As String) As DataTable
If Not File.Exists(ExcelFileName) Then
Throw New Exception("指定的Excel文件不存在")
End If
Dim tableList As ArrayList = GetExcelTables(ExcelFileName)
If tableList.IndexOf(TableName) 0 Then
TableName = tableList(0).ToString.Trim
End If
Dim dt As New DataTable
Dim conn As New OleDbConnection(buildConnStr(ExcelFileName))
Dim cmd As New OleDbCommand("select * from [" TableName "$]", conn) '调试是否需要$
Dim adapter As New OleDbDataAdapter(cmd)
Try
If conn.State = ConnectionState.Closed Then conn.Open()
adapter.Fill(dt)
Catch ex As Exception
Throw ex
Finally
If conn.State = ConnectionState.Open Then conn.Close()
End Try
Return dt
End Function
'查询excel文件中的一个数据
Public Shared Function ReadOneDataFromExcel(ExcelFileName As String, TableName As String, sql As String) As Object
If Not File.Exists(ExcelFileName) Then
Throw New Exception("指定的Excel文件不存在")
End If
Dim tableList As ArrayList = GetExcelTables(ExcelFileName)
If tableList.IndexOf(TableName) 0 Then
TableName = tableList(0).ToString.Trim
End If
Dim dt As New DataTable
Dim conn As New OleDbConnection(buildConnStr(ExcelFileName))
Dim cmd As New OleDbCommand(sql, conn) '调试是否需要$
Dim ret As Object
Try
If conn.State = ConnectionState.Closed Then conn.Open()
ret = cmd.ExecuteScalar()
Catch ex As Exception
Throw ex
Finally
If conn.State = ConnectionState.Open Then conn.Close()
End Try
Return ret
End Function
'获取Excel文件指定数据表的数据列表columnNames
Public Shared Function GetExcelTableColumns(ExcelFileName As String, TableName As String) As ArrayList
Dim dt As DataTable
If Not File.Exists(ExcelFileName) Then
Throw New Exception("指定的Excel文件不存在")
Return Nothing
End If
Dim ColList As New ArrayList
Using conn As OleDbConnection = New OleDbConnection(buildConnStr(ExcelFileName))
Try
conn.Open()
dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, New Object() {Nothing, Nothing, TableName, Nothing})
Catch ex As Exception
Throw ex
End Try
For i As Integer = 0 To dt.Rows.Count - 1
Dim ColName = dt.Rows(i)("Column_Name").ToString().Trim()
ColList.Add(ColName)
Next
End Using
Return ColList
End Function
End Class
vb.net怎么从文本文档中读取一行数据,将文本输出到控制台?
以下示例一次从文件中读取一行,然后将每行文本打印到控制台。
Sub ReadTextLinesFromFile()
Dim file As New System.IO.StreamReader("c:test.txt")
Dim oneLine As String
oneLine = file.ReadLine()
While (oneLine "")
Console.WriteLine(oneLine)
oneLine = file.ReadLine()
End While
file.Close()
End Sub
如何在vb.net控制台程序中格式化输出结果(如图)
Sub Main()
Dim a As Boolean = True, b As Boolean = False
Console.WriteLine(LCase("a=" a " b=" b))
Console.WriteLine(LCase("true and false = " (a And b)))
Console.WriteLine(LCase("true and not false = " (a And Not b)))
Console.WriteLine(LCase("true false or false = " ((ab) Or b)))
Console.ReadKey()
End Sub
vb.net中 导出excel表格代码怎么写
private void ExportExcelFromDataGrid
( string filename , System.Web.UI.WebControls.DataGrid ToExcelGrid )
...{
Response.Clear();
Response.Buffer= true;
Response.Charset="utf-8";
Response.AppendHeader ("Content-Disposition","attachment;filename="+Server.UrlEncode ( filename ) );
Response.ContentEncoding=System.Text.Encoding.Default;//设置输出流为简体中文
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
this.EnableViewState = false;
System.Globalization.CultureInfo myCItrad =
new System.Globalization.CultureInfo("ZH-CN",true);
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
System.Web.UI.HtmlTextWriter oHtmlTextWriter =
new System.Web.UI.HtmlTextWriter(oStringWriter);
ToExcelGrid.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
private void Button4_Click(object sender, System.EventArgs e)
...{
this.Panel1.Visible = false;
string filename = "内训师.xls";
this.DataGrid1.Columns[6].Visible = true;
this.DataGrid1.Columns[7].Visible = true;
this.DataGrid1.Columns[this.DataGrid1.Columns.Count-1].Visible = false; // *
this.DataGrid1.Columns[this.DataGrid1.Columns.Count-2].Visible = false; // *
this.DataGrid1.AllowSorting = false; // *
this.DataGrid1.AllowPaging = false;
this.DataGrid1.SelectedIndex = -1; // *
this.BindGrid();
this.ExportExcelFromDataGrid ( filename , this.DataGrid1 );
}
}
原理是利用DataGrid(其实是其父类Control)的RenderControl方法输出,整个DataGrid的外观时,将这些HTML代码写入到缓冲区,同时设置一下 ContentType ,让Excel自己的自动纠错功能将这个输出存为一个Excel文件。
很多网上的朋友使用了以上这种可粘贴性强的代码,发现不好用,反映的错误类似:
“LinkButton必须放在一个具有runat=server的标签的Form”之类的话,而更多的网友说:
问题很明显,因为DataGrid没有放在runat=server 的Form里面,加上就可以了。
我认为,这种回答是很不准确的,理由如下:
通常使用这种代码的人他/她的DataGrid,最起码已经能用了,所以必定放在那个具有runat=server 的form标签里了。 报错是LinkButton,而不是DataGrid,很多细心的朋友很可能会说,我一直在用DataGrid,LinkButton在哪里来的。 其实真正的问题是,上面的代码没有加了 // * 的那几行代码引起的。
当然如果你的DataGrid,没有排序,没有使用那种按钮列的话,是不会出问题的。
言归正传,LinkButtion其实是你将DataGrid设为可排序时候,的表头包含的,所以我要将DataGrid的排序设为False。
同样得到上面的其实,那些按钮列,什么"编辑"、“删除”等等这些,也是用了LinkButton,把他设为不可见就是了。
其实说得再明白一点就是,将有可能产生LinkButton,或其他控件的东西都不让它输出就是了
vb.net dataGridView中的数据导出为excel表2010-03-01 15:03在form1窗体里添加一个dataGridView1(根据自己是使用情况要给他命名,符合命名规范哟。)在添加一个Button1(命名)。记着,dataGridView的属性里有一个allowUsersToAddRows,要设置成FALSE。否则会发生一个错误,当然错误是什么你自己试一下就ok了。
还有一点要注意:因为你要用到excel表,所以要首先在项目里添加引用哟:项目(project)-添加引用(add reference)-Microsoft .Office.Interop.Excel
Button1的代码:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'要先添加引用才能用到 Microsoft.Office.Interop.Excel.Application()
Dim MyExcel As New Microsoft.Office.Interop.Excel.Application()
MyExcel.Application.Workbooks.Add(True)
MyExcel.Visible = True
'去除dataGridView1的编号列(这里也可以不要)
Dim m As Integer
For m = 0 To DataGridView1.ColumnCount - 1
MyExcel.Cells(1, m + 1) = Me.DataGridView1.Columns(m).HeaderText
Next m
'往excel表里添加数据
Dim i As Integer
For i = 0 To DataGridView1.RowCount - 1
Dim j As Integer
For j = 0 To DataGridView1.ColumnCount - 1
If Me.DataGridView1(j, i).Value Is System.DBNull.Value Then
MyExcel.Cells(i + 2, j + 1) = ""
Else
MyExcel.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString
End If
Next j
Next i
End Sub
vb.net输出数组
1.你说的这个有点问题,是要只输出一次,也可做,
2.但问题是如果你数组还有就看不到了!这个做法有点问题
1.解决方法:
循环前面加入一个变量 dim Temp as Double=0
For i = 0 To 9
If score(i) avg and score(i)temp Then
TextBox3.Text = TextBox3.Text score(i) " "
if score(i)=avg then
temp=score(i)
end if
End If
Next
本文题目:vb.net输出数据 vbnet数据库编程例子
当前URL:http://hbruida.cn/article/dodjedd.html