我想将数据从datatable导出到excel文件
我收到了这个错误
'EmployeeMaster$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that is not too long.
这是我的代码
Response.Clear()
Dim dt_excel As New System.Data.DataTable
Dim attach As String = "attachment; filename=EmployeeMaster.xls"
File.Delete("C:\Users\Julian\Downloads\EmployeeMaster.xls")
conn.connect()
conn.connectExcel()
dt_excel = conn.openReader("Select * from EmployeeMaster")
Response.ClearContent()
Response.AddHeader("content-disposition", attach)
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Dim tab As String = ""
For Each dc As DataColumn In dt_excel.Columns
Response.Write(tab + dc.ColumnName)
tab = vbTab
Next
Response.Write(vbLf)
conn.openReaderExcel("Create Table [EmployeeMaster$] (EmployeeNo varchar(25))") '<- throw error here
For Each dr As DataRow In dt_excel.Rows
tab = ""
conn.openReaderExcel("Insert into [EmployeeMaster$] (EmployeeNo) values ('" & dr.Item("EmployeeNo") & "')")
Response.Write(vbLf)
Next
Response.End()
我一直想知道我的代码有什么问题。难道有人建议我解决这个问题的方法吗?
所有建议/帮助将不胜感激
关心Siekh
答案 0 :(得分:0)
试试这个
Protected Sub btnExportExcel_Click(ByVal sender As Object,
ByVal e As EventArgs)
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
GridView1.AllowPaging = False
GridView1.DataBind()
'Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF")
'Apply style to Individual Cells
GridView1.HeaderRow.Cells(0).Style.Add("background-color", "green")
GridView1.HeaderRow.Cells(1).Style.Add("background-color", "green")
GridView1.HeaderRow.Cells(2).Style.Add("background-color", "green")
GridView1.HeaderRow.Cells(3).Style.Add("background-color", "green")
For i As Integer = 0 To GridView1.Rows.Count - 1
Dim row As GridViewRow = GridView1.Rows(i)
'Change Color back to white
row.BackColor = System.Drawing.Color.White
'Apply text style to each Row
row.Attributes.Add("class", "textmode")
'Apply style to Individual Cells of Alternating Row
If i Mod 2 <> 0 Then
row.Cells(0).Style.Add("background-color", "#C2D69B")
row.Cells(1).Style.Add("background-color", "#C2D69B")
row.Cells(2).Style.Add("background-color", "#C2D69B")
row.Cells(3).Style.Add("background-color", "#C2D69B")
End If
Next
GridView1.RenderControl(hw)
'style to format numbers to string
Dim style As String = "<style>.textmode{mso-number-format:\@;}</style>"
Response.Write(style)
Response.Output.Write(sw.ToString())
Response.Flush()
Response.End()
End Sub
希望它可以帮到你
答案 1 :(得分:0)
你知道如何使用数据集吗?因为你可以在那里创建自定义查询...不需要所有代码...然后将此查询分配给数据表甚至数据网格然后将其导出到excel。如果你使用数据集,datatables / datagridviews并需要代码知道
答案 2 :(得分:0)
回答可能有点迟,但我认为这里的问题在于使用“table”(= sheet)名称中的[
和]
个字符...虽然它可以大多数数据库,你在这里处理excel ......