欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net导出excel

程序员文章站 2022-07-19 20:38:52
asp.net 根据html模板导出excel public class ExcelHelper { /// /// 根据html模板文件生成excel文件 /// /// 数据源 ///

asp.net 根据html模板导出excel

public class excelhelper
{
    /// <summary>
    /// 根据html模板文件生成excel文件
    /// </summary>
    /// <param name="ds">数据源</param>
    /// <param name="templatefilepath">html模板文件路径(虚拟路径而非物理路径)</param>
    /// <param name="tofilename">生成的excel文件名,带后缀不带路径</param>
    /// <returns></returns>
    public static string getexcel(dataset ds, string templatefilepath, string tofilename)
    {
        string tofilepath = syshelper.getvirtualpath() + "upload/export_excel/";
        string stroutpath = httpcontext.current.server.mappath(tofilepath);
        if (!directory.exists(stroutpath))
        {
            directory.createdirectory(stroutpath);
        }

        string templatecontent = getstringfromtemplate(ds, templatefilepath);
        //保存文件
        using (filestream fs = new filestream(stroutpath + tofilename, filemode.create))
        {
            using (streamwriter sw = new streamwriter(fs))
            {
                sw.write(templatecontent);
            }
        }
        return tofilepath + tofilename;
    }

    /// <summary>
    /// 根据模板生成字符换
    /// </summary>
    /// <param name="ds"></param>
    /// <param name="templatefilepath"></param>
    /// <returns></returns>
    private static string getstringfromtemplate(dataset ds, string templatefilepath)
    {
        //读取模板
        string templatecontent = "";
        using (streamreader sr = new streamreader(httpcontext.current.server.mappath(templatefilepath)))
        {
            templatecontent = sr.readtoend();
        }
        
        //解析每个表
        for (int tableindex = 0; tableindex < ds.tables.count; tableindex++)
        {
            datatable dt = ds.tables[tableindex];
            //获取表的模板集合
            string tabletag = string.format(@"#table.{0}#", tableindex);//表的标签
            string pattern = string.format(@"#table\.{0}#.*?#table\.{0}#", tableindex);
            regex reg = new regex(pattern, regexoptions.singleline);
            matchcollection matchs = reg.matches(templatecontent);
            //解析每个模板
            foreach (match match in matchs)
            {
                string tabletemplate = match.value;
                string table = "";//解析后内容
                                  //解析每行数据
                for (int i = 0; i < dt.rows.count; i++)
                {
                    string rowtemplate = tabletemplate.replace(tabletag, "");//去掉模板标签
                                                                             //解析行模板
                    for (int j = 0; j < dt.columns.count; j++)
                    {
                        string columnname = "#table." + tableindex + "." + dt.columns[j].columnname + "#";
                        rowtemplate = rowtemplate.replace(columnname, dt.rows[i][j].tostring());
                    }
                    table += rowtemplate;
                }
                //解析完之后替换到模板
                templatecontent = templatecontent.replace(tabletemplate, table);
            }
        }
        return templatecontent;
    }
}

 

html模板格式

<!doctype html>
<html>
<head>
    <title></title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body>
    <table border="1">
        <tr><td colspan="4" style="text-align:center;">事件汇总表</td></tr>
        <tr>
            <td style="width:200px;">事件名称</td>
            <td style="width:500px;">事件简要情况</td>
            <td style="width:100px;">发生时间</td>
            <td style="width:100px;">发生地区</td>
        </tr>
        #table.0#
        <tr>
            <td>#table.0.omtb_title#</td>
            <td>#table.0.omtb_content#</td>
            <td>#table.0.omtb_date#</td>
            <td>#table.0.omtb_address#</td>
        </tr>
        #table.0#
    </table>
</body>
</html>

 

调用方式

string templatepath = syshelper.getvirtualpath() + "zfb/pro_list_excel.html",
  outfile = "事件汇总表" + datetime.now.tostring("yyyymmddhhmmss") + ".xls";

string excel_file_path = excelhelper.getexcel(dssource, templatepath, outfile);

 

附加获取应用程序虚拟目录方法

public class syshelper
{
    public static string getvirtualpath()
    {
        string path = httpcontext.current.request.applicationpath;
        return path + (path != "/" ? "/" : "");  //以/结尾
    }
}