Code
''' <summary>
''' Generate xls file
''' </summary>
''' <param name="sourceDT"></param>
''' <remarks></remarks>
Private Sub GenerateFile(ByVal sourceDT As DataTable, ByVal fileName As String)
Dim sw As StringWriter = New StringWriter()
Dim dg As DataGrid = New DataGrid()
Dim htmlWeite As New HtmlTextWriter(sw)
dg.DataSource = sourceDT
dg.DataBind()
dg.RenderControl(htmlWeite)
sw.Close()
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls")
Response.ContentType = "application/ms-excel"
'Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312")
Response.Write(sw)
Response.End()
End Sub
''' <summary>
''' Generate xls file
''' </summary>
''' <param name="sourceDT"></param>
''' <remarks></remarks>
Private Sub GenerateFile(ByVal sourceDT As DataTable, ByVal fileName As String)
Dim sw As StringWriter = New StringWriter()
Dim dg As DataGrid = New DataGrid()
Dim htmlWeite As New HtmlTextWriter(sw)
dg.DataSource = sourceDT
dg.DataBind()
dg.RenderControl(htmlWeite)
sw.Close()
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls")
Response.ContentType = "application/ms-excel"
'Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312")
Response.Write(sw)
Response.End()
End Sub
以上一步只能做个简单的生成,但是在很多时候,我们想要对格式进行 format 那么就需要以下的步骤了:
在bind item的时候做处理
Code
protected void DataGrid1_ItemDataBound1(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
e.Item.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
e.Item.Cells[2].Attributes.Add("style", "vnd.ms-excel.numberformat:dd-MM-yyyy");
}
}
protected void DataGrid1_ItemDataBound1(object sender, DataGridItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
e.Item.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
e.Item.Cells[2].Attributes.Add("style", "vnd.ms-excel.numberformat:dd-MM-yyyy");
}
}
以上只是思路,希望能够帮助你。