首页 > 开发 > 综合 > 正文

实现将DataGrid中数据倒出Excel文件并下载

2024-07-21 02:23:57
字体:
来源:转载
供稿:网友
imports system
imports system.text
namespace toexcel

    '功能:将asp.net中datagrid生成excel文件下载。
    'mountains改进:1、支持中文 2、隐藏列不显示
    '日期:2002.10.30
    public class datagridtocsv

        public function generatefile(byref page as system.web.ui.page, byval mydatagrid as system.web.ui.webcontrols.datagrid, byval filename as string) as string

            dim resp as httpresponse
            dim colcount as integer = mydatagrid.columns.count - 1

            resp = page.response

            resp.contentencoding = system.text.encoding.getencoding("gb2312") '解决中文乱码之关键
            'resp.charset = "utf-8"
            'resp.addfiledependency(filename)
            'resp.contenttype = "text/html"
            ''resp.appendheader("content-type", "text/html; charset=gb2312")

            resp.appendheader("content-disposition", "attachment;filename=" + filename)  '必要,做成下载文件
   

            dim colheaders as string = ""
            dim stritems as stringbuilder = new stringbuilder()

            dim mycol as datagridcolumn

            dim i as integer

            for i = 0 to colcount
                mycol = mydatagrid.columns(i)
                if mycol.visible = true then
                    colheaders = colheaders & mycol.headertext.tostring & ","
                end if
            next

            if colheaders.length > 0 then
                colheaders = colheaders.substring(0, colheaders.lastindexof(","))
            end if

            colheaders = colheaders & chr(13) & chr(10)



            resp.write(colheaders)

            dim colrow as string

            dim item as datagriditem

            for each item in mydatagrid.items
                resp.write(formatexportrow(colcount, item, mydatagrid))
            next item

            resp.end()

        end function

        private function formatexportrow(byval colcount as integer, byval item as datagriditem, byval mydatagrid as system.web.ui.webcontrols.datagrid) as string
            dim stritem as string
            dim i as integer

            for i = 0 to colcount
                if mydatagrid.columns(i).visible = true then
                    if item.cells(i).text is system.dbnull.value then
                        item.cells(i).text = ""
                    end if
                    if i = colcount then
                        stritem += item.cells(i).text.tostring & chr(13) & chr(10)
                    else
                        stritem += item.cells(i).text.tostring & ","
                    end if
                end if
            next
            stritem = replace(stritem, " ", " ")
            return stritem
        end function


    end class

end namespace
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表