我想從gridview導出數據到excel。我的電腦上安裝了office 2010。當我試圖打開excel文件時,它給了我錯誤,即「您試圖打開的文件的格式不同於文件擴展名c#指定的格式」。如何將數據從gridview導出到excel 2003,2007,2010沒有警告信息
我對出口的GridView代碼:
Protected Sub btnexptoexcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnexptoexcel.Click
Try
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", "attachment;filename=Complaint_Details.xls")
Response.Charset = ""
Response.ContentType = "application/ms-excel"
Using sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
grd_ComplaintDetails.AllowPaging = False
grd_ComplaintDetails.HeaderRow.BackColor = Color.White
For Each cell As TableCell In grd_ComplaintDetails.HeaderRow.Cells
cell.BackColor = grd_ComplaintDetails.HeaderStyle.BackColor
Next
For Each row As GridViewRow In grd_ComplaintDetails.Rows
row.BackColor = Color.White
For Each cell As TableCell In row.Cells
If row.RowIndex Mod 2 = 0 Then
cell.BackColor = grd_ComplaintDetails.AlternatingRowStyle.BackColor
Else
cell.BackColor = grd_ComplaintDetails.RowStyle.BackColor
End If
cell.CssClass = "textmode"
Next
Next
grd_ComplaintDetails.RenderControl(hw)
Dim style As String = "<style> .textmode { } </style>"
Response.Write(style)
Response.Output.Write(sw.ToString())
Response.Flush()
Response.[End]()
End Using
Catch ex As Exception
div_Msg.InnerText = "Can not generate Excel File"
End Try
End Sub
我的問題是,當我打開文件(在2003的MSOffice,2007或2010),它不應該給我的文件擴展名錯誤... 你能告訴我什麼是我應該在代碼中做出的更改嗎?
感謝您的回覆...我根據您的評論替換我的代碼,但它給了我錯誤,即「excel無法打開文件,因爲文件格式無效。」..你能幫我嗎? – 2014-09-03 13:04:35
@KishorRajendraKulkarni我不能,我不知道你在做什麼......我建議用EPPLUS重寫你的整個過程,然後根據提供的示例項目創建一個** valid **'xlsx'文件。 – Vland 2014-09-03 13:19:17