我有一个问题我还没找到合适的答案....我有一个检索数据的功能
从数据库中我想通过点击按钮将所有数据导出到Excel文件我该怎么办?
Here is my function:
******************
Protected Sub btnExport_Click(ByVal sender as Object,ByVal e as EventArgs)
Try
Dim tmp as String = ""
Dim dba as New DBAccess
Dim ds as DataSet = dba.GetGlobalAdminUser(m_user.UserID)
If Not ds Is Nothing Then
Dim dt as DataTable = ds.Tables(0)
????
End IF
End Sub
答案 0 :(得分:0)
您需要自己创建文件,然后使用OpenXml库。你应该避免使用OLE / COM
这是一种不需要大量编码的方法:
How to Create/Open Excel files using OpenXml with C#
以下是另一种编写数据集的方法:
http://www.codeproject.com/Articles/692121/Csharp-Export-data-to-Excel-using-OpenXML-librarie
答案 1 :(得分:0)
试试这个方法。你必须使用像
Protected Sub btnExport_Click(ByVal sender as Object,ByVal e as EventArgs)
Try
Dim tmp as String = ""
Dim dba as New DBAccess
Dim ds as DataSet = dba.GetGlobalAdminUser(m_user.UserID)
If Not ds Is Nothing Then
Dim dt as DataTable = ds.Tables(0)
DatatableToExcel(dt)
End IF
...
...
End Sub
Private Sub DatatableToExcel(ByVal dtTemp As DataTable)
Dim _excel As New Microsoft.Office.Interop.Excel.Application
Dim wBook As Microsoft.Office.Interop.Excel.Workbook
Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet
wBook = _excel.Workbooks.Add()
wSheet = wBook.ActiveSheet()
Dim dt As System.Data.DataTable = dtTemp
Dim dc As System.Data.DataColumn
Dim dr As System.Data.DataRow
Dim colIndex As Integer = 0
Dim rowIndex As Integer = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
_excel.Cells(1, colIndex) = dc.ColumnName
Next
For Each dr In dt.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each dc In dt.Columns
colIndex = colIndex + 1
_excel.Cells(rowIndex + 1, colIndex) = dr(dc.ColumnName)
Next
Next
wSheet.Columns.AutoFit()
Dim strFileName As String = "C:\datatable.xlsx"
If System.IO.File.Exists(strFileName) Then
System.IO.File.Delete(strFileName)
End If
wBook.SaveAs(strFileName)
wBook.Close()
_excel.Quit()
End Sub