c# excel导出png_c#根据html模板导出excel
生活随笔
收集整理的這篇文章主要介紹了
c# excel导出png_c#根据html模板导出excel
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
ExcelHelper封裝
public class ExcelHelper{ /// /// 根據html模板文件生成excel文件 /// /// 數據源 /// html模板文件路徑(虛擬路徑而非物理路徑) /// 生成的excel文件名,帶后綴不帶路徑 /// 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; } /// /// 根據模板生成字符換 /// /// /// /// 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模板格式
事件匯總表 事件名稱 事件簡要情況 發生時間 發生地區 #table.0# #table.0.omtb_title# #table.0.omtb_content# #table.0.omtb_date# #table.0.omtb_address# #table.0#調用方式
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 != "/" ? "/" : ""); //以/結尾 }}總結
以上是生活随笔為你收集整理的c# excel导出png_c#根据html模板导出excel的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: share extension 不显示_
- 下一篇: c#图片base64去转义字符_C# 将